Sequencer: initial implementation of multithreaded effects
[blender.git] / source / blender / blenkernel / intern / sequencer.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): 
22  * - Blender Foundation, 2003-2009
23  * - Peter Schlaile <peter [at] schlaile [dot] de> 2005/2006
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/sequencer.c
29  *  \ingroup bke
30  */
31
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38 #include "MEM_CacheLimiterC-Api.h"
39
40 #include "DNA_sequence_types.h"
41 #include "DNA_movieclip_types.h"
42 #include "DNA_mask_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_anim_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_sound_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_fileops.h"
50 #include "BLI_listbase.h"
51 #include "BLI_path_util.h"
52 #include "BLI_string.h"
53 #include "BLI_threads.h"
54 #include "BLI_utildefines.h"
55
56 #include "BKE_animsys.h"
57 #include "BKE_global.h"
58 #include "BKE_image.h"
59 #include "BKE_main.h"
60 #include "BKE_sequencer.h"
61 #include "BKE_movieclip.h"
62 #include "BKE_fcurve.h"
63 #include "BKE_scene.h"
64 #include "BKE_mask.h"
65 #include "BKE_utildefines.h"
66
67 #include "RNA_access.h"
68
69 #include "RE_pipeline.h"
70
71 #include <pthread.h>
72
73 #include "IMB_imbuf.h"
74 #include "IMB_imbuf_types.h"
75
76 #include "BKE_context.h"
77 #include "BKE_sound.h"
78
79 #ifdef WITH_AUDASPACE
80 #  include "AUD_C-API.h"
81 #endif
82
83 static ImBuf *seq_render_strip_stack(SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown);
84 static ImBuf *seq_render_strip(SeqRenderData context, Sequence *seq, float cfra);
85 static void seq_free_animdata(Scene *scene, Sequence *seq);
86
87 /* **** XXX ******** */
88 #define SELECT 1
89 ListBase seqbase_clipboard;
90 int seqbase_clipboard_frame;
91 SequencerDrawView sequencer_view3d_cb = NULL; /* NULL in background mode */
92
93 #if 0  /* unused function */
94 static void printf_strip(Sequence *seq)
95 {
96         fprintf(stderr, "name: '%s', len:%d, start:%d, (startofs:%d, endofs:%d), "
97                 "(startstill:%d, endstill:%d), machine:%d, (startdisp:%d, enddisp:%d)\n",
98                 seq->name, seq->len, seq->start, seq->startofs, seq->endofs, seq->startstill, seq->endstill, seq->machine,
99                 seq->startdisp, seq->enddisp);
100
101         fprintf(stderr, "\tseq_tx_set_final_left: %d %d\n\n", seq_tx_get_final_left(seq, 0),
102                 seq_tx_get_final_right(seq, 0));
103 }
104 #endif
105
106 int BKE_sequencer_base_recursive_apply(ListBase *seqbase, int (*apply_func)(Sequence *seq, void *), void *arg)
107 {
108         Sequence *iseq;
109         for (iseq = seqbase->first; iseq; iseq = iseq->next) {
110                 if (BKE_sequencer_recursive_apply(iseq, apply_func, arg) == -1)
111                         return -1;  /* bail out */
112         }
113         return 1;
114 }
115
116 int BKE_sequencer_recursive_apply(Sequence *seq, int (*apply_func)(Sequence *, void *), void *arg)
117 {
118         int ret = apply_func(seq, arg);
119
120         if (ret == -1)
121                 return -1;  /* bail out */
122
123         if (ret && seq->seqbase.first)
124                 ret = BKE_sequencer_base_recursive_apply(&seq->seqbase, apply_func, arg);
125
126         return ret;
127 }
128
129 /*********************** alloc / free functions *************************/
130
131 /* free */
132
133 static void free_proxy_seq(Sequence *seq)
134 {
135         if (seq->strip && seq->strip->proxy && seq->strip->proxy->anim) {
136                 IMB_free_anim(seq->strip->proxy->anim);
137                 seq->strip->proxy->anim = NULL;
138         }
139 }
140
141 static void seq_free_strip(Strip *strip)
142 {
143         strip->us--;
144         if (strip->us > 0)
145                 return;
146         if (strip->us < 0) {
147                 printf("error: negative users in strip\n");
148                 return;
149         }
150
151         if (strip->stripdata) {
152                 MEM_freeN(strip->stripdata);
153         }
154
155         if (strip->proxy) {
156                 if (strip->proxy->anim) {
157                         IMB_free_anim(strip->proxy->anim);
158                 }
159
160                 MEM_freeN(strip->proxy);
161         }
162         if (strip->crop) {
163                 MEM_freeN(strip->crop);
164         }
165         if (strip->transform) {
166                 MEM_freeN(strip->transform);
167         }
168         if (strip->color_balance) {
169                 MEM_freeN(strip->color_balance);
170         }
171
172         MEM_freeN(strip);
173 }
174
175 void BKE_sequence_free(Scene *scene, Sequence *seq)
176 {
177         if (seq->strip)
178                 seq_free_strip(seq->strip);
179
180         if (seq->anim)
181                 IMB_free_anim(seq->anim);
182
183         if (seq->type & SEQ_TYPE_EFFECT) {
184                 struct SeqEffectHandle sh = BKE_sequence_get_effect(seq);
185
186                 sh.free(seq);
187         }
188
189         if (seq->sound) {
190                 ((ID *)seq->sound)->us--; 
191         }
192
193         /* clipboard has no scene and will never have a sound handle or be active */
194         if (scene) {
195                 Editing *ed = scene->ed;
196
197                 if (ed->act_seq == seq)
198                         ed->act_seq = NULL;
199
200                 if (seq->scene_sound && ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE))
201                         sound_remove_scene_sound(scene, seq->scene_sound);
202
203                 seq_free_animdata(scene, seq);
204         }
205
206         MEM_freeN(seq);
207 }
208
209 static void seq_free_sequence_recurse(Scene *scene, Sequence *seq)
210 {
211         Sequence *iseq;
212
213         for (iseq = seq->seqbase.first; iseq; iseq = iseq->next) {
214                 seq_free_sequence_recurse(scene, iseq);
215         }
216
217         BKE_sequence_free(scene, seq);
218 }
219
220
221 Editing *BKE_sequencer_editing_get(Scene *scene, int alloc)
222 {
223         if (alloc) {
224                 BKE_sequencer_editing_ensure(scene);
225         }
226         return scene->ed;
227 }
228
229 static void seq_free_clipboard_recursive(Sequence *seq_parent)
230 {
231         Sequence *seq, *nseq;
232
233         for (seq = seq_parent->seqbase.first; seq; seq = nseq) {
234                 nseq = seq->next;
235                 seq_free_clipboard_recursive(seq);
236         }
237
238         BKE_sequence_free(NULL, seq_parent);
239 }
240
241 void BKE_sequencer_free_clipboard(void)
242 {
243         Sequence *seq, *nseq;
244
245         for (seq = seqbase_clipboard.first; seq; seq = nseq) {
246                 nseq = seq->next;
247                 seq_free_clipboard_recursive(seq);
248         }
249         seqbase_clipboard.first = seqbase_clipboard.last = NULL;
250 }
251
252 Editing *BKE_sequencer_editing_ensure(Scene *scene)
253 {
254         if (scene->ed == NULL) {
255                 Editing *ed;
256
257                 ed = scene->ed = MEM_callocN(sizeof(Editing), "addseq");
258                 ed->seqbasep = &ed->seqbase;
259         }
260
261         return scene->ed;
262 }
263
264 void BKE_sequencer_editing_free(Scene *scene)
265 {
266         Editing *ed = scene->ed;
267         MetaStack *ms;
268         Sequence *seq;
269
270         if (ed == NULL)
271                 return;
272
273         SEQ_BEGIN (ed, seq)
274         {
275                 BKE_sequence_free(scene, seq);
276         }
277         SEQ_END
278
279         while ((ms = ed->metastack.first)) {
280                 BLI_remlink(&ed->metastack, ms);
281                 MEM_freeN(ms);
282         }
283
284         MEM_freeN(ed);
285
286         scene->ed = NULL;
287 }
288
289 /*********************** sequencer pipeline functions *************************/
290
291 SeqRenderData BKE_sequencer_new_render_data(Main *bmain, Scene *scene, int rectx, int recty, int preview_render_size)
292 {
293         SeqRenderData rval;
294
295         rval.bmain = bmain;
296         rval.scene = scene;
297         rval.rectx = rectx;
298         rval.recty = recty;
299         rval.preview_render_size = preview_render_size;
300         rval.motion_blur_samples = 0;
301         rval.motion_blur_shutter = 0;
302
303         return rval;
304 }
305
306 /* ************************* iterator ************************** */
307 /* *************** (replaces old WHILE_SEQ) ********************* */
308 /* **************** use now SEQ_BEGIN () SEQ_END ***************** */
309
310 /* sequence strip iterator:
311  * - builds a full array, recursively into meta strips
312  */
313
314 static void seq_count(ListBase *seqbase, int *tot)
315 {
316         Sequence *seq;
317
318         for (seq = seqbase->first; seq; seq = seq->next) {
319                 (*tot)++;
320
321                 if (seq->seqbase.first)
322                         seq_count(&seq->seqbase, tot);
323         }
324 }
325
326 static void seq_build_array(ListBase *seqbase, Sequence ***array, int depth)
327 {
328         Sequence *seq;
329
330         for (seq = seqbase->first; seq; seq = seq->next) {
331                 seq->depth = depth;
332
333                 if (seq->seqbase.first)
334                         seq_build_array(&seq->seqbase, array, depth + 1);
335
336                 **array = seq;
337                 (*array)++;
338         }
339 }
340
341 static void seq_array(Editing *ed, Sequence ***seqarray, int *tot, int use_pointer)
342 {
343         Sequence **array;
344
345         *seqarray = NULL;
346         *tot = 0;
347
348         if (ed == NULL)
349                 return;
350
351         if (use_pointer)
352                 seq_count(ed->seqbasep, tot);
353         else
354                 seq_count(&ed->seqbase, tot);
355
356         if (*tot == 0)
357                 return;
358
359         *seqarray = array = MEM_mallocN(sizeof(Sequence *) * (*tot), "SeqArray");
360         if (use_pointer)
361                 seq_build_array(ed->seqbasep, &array, 0);
362         else
363                 seq_build_array(&ed->seqbase, &array, 0);
364 }
365
366 void BKE_seqence_iterator_begin(Editing *ed, SeqIterator *iter, int use_pointer)
367 {
368         memset(iter, 0, sizeof(*iter));
369         seq_array(ed, &iter->array, &iter->tot, use_pointer);
370
371         if (iter->tot) {
372                 iter->cur = 0;
373                 iter->seq = iter->array[iter->cur];
374                 iter->valid = 1;
375         }
376 }
377
378 void BKE_seqence_iterator_next(SeqIterator *iter)
379 {
380         if (++iter->cur < iter->tot)
381                 iter->seq = iter->array[iter->cur];
382         else
383                 iter->valid = 0;
384 }
385
386 void BKE_seqence_iterator_end(SeqIterator *iter)
387 {
388         if (iter->array)
389                 MEM_freeN(iter->array);
390
391         iter->valid = 0;
392 }
393
394 static int metaseq_start(Sequence *metaseq)
395 {
396         return metaseq->start + metaseq->startofs;
397 }
398
399 static int metaseq_end(Sequence *metaseq)
400 {
401         return metaseq->start + metaseq->len - metaseq->endofs;
402 }
403
404 static void seq_update_sound_bounds_recursive_rec(Scene *scene, Sequence *metaseq, int start, int end)
405 {
406         Sequence *seq;
407
408         /* for sound we go over full meta tree to update bounds of the sound strips,
409          * since sound is played outside of evaluating the imbufs, */
410         for (seq = metaseq->seqbase.first; seq; seq = seq->next) {
411                 if (seq->type == SEQ_TYPE_META) {
412                         seq_update_sound_bounds_recursive_rec(scene, seq, maxi(start, metaseq_start(seq)),
413                                                               mini(end, metaseq_end(seq)));
414                 }
415                 else if (ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) {
416                         if (seq->scene_sound) {
417                                 int startofs = seq->startofs;
418                                 int endofs = seq->endofs;
419                                 if (seq->startofs + seq->start < start)
420                                         startofs = start - seq->start;
421
422                                 if (seq->start + seq->len - seq->endofs > end)
423                                         endofs = seq->start + seq->len - end;
424
425                                 sound_move_scene_sound(scene, seq->scene_sound, seq->start + startofs,
426                                                        seq->start + seq->len - endofs, startofs);
427                         }
428                 }
429         }
430 }
431
432 static void seq_update_sound_bounds_recursive(Scene *scene, Sequence *metaseq)
433 {
434         seq_update_sound_bounds_recursive_rec(scene, metaseq, metaseq_start(metaseq), metaseq_end(metaseq));
435 }
436
437 void BKE_sequence_calc_disp(Scene *scene, Sequence *seq)
438 {
439         if (seq->startofs && seq->startstill)
440                 seq->startstill = 0;
441         if (seq->endofs && seq->endstill)
442                 seq->endstill = 0;
443         
444         seq->startdisp = seq->start + seq->startofs - seq->startstill;
445         seq->enddisp = seq->start + seq->len - seq->endofs + seq->endstill;
446         
447         seq->handsize = 10.0;  /* 10 frames */
448         if (seq->enddisp - seq->startdisp < 10) {
449                 seq->handsize = (float)(0.5 * (seq->enddisp - seq->startdisp));
450         }
451         else if (seq->enddisp - seq->startdisp > 250) {
452                 seq->handsize = (float)((seq->enddisp - seq->startdisp) / 25);
453         }
454
455         if (ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) {
456                 BKE_sequencer_update_sound_bounds(scene, seq);
457         }
458         else if (seq->type == SEQ_TYPE_META)
459                 seq_update_sound_bounds_recursive(scene, seq);
460 }
461
462 void BKE_sequence_calc(Scene *scene, Sequence *seq)
463 {
464         Sequence *seqm;
465         int min, max;
466
467         /* check all metas recursively */
468         seqm = seq->seqbase.first;
469         while (seqm) {
470                 if (seqm->seqbase.first) BKE_sequence_calc(scene, seqm);
471                 seqm = seqm->next;
472         }
473
474         /* effects and meta: automatic start and end */
475
476         if (seq->type & SEQ_TYPE_EFFECT) {
477                 /* pointers */
478                 if (seq->seq2 == NULL)
479                         seq->seq2 = seq->seq1;
480                 if (seq->seq3 == NULL)
481                         seq->seq3 = seq->seq1;
482
483                 /* effecten go from seq1 -> seq2: test */
484
485                 /* we take the largest start and smallest end */
486
487                 // seq->start = seq->startdisp = MAX2(seq->seq1->startdisp, seq->seq2->startdisp);
488                 // seq->enddisp = MIN2(seq->seq1->enddisp, seq->seq2->enddisp);
489
490                 if (seq->seq1) {
491                         /* XXX These resets should not be necessary, but users used to be able to
492                          *     edit effect's length, leading to strange results. See [#29190] */
493                         seq->startofs = seq->endofs = seq->startstill = seq->endstill = 0;
494                         seq->start = seq->startdisp = MAX3(seq->seq1->startdisp, seq->seq2->startdisp, seq->seq3->startdisp);
495                         seq->enddisp = MIN3(seq->seq1->enddisp, seq->seq2->enddisp, seq->seq3->enddisp);
496                         /* we cant help if strips don't overlap, it wont give useful results.
497                          * but at least ensure 'len' is never negative which causes bad bugs elsewhere. */
498                         if (seq->enddisp < seq->startdisp) {
499                                 /* simple start/end swap */
500                                 seq->start = seq->enddisp;
501                                 seq->enddisp = seq->startdisp;
502                                 seq->startdisp = seq->start;
503                                 seq->flag |= SEQ_INVALID_EFFECT;
504                         }
505                         else {
506                                 seq->flag &= ~SEQ_INVALID_EFFECT;
507                         }
508
509                         seq->len = seq->enddisp - seq->startdisp;
510                 }
511                 else {
512                         BKE_sequence_calc_disp(scene, seq);
513                 }
514         }
515         else {
516                 if (seq->type == SEQ_TYPE_META) {
517                         seqm = seq->seqbase.first;
518                         if (seqm) {
519                                 min =  MAXFRAME * 2;
520                                 max = -MAXFRAME * 2;
521                                 while (seqm) {
522                                         if (seqm->startdisp < min) min = seqm->startdisp;
523                                         if (seqm->enddisp > max) max = seqm->enddisp;
524                                         seqm = seqm->next;
525                                 }
526                                 seq->start = min + seq->anim_startofs;
527                                 seq->len = max - min;
528                                 seq->len -= seq->anim_startofs;
529                                 seq->len -= seq->anim_endofs;
530                         }
531                         seq_update_sound_bounds_recursive(scene, seq);
532                 }
533                 BKE_sequence_calc_disp(scene, seq);
534         }
535 }
536
537 /* note: caller should run calc_sequence(scene, seq) after */
538 void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, int lock_range)
539 {
540         char str[FILE_MAX];
541         int prev_startdisp = 0, prev_enddisp = 0;
542         /* note: don't rename the strip, will break animation curves */
543
544         if (ELEM7(seq->type,
545                   SEQ_TYPE_MOVIE, SEQ_TYPE_IMAGE, SEQ_TYPE_SOUND_RAM,
546                   SEQ_TYPE_SCENE, SEQ_TYPE_META, SEQ_TYPE_MOVIECLIP, SEQ_TYPE_MASK) == 0)
547         {
548                 return;
549         }
550
551         if (lock_range) {
552                 /* keep so we don't have to move the actual start and end points (only the data) */
553                 BKE_sequence_calc_disp(scene, seq);
554                 prev_startdisp = seq->startdisp;
555                 prev_enddisp = seq->enddisp;
556         }
557
558         switch (seq->type) {
559                 case SEQ_TYPE_IMAGE:
560                 {
561                         /* Hack? */
562                         size_t olen = MEM_allocN_len(seq->strip->stripdata) / sizeof(StripElem);
563
564                         seq->len = olen;
565                         seq->len -= seq->anim_startofs;
566                         seq->len -= seq->anim_endofs;
567                         if (seq->len < 0) {
568                                 seq->len = 0;
569                         }
570                         break;
571                 }
572                 case SEQ_TYPE_MOVIE:
573                         BLI_join_dirfile(str, sizeof(str), seq->strip->dir,
574                                          seq->strip->stripdata->name);
575                         BLI_path_abs(str, G.main->name);
576
577                         if (seq->anim) IMB_free_anim(seq->anim);
578                         seq->anim = openanim(str, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), seq->streamindex);
579
580                         if (!seq->anim) {
581                                 return;
582                         }
583
584                         seq->len = IMB_anim_get_duration(seq->anim, seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN);
585         
586                         seq->anim_preseek = IMB_anim_get_preseek(seq->anim);
587
588                         seq->len -= seq->anim_startofs;
589                         seq->len -= seq->anim_endofs;
590                         if (seq->len < 0) {
591                                 seq->len = 0;
592                         }
593                         break;
594                 case SEQ_TYPE_MOVIECLIP:
595                         seq->len = BKE_movieclip_get_duration(seq->clip);
596
597                         seq->len -= seq->anim_startofs;
598                         seq->len -= seq->anim_endofs;
599                         if (seq->len < 0) {
600                                 seq->len = 0;
601                         }
602                         break;
603                 case SEQ_TYPE_MASK:
604                         seq->len = BKE_mask_get_duration(seq->mask);
605
606                         seq->len -= seq->anim_startofs;
607                         seq->len -= seq->anim_endofs;
608                         if (seq->len < 0) {
609                                 seq->len = 0;
610                         }
611                         break;
612                 case SEQ_TYPE_SOUND_RAM:
613 #ifdef WITH_AUDASPACE
614                         if (!seq->sound)
615                                 return;
616                         seq->len = ceil(AUD_getInfo(seq->sound->playback_handle).length * FPS);
617                         seq->len -= seq->anim_startofs;
618                         seq->len -= seq->anim_endofs;
619                         if (seq->len < 0) {
620                                 seq->len = 0;
621                         }
622 #else
623                         return;
624 #endif
625                         break;
626                 case SEQ_TYPE_SCENE:
627                 {
628                         seq->len = (seq->scene) ? seq->scene->r.efra - seq->scene->r.sfra + 1 : 0;
629                         seq->len -= seq->anim_startofs;
630                         seq->len -= seq->anim_endofs;
631                         if (seq->len < 0) {
632                                 seq->len = 0;
633                         }
634                         break;
635                 }
636         }
637
638         free_proxy_seq(seq);
639
640         if (lock_range) {
641                 BKE_sequence_tx_set_final_left(seq, prev_startdisp);
642                 BKE_sequence_tx_set_final_right(seq, prev_enddisp);
643                 BKE_sequence_single_fix(seq);
644         }
645         
646         BKE_sequence_calc(scene, seq);
647 }
648
649 void BKE_sequencer_sort(Scene *scene)
650 {
651         /* all strips together per kind, and in order of y location ("machine") */
652         ListBase seqbase, effbase;
653         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
654         Sequence *seq, *seqt;
655
656         
657         if (ed == NULL)
658                 return;
659
660         seqbase.first = seqbase.last = NULL;
661         effbase.first = effbase.last = NULL;
662
663         while ( (seq = ed->seqbasep->first) ) {
664                 BLI_remlink(ed->seqbasep, seq);
665
666                 if (seq->type & SEQ_TYPE_EFFECT) {
667                         seqt = effbase.first;
668                         while (seqt) {
669                                 if (seqt->machine >= seq->machine) {
670                                         BLI_insertlinkbefore(&effbase, seqt, seq);
671                                         break;
672                                 }
673                                 seqt = seqt->next;
674                         }
675                         if (seqt == NULL)
676                                 BLI_addtail(&effbase, seq);
677                 }
678                 else {
679                         seqt = seqbase.first;
680                         while (seqt) {
681                                 if (seqt->machine >= seq->machine) {
682                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
683                                         break;
684                                 }
685                                 seqt = seqt->next;
686                         }
687                         if (seqt == NULL)
688                                 BLI_addtail(&seqbase, seq);
689                 }
690         }
691
692         BLI_movelisttolist(&seqbase, &effbase);
693         *(ed->seqbasep) = seqbase;
694 }
695
696 static int clear_scene_in_allseqs_cb(Sequence *seq, void *arg_pt)
697 {
698         if (seq->scene == (Scene *)arg_pt)
699                 seq->scene = NULL;
700         return 1;
701 }
702
703 void BKE_sequencer_clear_scene_in_allseqs(Main *bmain, Scene *scene)
704 {
705         Scene *scene_iter;
706
707         /* when a scene is deleted: test all seqs */
708         for (scene_iter = bmain->scene.first; scene_iter; scene_iter = scene_iter->id.next) {
709                 if (scene_iter != scene && scene_iter->ed) {
710                         BKE_sequencer_base_recursive_apply(&scene_iter->ed->seqbase, clear_scene_in_allseqs_cb, scene);
711                 }
712         }
713 }
714
715 typedef struct SeqUniqueInfo {
716         Sequence *seq;
717         char name_src[SEQ_NAME_MAXSTR];
718         char name_dest[SEQ_NAME_MAXSTR];
719         int count;
720         int match;
721 } SeqUniqueInfo;
722
723 static void seqbase_unique_name(ListBase *seqbasep, SeqUniqueInfo *sui)
724 {
725         Sequence *seq;
726         for (seq = seqbasep->first; seq; seq = seq->next) {
727                 if (sui->seq != seq && strcmp(sui->name_dest, seq->name + 2) == 0) {
728                         /* SEQ_NAME_MAXSTR - 2 for prefix, -1 for \0, -4 for the number */
729                         BLI_snprintf(sui->name_dest, sizeof(sui->name_dest), "%.59s.%03d",  sui->name_src, sui->count++);
730                         sui->match = 1; /* be sure to re-scan */
731                 }
732         }
733 }
734
735 static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt)
736 {
737         if (seq->seqbase.first)
738                 seqbase_unique_name(&seq->seqbase, (SeqUniqueInfo *)arg_pt);
739         return 1;
740 }
741
742 void BKE_seqence_base_unique_name_recursive(ListBase *seqbasep, Sequence *seq)
743 {
744         SeqUniqueInfo sui;
745         char *dot;
746         sui.seq = seq;
747         BLI_strncpy(sui.name_src, seq->name + 2, sizeof(sui.name_src));
748         BLI_strncpy(sui.name_dest, seq->name + 2, sizeof(sui.name_dest));
749
750         sui.count = 1;
751         sui.match = 1; /* assume the worst to start the loop */
752
753         /* Strip off the suffix */
754         if ((dot = strrchr(sui.name_src, '.'))) {
755                 *dot = '\0';
756                 dot++;
757
758                 if (*dot)
759                         sui.count = atoi(dot) + 1;
760         }
761
762         while (sui.match) {
763                 sui.match = 0;
764                 seqbase_unique_name(seqbasep, &sui);
765                 BKE_sequencer_base_recursive_apply(seqbasep, seqbase_unique_name_recursive_cb, &sui);
766         }
767
768         BLI_strncpy(seq->name + 2, sui.name_dest, sizeof(seq->name) - 2);
769 }
770
771 static const char *give_seqname_by_type(int type)
772 {
773         switch (type) {
774                 case SEQ_TYPE_META:       return "Meta";
775                 case SEQ_TYPE_IMAGE:      return "Image";
776                 case SEQ_TYPE_SCENE:      return "Scene";
777                 case SEQ_TYPE_MOVIE:      return "Movie";
778                 case SEQ_TYPE_MOVIECLIP:  return "Clip";
779                 case SEQ_TYPE_MASK:       return "Mask";
780                 case SEQ_TYPE_SOUND_RAM:  return "Audio";
781                 case SEQ_TYPE_CROSS:      return "Cross";
782                 case SEQ_TYPE_GAMCROSS:   return "Gamma Cross";
783                 case SEQ_TYPE_ADD:        return "Add";
784                 case SEQ_TYPE_SUB:        return "Sub";
785                 case SEQ_TYPE_MUL:        return "Mul";
786                 case SEQ_TYPE_ALPHAOVER:  return "Alpha Over";
787                 case SEQ_TYPE_ALPHAUNDER: return "Alpha Under";
788                 case SEQ_TYPE_OVERDROP:   return "Over Drop";
789                 case SEQ_TYPE_WIPE:       return "Wipe";
790                 case SEQ_TYPE_GLOW:       return "Glow";
791                 case SEQ_TYPE_TRANSFORM:  return "Transform";
792                 case SEQ_TYPE_COLOR:      return "Color";
793                 case SEQ_TYPE_MULTICAM:   return "Multicam";
794                 case SEQ_TYPE_ADJUSTMENT: return "Adjustment";
795                 case SEQ_TYPE_SPEED:      return "Speed";
796                 default:
797                         return NULL;
798         }
799 }
800
801 const char *BKE_sequence_give_name(Sequence *seq)
802 {
803         const char *name = give_seqname_by_type(seq->type);
804
805         if (!name) {
806                 if (seq->type < SEQ_TYPE_EFFECT) {
807                         return seq->strip->dir;
808                 }
809                 else {
810                         return "Effect";
811                 }
812         }
813         return name;
814 }
815
816 /*********************** DO THE SEQUENCE *************************/
817
818 static void make_black_ibuf(ImBuf *ibuf)
819 {
820         unsigned int *rect;
821         float *rect_float;
822         int tot;
823
824         if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL)) {
825                 return;
826         }
827
828         tot = ibuf->x * ibuf->y;
829
830         rect = ibuf->rect;
831         rect_float = ibuf->rect_float;
832
833         if (rect) {
834                 memset(rect, 0, tot * sizeof(char) * 4);
835         }
836
837         if (rect_float) {
838                 memset(rect_float, 0, tot * sizeof(float) * 4);
839         }
840 }
841
842 static void multibuf(ImBuf *ibuf, float fmul)
843 {
844         char *rt;
845         float *rt_float;
846
847         int a, mul, icol;
848
849         mul = (int)(256.0f * fmul);
850         rt = (char *)ibuf->rect;
851         rt_float = ibuf->rect_float;
852
853         if (rt) {
854                 a = ibuf->x * ibuf->y;
855                 while (a--) {
856
857                         icol = (mul * rt[0]) >> 8;
858                         if (icol > 254) rt[0] = 255; else rt[0] = icol;
859                         icol = (mul * rt[1]) >> 8;
860                         if (icol > 254) rt[1] = 255; else rt[1] = icol;
861                         icol = (mul * rt[2]) >> 8;
862                         if (icol > 254) rt[2] = 255; else rt[2] = icol;
863                         icol = (mul * rt[3]) >> 8;
864                         if (icol > 254) rt[3] = 255; else rt[3] = icol;
865                         
866                         rt += 4;
867                 }
868         }
869         if (rt_float) {
870                 a = ibuf->x * ibuf->y;
871                 while (a--) {
872                         rt_float[0] *= fmul;
873                         rt_float[1] *= fmul;
874                         rt_float[2] *= fmul;
875                         rt_float[3] *= fmul;
876                         
877                         rt_float += 4;
878                 }
879         }
880 }
881
882 static float give_stripelem_index(Sequence *seq, float cfra)
883 {
884         float nr;
885         int sta = seq->start;
886         int end = seq->start + seq->len - 1;
887
888         if (seq->type & SEQ_TYPE_EFFECT) {
889                 end = seq->enddisp;
890         } 
891
892         if (end < sta) {
893                 return -1;
894         }
895
896         if (seq->flag & SEQ_REVERSE_FRAMES) {
897                 /*reverse frame in this sequence */
898                 if (cfra <= sta) nr = end - sta;
899                 else if (cfra >= end) nr = 0;
900                 else nr = end - cfra;
901         }
902         else {
903                 if (cfra <= sta) nr = 0;
904                 else if (cfra >= end) nr = end - sta;
905                 else nr = cfra - sta;
906         }
907         
908         if (seq->strobe < 1.0f) seq->strobe = 1.0f;
909         
910         if (seq->strobe > 1.0f) {
911                 nr -= fmodf((double)nr, (double)seq->strobe);
912         }
913
914         return nr;
915 }
916
917 StripElem *BKE_sequencer_give_stripelem(Sequence *seq, int cfra)
918 {
919         StripElem *se = seq->strip->stripdata;
920
921         if (seq->type == SEQ_TYPE_IMAGE) {
922                 /* only IMAGE strips use the whole array, MOVIE strips use only the first element,
923                  * all other strips don't use this...
924                  */
925
926                 int nr = (int) give_stripelem_index(seq, cfra);
927
928                 if (nr == -1 || se == NULL)
929                         return NULL;
930         
931                 se += nr + seq->anim_startofs;
932         }
933         return se;
934 }
935
936 static int evaluate_seq_frame_gen(Sequence **seq_arr, ListBase *seqbase, int cfra)
937 {
938         Sequence *seq;
939         int totseq = 0;
940
941         memset(seq_arr, 0, sizeof(Sequence *) * (MAXSEQ + 1));
942
943         seq = seqbase->first;
944         while (seq) {
945                 if (seq->startdisp <= cfra && seq->enddisp > cfra) {
946                         seq_arr[seq->machine] = seq;
947                         totseq++;
948                 }
949                 seq = seq->next;
950         }
951
952         return totseq;
953 }
954
955 int BKE_sequencer_evaluate_frame(Scene *scene, int cfra)
956 {
957         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
958         Sequence *seq_arr[MAXSEQ + 1];
959
960         if (ed == NULL)
961                 return 0;
962
963         return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
964 }
965
966 static int video_seq_is_rendered(Sequence *seq)
967 {
968         return (seq && !(seq->flag & SEQ_MUTE) && seq->type != SEQ_TYPE_SOUND_RAM);
969 }
970
971 static int get_shown_sequences(ListBase *seqbasep, int cfra, int chanshown, Sequence **seq_arr_out)
972 {
973         Sequence *seq_arr[MAXSEQ + 1];
974         int b = chanshown;
975         int cnt = 0;
976
977         if (b > MAXSEQ) {
978                 return 0;
979         }
980
981         if (evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
982                 if (b == 0) {
983                         b = MAXSEQ;
984                 }
985                 for (; b > 0; b--) {
986                         if (video_seq_is_rendered(seq_arr[b])) {
987                                 break;
988                         }
989                 }
990         }
991         
992         chanshown = b;
993
994         for (; b > 0; b--) {
995                 if (video_seq_is_rendered(seq_arr[b])) {
996                         if (seq_arr[b]->blend_mode == SEQ_BLEND_REPLACE) {
997                                 break;
998                         }
999                 }
1000         }
1001
1002         for (; b <= chanshown && b >= 0; b++) {
1003                 if (video_seq_is_rendered(seq_arr[b])) {
1004                         seq_arr_out[cnt++] = seq_arr[b];
1005                 }
1006         }
1007
1008         return cnt;
1009 }
1010
1011 /*********************** proxy management *************************/
1012
1013 typedef struct SeqIndexBuildContext {
1014         struct IndexBuildContext *index_context;
1015
1016         int tc_flags;
1017         int size_flags;
1018         int quality;
1019
1020         Main *bmain;
1021         Scene *scene;
1022         Sequence *seq, *orig_seq;
1023 } SeqIndexBuildContext;
1024
1025 #define PROXY_MAXFILE (2 * FILE_MAXDIR + FILE_MAXFILE)
1026
1027 static IMB_Proxy_Size seq_rendersize_to_proxysize(int size)
1028 {
1029         if (size >= 100) {
1030                 return IMB_PROXY_NONE;
1031         }
1032         if (size >= 99) {
1033                 return IMB_PROXY_100;
1034         }
1035         if (size >= 75) {
1036                 return IMB_PROXY_75;
1037         }
1038         if (size >= 50) {
1039                 return IMB_PROXY_50;
1040         }
1041         return IMB_PROXY_25;
1042 }
1043
1044 static double seq_rendersize_to_scale_factor(int size)
1045 {
1046         if (size >= 99) {
1047                 return 1.0;
1048         }
1049         if (size >= 75) {
1050                 return 0.75;
1051         }
1052         if (size >= 50) {
1053                 return 0.50;
1054         }
1055         return 0.25;
1056 }
1057
1058 static void seq_open_anim_file(Sequence *seq)
1059 {
1060         char name[FILE_MAX];
1061         StripProxy *proxy;
1062
1063         if (seq->anim != NULL) {
1064                 return;
1065         }
1066
1067         BLI_join_dirfile(name, sizeof(name),
1068                          seq->strip->dir, seq->strip->stripdata->name);
1069         BLI_path_abs(name, G.main->name);
1070         
1071         seq->anim = openanim(name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), seq->streamindex);
1072
1073         if (seq->anim == NULL) {
1074                 return;
1075         }
1076
1077         proxy = seq->strip->proxy;
1078
1079         if (proxy == NULL) {
1080                 return;
1081         }
1082
1083         if (seq->flag & SEQ_USE_PROXY_CUSTOM_DIR) {
1084                 char dir[FILE_MAX];
1085                 BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1086                 BLI_path_abs(dir, G.main->name);
1087
1088                 IMB_anim_set_index_dir(seq->anim, dir);
1089         }
1090 }
1091
1092
1093 static int seq_proxy_get_fname(Sequence *seq, int cfra, int render_size, char *name)
1094 {
1095         int frameno;
1096         char dir[PROXY_MAXFILE];
1097
1098         if (!seq->strip->proxy) {
1099                 return FALSE;
1100         }
1101
1102         /* MOVIE tracks (only exception: custom files) are now handled 
1103          * internally by ImBuf module for various reasons: proper time code
1104          * support, quicker index build, using one file instead
1105          * of a full directory of jpeg files, etc. Trying to support old
1106          * and new method at once could lead to funny effects, if people
1107          * have both, a directory full of jpeg files and proxy avis, so
1108          * sorry folks, please rebuild your proxies... */
1109
1110         if (seq->flag & (SEQ_USE_PROXY_CUSTOM_DIR | SEQ_USE_PROXY_CUSTOM_FILE)) {
1111                 BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1112         }
1113         else if (seq->type == SEQ_TYPE_IMAGE) {
1114                 BLI_snprintf(dir, PROXY_MAXFILE, "%s/BL_proxy", seq->strip->dir);
1115         }
1116         else {
1117                 return FALSE;
1118         }
1119
1120         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1121                 BLI_join_dirfile(name, PROXY_MAXFILE,
1122                                  dir, seq->strip->proxy->file);
1123                 BLI_path_abs(name, G.main->name);
1124
1125                 return TRUE;
1126         }
1127
1128         /* generate a separate proxy directory for each preview size */
1129
1130         if (seq->type == SEQ_TYPE_IMAGE) {
1131                 BLI_snprintf(name, PROXY_MAXFILE, "%s/images/%d/%s_proxy", dir,
1132                              render_size,
1133                              BKE_sequencer_give_stripelem(seq, cfra)->name);
1134                 frameno = 1;
1135         }
1136         else {
1137                 frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1138                 BLI_snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####", dir, 
1139                              render_size);
1140         }
1141
1142         BLI_path_abs(name, G.main->name);
1143         BLI_path_frame(name, frameno, 0);
1144
1145         strcat(name, ".jpg");
1146
1147         return TRUE;
1148 }
1149
1150 static ImBuf *seq_proxy_fetch(SeqRenderData context, Sequence *seq, int cfra)
1151 {
1152         char name[PROXY_MAXFILE];
1153         IMB_Proxy_Size psize = seq_rendersize_to_proxysize(context.preview_render_size);
1154         int size_flags;
1155         int render_size = context.preview_render_size;
1156
1157         /* dirty hack to distinguish 100% render size from PROXY_100 */
1158         if (render_size == 99) {
1159                 render_size = 100;
1160         }
1161
1162         if (!(seq->flag & SEQ_USE_PROXY)) {
1163                 return NULL;
1164         }
1165
1166         size_flags = seq->strip->proxy->build_size_flags;
1167
1168         /* only use proxies, if they are enabled (even if present!) */
1169         if (psize == IMB_PROXY_NONE || ((size_flags & psize) != psize)) {
1170                 return NULL;
1171         }
1172
1173         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1174                 int frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1175                 if (seq->strip->proxy->anim == NULL) {
1176                         if (seq_proxy_get_fname(seq, cfra, render_size, name) == 0) {
1177                                 return NULL;
1178                         }
1179  
1180                         seq->strip->proxy->anim = openanim(name, IB_rect, 0);
1181                 }
1182                 if (seq->strip->proxy->anim == NULL) {
1183                         return NULL;
1184                 }
1185  
1186                 seq_open_anim_file(seq);
1187
1188                 frameno = IMB_anim_index_get_frame_index(seq->anim, seq->strip->proxy->tc,
1189                                                          frameno);
1190
1191                 return IMB_anim_absolute(seq->strip->proxy->anim, frameno,
1192                                          IMB_TC_NONE, IMB_PROXY_NONE);
1193         }
1194  
1195         if (seq_proxy_get_fname(seq, cfra, render_size, name) == 0) {
1196                 return NULL;
1197         }
1198
1199         if (BLI_exists(name)) {
1200                 return IMB_loadiffname(name, IB_rect);
1201         }
1202         else {
1203                 return NULL;
1204         }
1205 }
1206
1207 static void seq_proxy_build_frame(SeqRenderData context, Sequence *seq, int cfra, int proxy_render_size)
1208 {
1209         char name[PROXY_MAXFILE];
1210         int quality;
1211         int rectx, recty;
1212         int ok;
1213         ImBuf *ibuf;
1214
1215         if (!seq_proxy_get_fname(seq, cfra, proxy_render_size, name)) {
1216                 return;
1217         }
1218
1219         ibuf = seq_render_strip(context, seq, cfra);
1220
1221         rectx = (proxy_render_size * context.scene->r.xsch) / 100;
1222         recty = (proxy_render_size * context.scene->r.ysch) / 100;
1223
1224         if (ibuf->x != rectx || ibuf->y != recty) {
1225                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1226         }
1227
1228         /* depth = 32 is intentionally left in, otherwise ALPHA channels
1229          * won't work... */
1230         quality = seq->strip->proxy->quality;
1231         ibuf->ftype = JPG | quality;
1232
1233         /* unsupported feature only confuses other s/w */
1234         if (ibuf->planes == 32)
1235                 ibuf->planes = 24;
1236
1237         BLI_make_existing_file(name);
1238         
1239         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1240         if (ok == 0) {
1241                 perror(name);
1242         }
1243
1244         IMB_freeImBuf(ibuf);
1245 }
1246
1247 SeqIndexBuildContext *BKE_sequencer_proxy_rebuild_context(Main *bmain, Scene *scene, Sequence *seq)
1248 {
1249         SeqIndexBuildContext *context;
1250         Sequence *nseq;
1251
1252         if (!seq->strip || !seq->strip->proxy) {
1253                 return NULL;
1254         }
1255
1256         if (!(seq->flag & SEQ_USE_PROXY)) {
1257                 return NULL;
1258         }
1259
1260         context = MEM_callocN(sizeof(SeqIndexBuildContext), "seq proxy rebuild context");
1261
1262         nseq = BKE_sequence_dupli_recursive(scene, scene, seq, 0);
1263
1264         context->tc_flags   = nseq->strip->proxy->build_tc_flags;
1265         context->size_flags = nseq->strip->proxy->build_size_flags;
1266         context->quality    = nseq->strip->proxy->quality;
1267
1268         context->bmain = bmain;
1269         context->scene = scene;
1270         context->orig_seq = seq;
1271         context->seq = nseq;
1272
1273         if (nseq->type == SEQ_TYPE_MOVIE) {
1274                 seq_open_anim_file(nseq);
1275
1276                 if (nseq->anim) {
1277                         context->index_context = IMB_anim_index_rebuild_context(nseq->anim,
1278                                 context->tc_flags, context->size_flags, context->quality);
1279                 }
1280         }
1281
1282         return context;
1283 }
1284
1285 void BKE_sequencer_proxy_rebuild(SeqIndexBuildContext *context, short *stop, short *do_update, float *progress)
1286 {
1287         SeqRenderData render_context;
1288         Sequence *seq = context->seq;
1289         Scene *scene = context->scene;
1290         int cfra;
1291
1292         if (seq->type == SEQ_TYPE_MOVIE) {
1293                 if (context->index_context) {
1294                         IMB_anim_index_rebuild(context->index_context, stop, do_update, progress);
1295                 }
1296
1297                 return;
1298         }
1299
1300         if (!(seq->flag & SEQ_USE_PROXY)) {
1301                 return;
1302         }
1303
1304         /* that's why it is called custom... */
1305         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1306                 return;
1307         }
1308
1309         /* fail safe code */
1310
1311         render_context = BKE_sequencer_new_render_data(context->bmain, context->scene,
1312                                             (scene->r.size * (float) scene->r.xsch) / 100.0f + 0.5f,
1313                                             (scene->r.size * (float) scene->r.ysch) / 100.0f + 0.5f, 100);
1314
1315         for (cfra = seq->startdisp + seq->startstill;  cfra < seq->enddisp - seq->endstill; cfra++) {
1316                 if (context->size_flags & IMB_PROXY_25) {
1317                         seq_proxy_build_frame(render_context, seq, cfra, 25);
1318                 }
1319                 if (context->size_flags & IMB_PROXY_50) {
1320                         seq_proxy_build_frame(render_context, seq, cfra, 50);
1321                 }
1322                 if (context->size_flags & IMB_PROXY_75) {
1323                         seq_proxy_build_frame(render_context, seq, cfra, 75);
1324                 }
1325                 if (context->size_flags & IMB_PROXY_100) {
1326                         seq_proxy_build_frame(render_context, seq, cfra, 100);
1327                 }
1328
1329                 *progress = (float) cfra / (seq->enddisp - seq->endstill - seq->startdisp + seq->startstill);
1330                 *do_update = TRUE;
1331
1332                 if (*stop || G.afbreek)
1333                         break;
1334         }
1335 }
1336
1337 void BKE_sequencer_proxy_rebuild_finish(SeqIndexBuildContext *context, short stop)
1338 {
1339         if (context->index_context) {
1340                 IMB_close_anim_proxies(context->seq->anim);
1341                 IMB_close_anim_proxies(context->orig_seq->anim);
1342                 IMB_anim_index_rebuild_finish(context->index_context, stop);
1343         }
1344
1345         seq_free_sequence_recurse(context->scene, context->seq);
1346
1347         MEM_freeN(context);
1348 }
1349
1350 /*********************** color balance *************************/
1351
1352 static StripColorBalance calc_cb(StripColorBalance *cb_)
1353 {
1354         StripColorBalance cb = *cb_;
1355         int c;
1356
1357         for (c = 0; c < 3; c++) {
1358                 cb.lift[c] = 2.0f - cb.lift[c];
1359         }
1360
1361         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1362                 for (c = 0; c < 3; c++) {
1363                         /* tweak to give more subtle results
1364                          * values above 1.0 are scaled */
1365                         if (cb.lift[c] > 1.0f)
1366                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0;
1367
1368                         cb.lift[c] = 2.0f - cb.lift[c];
1369                 }
1370         }
1371
1372         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1373                 for (c = 0; c < 3; c++) {
1374                         if (cb.gain[c] != 0.0f) {
1375                                 cb.gain[c] = 1.0f / cb.gain[c];
1376                         }
1377                         else {
1378                                 cb.gain[c] = 1000000; /* should be enough :) */
1379                         }
1380                 }
1381         }
1382
1383         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1384                 for (c = 0; c < 3; c++) {
1385                         if (cb.gamma[c] != 0.0f) {
1386                                 cb.gamma[c] = 1.0f / cb.gamma[c];
1387                         }
1388                         else {
1389                                 cb.gamma[c] = 1000000; /* should be enough :) */
1390                         }
1391                 }
1392         }
1393
1394         return cb;
1395 }
1396
1397 /* note: lift is actually 2-lift */
1398 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1399 {
1400         float x = (((in - 1.0f) * lift) + 1.0f) * gain;
1401
1402         /* prevent NaN */
1403         if (x < 0.f)
1404                 x = 0.f;
1405
1406         return powf(x, gamma) * mul;
1407 }
1408
1409 static void make_cb_table_byte(float lift, float gain, float gamma,
1410                                unsigned char *table, float mul)
1411 {
1412         int y;
1413
1414         for (y = 0; y < 256; y++) {
1415                 float v = color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1416
1417                 table[y] = FTOCHAR(v);
1418         }
1419 }
1420
1421 static void make_cb_table_float(float lift, float gain, float gamma,
1422                                 float *table, float mul)
1423 {
1424         int y;
1425
1426         for (y = 0; y < 256; y++) {
1427                 float v = color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1428
1429                 table[y] = v;
1430         }
1431 }
1432
1433 static void color_balance_byte_byte(Sequence *seq, unsigned char *rect, int width, int height, float mul)
1434 {
1435         unsigned char cb_tab[3][256];
1436         int c;
1437         unsigned char *p = rect;
1438         unsigned char *e = p + width * 4 * height;
1439
1440         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1441
1442         for (c = 0; c < 3; c++) {
1443                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1444         }
1445
1446         while (p < e) {
1447                 p[0] = cb_tab[0][p[0]];
1448                 p[1] = cb_tab[1][p[1]];
1449                 p[2] = cb_tab[2][p[2]];
1450                 
1451                 p += 4;
1452         }
1453 }
1454
1455 static void color_balance_byte_float(Sequence *seq, unsigned char *rect, float *rect_float, int width, int height, float mul)
1456 {
1457         float cb_tab[4][256];
1458         int c, i;
1459         unsigned char *p = rect;
1460         unsigned char *e = p + width * 4 * height;
1461         float *o;
1462         StripColorBalance cb;
1463
1464         o = rect_float;
1465
1466         cb = calc_cb(seq->strip->color_balance);
1467
1468         for (c = 0; c < 3; c++) {
1469                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1470         }
1471
1472         for (i = 0; i < 256; i++) {
1473                 cb_tab[3][i] = ((float)i) * (1.0f / 255.0f);
1474         }
1475
1476         while (p < e) {
1477                 o[0] = cb_tab[0][p[0]];
1478                 o[1] = cb_tab[1][p[1]];
1479                 o[2] = cb_tab[2][p[2]];
1480                 o[3] = cb_tab[3][p[3]];
1481
1482                 p += 4; o += 4;
1483         }
1484 }
1485
1486 static void color_balance_float_float(Sequence *seq, float *rect_float, int width, int height, float mul)
1487 {
1488         float *p = rect_float;
1489         float *e = rect_float + width * 4 * height;
1490         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1491
1492         while (p < e) {
1493                 int c;
1494                 for (c = 0; c < 3; c++) {
1495                         p[c] = color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1496                 }
1497                 p += 4;
1498         }
1499 }
1500
1501 typedef struct ColorBalanceInitData {
1502         Sequence *seq;
1503         ImBuf *ibuf;
1504         float mul;
1505 } ColorBalanceInitData;
1506
1507 typedef struct ColorBalanceThread {
1508         Sequence *seq;
1509         float mul;
1510
1511         int width, height;
1512
1513         unsigned char *rect;
1514         float *rect_float;
1515 } ColorBalanceThread;
1516
1517 static void color_balance_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1518 {
1519         ColorBalanceThread *handle = (ColorBalanceThread *) handle_v;
1520         ColorBalanceInitData *init_data = (ColorBalanceInitData *) init_data_v;
1521         ImBuf *ibuf = init_data->ibuf;
1522
1523         int offset = 4 * start_line * ibuf->x;
1524
1525         memset(handle, 0, sizeof(ColorBalanceThread));
1526
1527         handle->seq = init_data->seq;
1528         handle->mul = init_data->mul;
1529         handle->width = ibuf->x;
1530         handle->height = tot_line;
1531
1532         if (ibuf->rect)
1533                 handle->rect = (unsigned char *) ibuf->rect + offset;
1534
1535         if (ibuf->rect_float)
1536                 handle->rect_float = ibuf->rect_float + offset;
1537 }
1538
1539 static void *color_balance_do_thread(void *thread_data_v)
1540 {
1541         ColorBalanceThread *thread_data = (ColorBalanceThread *) thread_data_v;
1542         Sequence *seq = thread_data->seq;
1543         int width = thread_data->width, height = thread_data->height;
1544         unsigned char *rect = thread_data->rect;
1545         float *rect_float = thread_data->rect_float;
1546         float mul = thread_data->mul;
1547
1548         if (rect_float) {
1549                 color_balance_float_float(seq, rect_float, width, height, mul);
1550         }
1551         else if (seq->flag & SEQ_MAKE_FLOAT) {
1552                 color_balance_byte_float(seq, rect, rect_float, width, height, mul);
1553         }
1554         else {
1555                 color_balance_byte_byte(seq, rect, width, height, mul);
1556         }
1557
1558         return NULL;
1559 }
1560
1561 static void color_balance(Sequence *seq, ImBuf *ibuf, float mul)
1562 {
1563         if (!ibuf->rect_float && seq->flag & SEQ_MAKE_FLOAT)
1564                 imb_addrectfloatImBuf(ibuf);
1565
1566         if (BLI_thread_is_main()) {
1567                 /* color balance could have been called from prefetching job which
1568                  * is already multithreaded, so doing threading here makes no sense
1569                  */
1570                 ColorBalanceInitData init_data;
1571
1572                 init_data.seq = seq;
1573                 init_data.ibuf = ibuf;
1574                 init_data.mul = mul;
1575
1576                 IMB_processor_apply_threaded(ibuf->y, sizeof(ColorBalanceThread), &init_data,
1577                                          color_balance_init_handle, color_balance_do_thread);
1578
1579         }
1580         else {
1581                 ColorBalanceThread handle;
1582
1583                 handle.seq = seq;
1584                 handle.mul = mul;
1585                 handle.width = ibuf->x;
1586                 handle.height = ibuf->y;
1587                 handle.rect = (unsigned char *)ibuf->rect;
1588                 handle.rect_float = ibuf->rect_float;
1589
1590                 color_balance_do_thread(&handle);
1591         }
1592 }
1593
1594 /*
1595  *  input preprocessing for SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP and SEQ_TYPE_SCENE
1596  *
1597  *  Do all the things you can't really do afterwards using sequence effects
1598  *  (read: before rescaling to render resolution has been done)
1599  *
1600  *  Order is important!
1601  *
1602  *  - Deinterlace
1603  *  - Crop and transform in image source coordinate space
1604  *  - Flip X + Flip Y (could be done afterwards, backward compatibility)
1605  *  - Promote image to float data (affects pipeline operations afterwards)
1606  *  - Color balance (is most efficient in the byte -> float
1607  *    (future: half -> float should also work fine!)
1608  *    case, if done on load, since we can use lookup tables)
1609  *  - Premultiply
1610  */
1611
1612 int BKE_sequencer_input_have_to_preprocess(SeqRenderData UNUSED(context), Sequence *seq, float UNUSED(cfra))
1613 {
1614         float mul;
1615
1616         if (seq->flag & (SEQ_FILTERY | SEQ_USE_CROP | SEQ_USE_TRANSFORM | SEQ_FLIPX |
1617                          SEQ_FLIPY | SEQ_USE_COLOR_BALANCE | SEQ_MAKE_PREMUL))
1618         {
1619                 return TRUE;
1620         }
1621
1622         mul = seq->mul;
1623
1624         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
1625                 mul *= seq->blend_opacity / 100.0f;
1626         }
1627
1628         if (mul != 1.0f) {
1629                 return TRUE;
1630         }
1631
1632         if (seq->sat != 1.0f) {
1633                 return TRUE;
1634         }
1635                 
1636         return FALSE;
1637 }
1638
1639 static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf *ibuf,
1640                                int is_proxy_image, int is_preprocessed)
1641 {
1642         float mul;
1643
1644         ibuf = IMB_makeSingleUser(ibuf);
1645
1646         if ((seq->flag & SEQ_FILTERY) &&
1647             !ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP))
1648         {
1649                 IMB_filtery(ibuf);
1650         }
1651
1652         if (seq->flag & (SEQ_USE_CROP | SEQ_USE_TRANSFORM)) {
1653                 StripCrop c = {0};
1654                 StripTransform t = {0};
1655                 int sx, sy, dx, dy;
1656                 double xscale = 1.0;
1657                 double yscale = 1.0;
1658
1659                 if (is_proxy_image) {
1660                         double f = seq_rendersize_to_scale_factor(context.preview_render_size);
1661
1662                         if (f != 1.0) {
1663                                 IMB_scalefastImBuf(ibuf, ibuf->x / f, ibuf->y / f);
1664                         }
1665                 }
1666
1667                 if (seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1668                         c = *seq->strip->crop;
1669                 }
1670                 if (seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1671                         t = *seq->strip->transform;
1672                 }
1673
1674                 xscale = context.scene->r.xsch ? ((double) context.rectx / (double) context.scene->r.xsch) : 1.0;
1675                 yscale = context.scene->r.ysch ? ((double) context.recty / (double) context.scene->r.ysch) : 1.0;
1676
1677                 c.left *= xscale; c.right *= xscale;
1678                 c.top *= yscale; c.bottom *= yscale;
1679
1680                 t.xofs *= xscale; t.yofs *= yscale;
1681
1682                 sx = ibuf->x - c.left - c.right;
1683                 sy = ibuf->y - c.top - c.bottom;
1684                 dx = sx;
1685                 dy = sy;
1686
1687                 if (seq->flag & SEQ_USE_TRANSFORM) {
1688                         if (is_preprocessed) {
1689                                 dx = context.rectx;
1690                                 dy = context.recty;
1691                         }
1692                         else {
1693                                 dx = context.scene->r.xsch;
1694                                 dy = context.scene->r.ysch;
1695                         }
1696                 }
1697
1698                 if (c.top  + c.bottom >= ibuf->y ||
1699                     c.left + c.right  >= ibuf->x ||
1700                     t.xofs >= dx || t.yofs >= dy)
1701                 {
1702                         make_black_ibuf(ibuf);
1703                 }
1704                 else {
1705                         ImBuf *i = IMB_allocImBuf(dx, dy, 32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1706
1707                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1708                         
1709                         IMB_freeImBuf(ibuf);
1710
1711                         ibuf = i;
1712                 }
1713         } 
1714
1715         if (seq->flag & SEQ_FLIPX) {
1716                 IMB_flipx(ibuf);
1717         }
1718         
1719         if (seq->flag & SEQ_FLIPY) {
1720                 IMB_flipy(ibuf);
1721         }
1722
1723         if (seq->sat != 1.0f) {
1724                 IMB_saturation(ibuf, seq->sat);
1725         }
1726
1727         mul = seq->mul;
1728
1729         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
1730                 mul *= seq->blend_opacity / 100.0f;
1731         }
1732
1733         if (seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1734                 color_balance(seq, ibuf, mul);
1735                 mul = 1.0;
1736         }
1737
1738         if (seq->flag & SEQ_MAKE_FLOAT) {
1739                 if (!ibuf->rect_float)
1740                         IMB_float_from_rect_simple(ibuf);
1741
1742                 if (ibuf->rect) {
1743                         imb_freerectImBuf(ibuf);
1744                 }
1745         }
1746
1747         if (mul != 1.0f) {
1748                 multibuf(ibuf, mul);
1749         }
1750
1751         if (seq->flag & SEQ_MAKE_PREMUL) {
1752                 if (ibuf->planes == 32 && ibuf->zbuf == NULL) {
1753                         IMB_premultiply_alpha(ibuf);
1754                 }
1755         }
1756
1757
1758         if (ibuf->x != context.rectx || ibuf->y != context.recty) {
1759                 if (context.scene->r.mode & R_OSA) {
1760                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1761                 }
1762                 else {
1763                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1764                 }
1765         }
1766         return ibuf;
1767 }
1768
1769 static ImBuf *copy_from_ibuf_still(SeqRenderData context, Sequence *seq, float nr)
1770 {
1771         ImBuf *rval = NULL;
1772         ImBuf *ibuf = NULL;
1773
1774         if (nr == 0) {
1775                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL);
1776         }
1777         else if (nr == seq->len - 1) {
1778                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL);
1779         }
1780
1781         if (ibuf) {
1782                 rval = IMB_dupImBuf(ibuf);
1783                 IMB_freeImBuf(ibuf);
1784         }
1785
1786         return rval;
1787 }
1788
1789 static void copy_to_ibuf_still(SeqRenderData context, Sequence *seq, float nr, ImBuf *ibuf)
1790 {
1791         if (nr == 0 || nr == seq->len - 1) {
1792                 /* we have to store a copy, since the passed ibuf
1793                  * could be preprocessed afterwards (thereby silently
1794                  * changing the cached image... */
1795                 ibuf = IMB_dupImBuf(ibuf);
1796
1797                 if (nr == 0) {
1798                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
1799                 } 
1800
1801                 if (nr == seq->len - 1) {
1802                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
1803                 }
1804
1805                 IMB_freeImBuf(ibuf);
1806         }
1807 }
1808
1809 /*********************** strip rendering functions  *************************/
1810
1811 typedef struct RenderEffectInitData {
1812         struct SeqEffectHandle *sh;
1813         SeqRenderData context;
1814         Sequence *seq;
1815         float cfra, facf0, facf1;
1816         ImBuf *ibuf1, *ibuf2, *ibuf3;
1817
1818         ImBuf *out;
1819 } RenderEffectInitData;
1820
1821 typedef struct RenderEffectThread {
1822         struct SeqEffectHandle *sh;
1823         SeqRenderData context;
1824         Sequence *seq;
1825         float cfra, facf0, facf1;
1826         ImBuf *ibuf1, *ibuf2, *ibuf3;
1827
1828         ImBuf *out;
1829         int start_line, tot_line;
1830 } RenderEffectThread;
1831
1832 static void render_effect_execute_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1833 {
1834         RenderEffectThread *handle = (RenderEffectThread *) handle_v;
1835         RenderEffectInitData *init_data = (RenderEffectInitData *) init_data_v;
1836
1837         handle->sh = init_data->sh;
1838         handle->context = init_data->context;
1839         handle->seq = init_data->seq;
1840         handle->cfra = init_data->cfra;
1841         handle->facf0 = init_data->facf0;
1842         handle->facf1 = init_data->facf1;
1843         handle->ibuf1 = init_data->ibuf1;
1844         handle->ibuf2 = init_data->ibuf2;
1845         handle->ibuf3 = init_data->ibuf3;
1846         handle->out = init_data->out;
1847
1848         handle->start_line = start_line;
1849         handle->tot_line = tot_line;
1850 }
1851
1852 static void *render_effect_execute_do_thread(void *thread_data_v)
1853 {
1854         RenderEffectThread *thread_data = (RenderEffectThread *) thread_data_v;
1855
1856         thread_data->sh->execute_slice(thread_data->context, thread_data->seq, thread_data->cfra,
1857                                        thread_data->facf0, thread_data->facf1, thread_data->ibuf1,
1858                                        thread_data->ibuf2, thread_data->ibuf3, thread_data->start_line,
1859                                        thread_data->tot_line, thread_data->out);
1860
1861         return NULL;
1862 }
1863
1864 static ImBuf *seq_render_effect_execute_threaded(struct SeqEffectHandle *sh, SeqRenderData context, Sequence *seq,
1865                                                  float cfra, float facf0, float facf1,
1866                                                  ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
1867 {
1868         RenderEffectInitData init_data;
1869         ImBuf *out = sh->init_execution(context, ibuf1, ibuf2, ibuf3);
1870
1871         init_data.sh = sh;
1872         init_data.context = context;
1873         init_data.seq = seq;
1874         init_data.cfra = cfra;
1875         init_data.facf0 = facf0;
1876         init_data.facf1 = facf1;
1877         init_data.ibuf1 = ibuf1;
1878         init_data.ibuf2 = ibuf2;
1879         init_data.ibuf3 = ibuf3;
1880         init_data.out = out;
1881
1882         IMB_processor_apply_threaded(out->y, sizeof(RenderEffectThread), &init_data,
1883                                  render_effect_execute_init_handle, render_effect_execute_do_thread);
1884
1885         return out;
1886 }
1887
1888 static ImBuf *seq_render_effect_strip_impl(SeqRenderData context, Sequence *seq, float cfra)
1889 {
1890         float fac, facf;
1891         int early_out;
1892         int i;
1893         struct SeqEffectHandle sh = BKE_sequence_get_effect(seq);
1894         FCurve *fcu = NULL;
1895         ImBuf *ibuf[3];
1896         Sequence *input[3];
1897         ImBuf *out = NULL;
1898
1899         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1900
1901         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1902
1903         if (!sh.execute && !(sh.execute_slice && sh.init_execution)) {
1904                 /* effect not supported in this version... */
1905                 out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
1906                 return out;
1907         }
1908
1909         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1910                 sh.get_default_fac(seq, cfra, &fac, &facf);
1911                 
1912                 if ((context.scene->r.mode & R_FIELDS) == 0)
1913                         facf = fac;
1914         }
1915         else {
1916                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0, NULL);
1917                 if (fcu) {
1918                         fac = facf = evaluate_fcurve(fcu, cfra);
1919                         if (context.scene->r.mode & R_FIELDS) {
1920                                 facf = evaluate_fcurve(fcu, cfra + 0.5f);
1921                         }
1922                 }
1923                 else {
1924                         fac = facf = seq->effect_fader;
1925                 }
1926         }
1927
1928         early_out = sh.early_out(seq, fac, facf);
1929
1930         switch (early_out) {
1931                 case EARLY_NO_INPUT:
1932                         out = sh.execute(context, seq, cfra, fac, facf, NULL, NULL, NULL);
1933                         break;
1934                 case EARLY_DO_EFFECT:
1935                         for (i = 0; i < 3; i++) {
1936                                 if (input[i])
1937                                         ibuf[i] = seq_render_strip(context, input[i], cfra);
1938                         }
1939
1940                         if (ibuf[0] && ibuf[1]) {
1941                                 if (sh.multithreaded)
1942                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
1943                                 else
1944                                         out = sh.execute(context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
1945                         }
1946                         break;
1947                 case EARLY_USE_INPUT_1:
1948                         if (input[0]) {
1949                                 ibuf[0] = seq_render_strip(context, input[0], cfra);
1950                         }
1951                         if (ibuf[0]) {
1952                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
1953                                         out = IMB_dupImBuf(ibuf[0]);
1954                                 }
1955                                 else {
1956                                         out = ibuf[0];
1957                                         IMB_refImBuf(out);
1958                                 }
1959                         }
1960                         break;
1961                 case EARLY_USE_INPUT_2:
1962                         if (input[1]) {
1963                                 ibuf[1] = seq_render_strip(context, input[1], cfra);
1964                         }
1965                         if (ibuf[1]) {
1966                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
1967                                         out = IMB_dupImBuf(ibuf[1]);
1968                                 }
1969                                 else {
1970                                         out = ibuf[1];
1971                                         IMB_refImBuf(out);
1972                                 }
1973                         }
1974                         break;
1975         }
1976
1977         for (i = 0; i < 3; i++) {
1978                 IMB_freeImBuf(ibuf[i]);
1979         }
1980
1981         if (out == NULL) {
1982                 out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
1983         }
1984
1985         return out;
1986 }
1987
1988 static ImBuf *seq_render_movieclip_strip(SeqRenderData context, Sequence *seq, float nr)
1989 {
1990         ImBuf *ibuf = NULL;
1991         MovieClipUser user;
1992         float tloc[2], tscale, tangle;
1993
1994         if (!seq->clip) {
1995                 return NULL;
1996         }
1997
1998         memset(&user, 0, sizeof(MovieClipUser));
1999         
2000         BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs);
2001
2002         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
2003
2004         switch (seq_rendersize_to_proxysize(context.preview_render_size)) {
2005                 case IMB_PROXY_NONE:
2006                         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
2007                         break;
2008                 case IMB_PROXY_100:
2009                         user.render_size = MCLIP_PROXY_RENDER_SIZE_100;
2010                         break;
2011                 case IMB_PROXY_75:
2012                         user.render_size = MCLIP_PROXY_RENDER_SIZE_75;
2013                         break;
2014                 case IMB_PROXY_50:
2015                         user.render_size = MCLIP_PROXY_RENDER_SIZE_50;
2016                         break;
2017                 case IMB_PROXY_25:
2018                         user.render_size = MCLIP_PROXY_RENDER_SIZE_25;
2019                         break;
2020         }
2021
2022         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_UNDISTORTED) {
2023                 user.render_flag = MCLIP_PROXY_RENDER_UNDISTORT;
2024         }
2025
2026         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_STABILIZED) {
2027                 ibuf = BKE_movieclip_get_stable_ibuf(seq->clip, &user, tloc, &tscale, &tangle, 0);
2028         }
2029         else {
2030                 ibuf = BKE_movieclip_get_ibuf_flag(seq->clip, &user, 0, MOVIECLIP_CACHE_SKIP);
2031         }
2032
2033         return ibuf;
2034 }
2035
2036
2037 static ImBuf *seq_render_mask_strip(SeqRenderData context, Sequence *seq, float nr)
2038 {
2039         /* TODO - add option to rasterize to alpha imbuf? */
2040         ImBuf *ibuf = NULL;
2041         float *maskbuf;
2042         int i;
2043
2044         if (!seq->mask) {
2045                 return NULL;
2046         }
2047         else {
2048                 Mask *mask_temp;
2049                 MaskRasterHandle *mr_handle;
2050
2051                 mask_temp = BKE_mask_copy_nolib(seq->mask);
2052
2053                 BKE_mask_evaluate(mask_temp, seq->mask->sfra + nr, TRUE);
2054
2055                 maskbuf = MEM_mallocN(sizeof(float) * context.rectx * context.recty, __func__);
2056
2057                 mr_handle = BKE_maskrasterize_handle_new();
2058
2059                 BKE_maskrasterize_handle_init(mr_handle, mask_temp, context.rectx, context.recty, TRUE, TRUE, TRUE);
2060
2061                 BKE_mask_free(mask_temp);
2062                 MEM_freeN(mask_temp);
2063
2064                 BKE_maskrasterize_buffer(mr_handle, context.rectx, context.recty, maskbuf);
2065
2066                 BKE_maskrasterize_handle_free(mr_handle);
2067         }
2068
2069
2070         if (seq->flag & SEQ_MAKE_FLOAT) {
2071                 /* pixels */
2072                 float *fp_src;
2073                 float *fp_dst;
2074
2075                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rectfloat);
2076
2077                 fp_src = maskbuf;
2078                 fp_dst = ibuf->rect_float;
2079                 i = context.rectx * context.recty;
2080                 while (--i) {
2081                         fp_dst[0] = fp_dst[1] = fp_dst[2] = *fp_src;
2082                         fp_dst[3] = 1.0f;
2083
2084                         fp_src += 1;
2085                         fp_dst += 4;
2086                 }
2087         }
2088         else {
2089                 /* pixels */
2090                 float *fp_src;
2091                 unsigned char *ub_dst;
2092
2093                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2094
2095                 fp_src = maskbuf;
2096                 ub_dst = (unsigned char *)ibuf->rect;
2097                 i = context.rectx * context.recty;
2098                 while (--i) {
2099                         ub_dst[0] = ub_dst[1] = ub_dst[2] = (unsigned char)(*fp_src * 255.0f); /* already clamped */
2100                         ub_dst[3] = 255;
2101
2102                         fp_src += 1;
2103                         ub_dst += 4;
2104                 }
2105         }
2106
2107         MEM_freeN(maskbuf);
2108
2109         return ibuf;
2110 }
2111
2112 static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float nr)
2113 {
2114         ImBuf *ibuf = NULL;
2115         float frame;
2116         float oldcfra;
2117         Object *camera;
2118         ListBase oldmarkers;
2119         
2120         /* Old info:
2121          * Hack! This function can be called from do_render_seq(), in that case
2122          * the seq->scene can already have a Render initialized with same name,
2123          * so we have to use a default name. (compositor uses scene name to
2124          * find render).
2125          * However, when called from within the UI (image preview in sequencer)
2126          * we do want to use scene Render, that way the render result is defined
2127          * for display in render/imagewindow
2128          *
2129          * Hmm, don't see, why we can't do that all the time,
2130          * and since G.rendering is uhm, gone... (Peter)
2131          */
2132
2133         /* New info:
2134          * Using the same name for the renders works just fine as the do_render_seq()
2135          * render is not used while the scene strips are rendered.
2136          *
2137          * However rendering from UI (through sequencer_preview_area_draw) can crash in
2138          * very many cases since other renders (material preview, an actual render etc.)
2139          * can be started while this sequence preview render is running. The only proper
2140          * solution is to make the sequencer preview render a proper job, which can be
2141          * stopped when needed. This would also give a nice progress bar for the preview
2142          * space so that users know there's something happening.
2143          *
2144          * As a result the active scene now only uses OpenGL rendering for the sequencer
2145          * preview. This is far from nice, but is the only way to prevent crashes at this
2146          * time.
2147          *
2148          * -jahka
2149          */
2150
2151         int rendering = G.rendering;
2152         int doseq;
2153         int doseq_gl = G.rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
2154         int have_seq = FALSE;
2155         Scene *scene;
2156
2157         /* don't refer to seq->scene above this point!, it can be NULL */
2158         if (seq->scene == NULL) {
2159                 return NULL;
2160         }
2161
2162         scene = seq->scene;
2163         frame = scene->r.sfra + nr + seq->anim_startofs;
2164
2165         have_seq = (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first;
2166
2167         oldcfra = scene->r.cfra;
2168         scene->r.cfra = frame;
2169
2170         if (seq->scene_camera)  
2171                 camera = seq->scene_camera;
2172         else {  
2173                 BKE_scene_camera_switch_update(scene);
2174                 camera = scene->camera;
2175         }
2176
2177         if (have_seq == FALSE && camera == NULL) {
2178                 scene->r.cfra = oldcfra;
2179                 return NULL;
2180         }
2181
2182         /* prevent eternal loop */
2183         doseq = context.scene->r.scemode & R_DOSEQ;
2184         context.scene->r.scemode &= ~R_DOSEQ;
2185         
2186 #ifdef DURIAN_CAMERA_SWITCH
2187         /* stooping to new low's in hackyness :( */
2188         oldmarkers = scene->markers;
2189         scene->markers.first = scene->markers.last = NULL;
2190 #else
2191         (void)oldmarkers;
2192 #endif
2193         
2194         if (sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq == 0) && camera) {
2195                 char err_out[256] = "unknown";
2196                 /* for old scened this can be uninitialized,
2197                  * should probably be added to do_versions at some point if the functionality stays */
2198                 if (context.scene->r.seq_prev_type == 0)
2199                         context.scene->r.seq_prev_type = 3 /* == OB_SOLID */;
2200
2201                 /* opengl offscreen render */
2202                 BKE_scene_update_for_newframe(context.bmain, scene, scene->lay);
2203                 ibuf = sequencer_view3d_cb(scene, camera, context.rectx, context.recty,
2204                                            IB_rect, context.scene->r.seq_prev_type, TRUE, err_out);
2205                 if (ibuf == NULL) {
2206                         fprintf(stderr, "seq_render_scene_strip failed to get opengl buffer: %s\n", err_out);
2207                 }
2208         }
2209         else {
2210                 Render *re = RE_GetRender(scene->id.name);
2211                 RenderResult rres;
2212
2213                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
2214                 if (rendering || context.scene != scene) {
2215                         if (re == NULL)
2216                                 re = RE_NewRender(scene->id.name);
2217                         
2218                         RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE);
2219
2220                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
2221                         G.rendering = rendering;
2222                 }
2223                 
2224                 RE_AcquireResultImage(re, &rres);
2225                 
2226                 if (rres.rectf) {
2227                         ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
2228                         memcpy(ibuf->rect_float, rres.rectf, 4 * sizeof(float) * rres.rectx * rres.recty);
2229                         if (rres.rectz) {
2230                                 addzbuffloatImBuf(ibuf);
2231                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float) * rres.rectx * rres.recty);
2232                         }
2233
2234                         /* float buffers in the sequencer are not linear */
2235                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2236                                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
2237                         else
2238                                 ibuf->profile = IB_PROFILE_NONE;
2239                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
2240                 }
2241                 else if (rres.rect32) {
2242                         ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
2243                         memcpy(ibuf->rect, rres.rect32, 4 * rres.rectx * rres.recty);
2244                 }
2245                 
2246                 RE_ReleaseResultImage(re);
2247                 
2248                 // BIF_end_render_callbacks();
2249         }
2250         
2251         /* restore */
2252         context.scene->r.scemode |= doseq;
2253         
2254         scene->r.cfra = oldcfra;
2255
2256         if (frame != oldcfra)
2257                 BKE_scene_update_for_newframe(context.bmain, scene, scene->lay);
2258         
2259 #ifdef DURIAN_CAMERA_SWITCH
2260         /* stooping to new low's in hackyness :( */
2261         scene->markers = oldmarkers;
2262 #endif
2263
2264         return ibuf;
2265 }
2266
2267 static ImBuf *seq_render_strip(SeqRenderData context, Sequence *seq, float cfra)
2268 {
2269         ImBuf *ibuf = NULL;
2270         char name[FILE_MAX];
2271         int use_preprocess = BKE_sequencer_input_have_to_preprocess(context, seq, cfra);
2272         int is_proxy_image = FALSE;
2273         float nr = give_stripelem_index(seq, cfra);
2274         /* all effects are handled similarly with the exception of speed effect */
2275         int type = (seq->type & SEQ_TYPE_EFFECT && seq->type != SEQ_TYPE_SPEED) ? SEQ_TYPE_EFFECT : seq->type;
2276         int is_preprocessed = !ELEM3(type, SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_SCENE);
2277
2278         ibuf = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF);
2279
2280         /* currently, we cache preprocessed images in SEQ_STRIPELEM_IBUF,
2281          * but not(!) on SEQ_STRIPELEM_IBUF_ENDSTILL and ..._STARTSTILL */
2282         if (ibuf)
2283                 use_preprocess = FALSE;
2284
2285         if (ibuf == NULL)
2286                 ibuf = copy_from_ibuf_still(context, seq, nr);
2287         
2288         /* MOVIECLIPs have their own proxy management */
2289         if (ibuf == NULL && seq->type != SEQ_TYPE_MOVIECLIP) {
2290                 ibuf = seq_proxy_fetch(context, seq, cfra);
2291                 is_proxy_image = (ibuf != NULL);
2292         }
2293
2294         if (ibuf == NULL) switch (type) {
2295                         case SEQ_TYPE_META:
2296                         {
2297                                 ImBuf *meta_ibuf = NULL;
2298
2299                                 if (seq->seqbase.first)
2300                                         meta_ibuf = seq_render_strip_stack(
2301                                                 context, &seq->seqbase,
2302                                                 seq->start + nr, 0);
2303
2304                                 if (meta_ibuf) {
2305                                         ibuf = meta_ibuf;
2306                                         if (ibuf && use_preprocess) {
2307                                                 ImBuf *i = IMB_dupImBuf(ibuf);
2308
2309                                                 IMB_freeImBuf(ibuf);
2310
2311                                                 ibuf = i;
2312                                         }
2313                                 }
2314
2315                                 break;
2316                         }
2317                         case SEQ_TYPE_SPEED:
2318                         {
2319                                 ImBuf *child_ibuf = NULL;
2320
2321                                 float f_cfra;
2322                                 SpeedControlVars *s = (SpeedControlVars *)seq->effectdata;
2323
2324                                 BKE_sequence_effect_speed_rebuild_map(context.scene, seq, 0);
2325
2326                                 /* weeek! */
2327                                 f_cfra = seq->start + s->frameMap[(int)nr];
2328
2329                                 child_ibuf = seq_render_strip(context, seq->seq1, f_cfra);
2330
2331                                 if (child_ibuf) {
2332                                         ibuf = child_ibuf;
2333                                         if (ibuf && use_preprocess) {
2334                                                 ImBuf *i = IMB_dupImBuf(ibuf);
2335
2336                                                 IMB_freeImBuf(ibuf);
2337
2338                                                 ibuf = i;
2339                                         }
2340                                 }
2341                                 break;
2342                         }
2343                         case SEQ_TYPE_EFFECT:
2344                         {
2345                                 ibuf = seq_render_effect_strip_impl(context, seq, seq->start + nr);
2346                                 break;
2347                         }
2348                         case SEQ_TYPE_IMAGE:
2349                         {
2350                                 StripElem *s_elem = BKE_sequencer_give_stripelem(seq, cfra);
2351
2352                                 if (s_elem) {
2353                                         BLI_join_dirfile(name, sizeof(name), seq->strip->dir, s_elem->name);
2354                                         BLI_path_abs(name, G.main->name);
2355                                 }
2356
2357                                 if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect))) {
2358                                         /* we don't need both (speed reasons)! */
2359                                         if (ibuf->rect_float && ibuf->rect)
2360                                                 imb_freerectImBuf(ibuf);
2361
2362                                         /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2363                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
2364                                                 IMB_convert_profile(ibuf, IB_PROFILE_NONE);
2365
2366                                         copy_to_ibuf_still(context, seq, nr, ibuf);
2367
2368                                         s_elem->orig_width  = ibuf->x;
2369                                         s_elem->orig_height = ibuf->y;
2370                                 }
2371                                 break;
2372                         }
2373                         case SEQ_TYPE_MOVIE:
2374                         {
2375                                 seq_open_anim_file(seq);
2376
2377                                 if (seq->anim) {
2378                                         IMB_anim_set_preseek(seq->anim, seq->anim_preseek);
2379
2380                                         ibuf = IMB_anim_absolute(seq->anim, nr + seq->anim_startofs,
2381                                                                  seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
2382                                                                  seq_rendersize_to_proxysize(context.preview_render_size));
2383
2384                                         /* we don't need both (speed reasons)! */
2385                                         if (ibuf && ibuf->rect_float && ibuf->rect)
2386                                                 imb_freerectImBuf(ibuf);
2387                                         if (ibuf) {
2388                                                 seq->strip->stripdata->orig_width = ibuf->x;
2389                                                 seq->strip->stripdata->orig_height = ibuf->y;
2390                                         }
2391                                 }
2392                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2393                                 break;
2394                         }
2395                         case SEQ_TYPE_SCENE:
2396                         {
2397                                 /* scene can be NULL after deletions */
2398                                 ibuf = seq_render_scene_strip(context, seq, nr);
2399
2400                                 /* Scene strips update all animation, so we need to restore original state.*/
2401                                 BKE_animsys_evaluate_all_animation(context.bmain, context.scene, cfra);
2402
2403                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2404                                 break;
2405                         }
2406                         case SEQ_TYPE_MOVIECLIP:
2407                         {
2408                                 ibuf = seq_render_movieclip_strip(context, seq, nr);
2409
2410                                 if (ibuf && use_preprocess) {
2411                                         ImBuf *i = IMB_dupImBuf(ibuf);
2412
2413                                         IMB_freeImBuf(ibuf);
2414
2415                                         ibuf = i;
2416                                 }
2417
2418                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2419                                 break;
2420                         }
2421                 case SEQ_TYPE_MASK:
2422                 {
2423                         /* ibuf is alwats new */
2424                         ibuf = seq_render_mask_strip(context, seq, nr);
2425
2426                         copy_to_ibuf_still(context, seq, nr, ibuf);
2427                         break;
2428                 }
2429         }
2430
2431         if (ibuf == NULL)
2432                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2433
2434         if (ibuf->x != context.rectx || ibuf->y != context.recty)
2435                 use_preprocess = TRUE;
2436
2437         if (use_preprocess)
2438                 ibuf = input_preprocess(context, seq, cfra, ibuf, is_proxy_image, is_preprocessed);
2439
2440         BKE_sequencer_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf);
2441
2442         return ibuf;
2443 }
2444
2445 /*********************** strip stack rendering functions *************************/
2446
2447 static int seq_must_swap_input_in_blend_mode(Sequence *seq)
2448 {
2449         int swap_input = FALSE;
2450
2451         /* bad hack, to fix crazy input ordering of 
2452          * those two effects */
2453
2454         if (ELEM3(seq->blend_mode, SEQ_TYPE_ALPHAOVER, SEQ_TYPE_ALPHAUNDER, SEQ_TYPE_OVERDROP)) {
2455                 swap_input = TRUE;
2456         }
2457         
2458         return swap_input;
2459 }
2460
2461 static int seq_get_early_out_for_blend_mode(Sequence *seq)
2462 {
2463         struct SeqEffectHandle sh = BKE_sequence_get_blend(seq);
2464         float facf = seq->blend_opacity / 100.0f;
2465         int early_out = sh.early_out(seq, facf, facf);
2466         
2467         if (ELEM(early_out, EARLY_DO_EFFECT, EARLY_NO_INPUT)) {
2468                 return early_out;
2469         }
2470
2471         if (seq_must_swap_input_in_blend_mode(seq)) {
2472                 if (early_out == EARLY_USE_INPUT_2) {
2473                         return EARLY_USE_INPUT_1;
2474                 }
2475                 else if (early_out == EARLY_USE_INPUT_1) {
2476                         return EARLY_USE_INPUT_2;
2477                 }
2478         }
2479         return early_out;
2480 }
2481
2482 static ImBuf *seq_render_strip_stack(SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown)
2483 {
2484         Sequence *seq_arr[MAXSEQ + 1];
2485         int count;
2486         int i;
2487         ImBuf *out = NULL;
2488
2489         count = get_shown_sequences(seqbasep, cfra, chanshown, (Sequence **)&seq_arr);
2490
2491         if (count == 0) {
2492                 return NULL;
2493         }
2494
2495 #if 0 /* commentind since this breaks keyframing, since it resets the value on draw */
2496         if (scene->r.cfra != cfra) {
2497                 /* XXX for prefetch and overlay offset!..., very bad!!! */
2498                 AnimData *adt = BKE_animdata_from_id(&scene->id);
2499                 BKE_animsys_evaluate_animdata(scene, &scene->id, adt, cfra, ADT_RECALC_ANIM);
2500         }
2501 #endif
2502
2503         out = BKE_sequencer_cache_get(context, seq_arr[count - 1],  cfra, SEQ_STRIPELEM_IBUF_COMP);
2504
2505         if (out) {
2506                 return out;
2507         }
2508         
2509         if (count == 1) {
2510                 out = seq_render_strip(context, seq_arr[0], cfra);
2511                 BKE_sequencer_cache_put(context, seq_arr[0], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2512
2513                 return out;
2514         }
2515
2516
2517         for (i = count - 1; i >= 0; i--) {
2518                 int early_out;
2519                 Sequence *seq = seq_arr[i];
2520
2521                 out = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP);
2522
2523                 if (out) {
2524                         break;
2525                 }
2526                 if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2527                         out = seq_render_strip(context, seq, cfra);
2528                         break;
2529                 }
2530
2531                 early_out = seq_get_early_out_for_blend_mode(seq);
2532
2533                 switch (early_out) {
2534                         case EARLY_NO_INPUT:
2535                         case EARLY_USE_INPUT_2:
2536                                 out = seq_render_strip(context, seq, cfra);
2537                                 break;
2538                         case EARLY_USE_INPUT_1:
2539                                 if (i == 0) {
2540                                         out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2541                                 }
2542                                 break;
2543                         case EARLY_DO_EFFECT:
2544                                 if (i == 0) {
2545                                         out = seq_render_strip(context, seq, cfra);
2546                                 }
2547
2548                                 break;
2549                 }
2550                 if (out) {
2551                         break;
2552                 }
2553         }
2554
2555         BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2556
2557         i++;
2558
2559         for (; i < count; i++) {
2560                 Sequence *seq = seq_arr[i];
2561
2562                 if (seq_get_early_out_for_blend_mode(seq) == EARLY_DO_EFFECT) {
2563                         struct SeqEffectHandle sh = BKE_sequence_get_blend(seq);
2564                         ImBuf *ibuf1 = out;
2565                         ImBuf *ibuf2 = seq_render_strip(context, seq, cfra);
2566
2567                         float facf = seq->blend_opacity / 100.0f;
2568                         int swap_input = seq_must_swap_input_in_blend_mode(seq);
2569
2570                         if (swap_input) {
2571                                 if (sh.multithreaded)
2572                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL);
2573                                 else
2574                                         out = sh.execute(context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL);
2575                         }
2576                         else {
2577                                 if (sh.multithreaded)
2578                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL);
2579                                 else
2580                                         out = sh.execute(context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL);
2581                         }
2582                 
2583                         IMB_freeImBuf(ibuf1);
2584                         IMB_freeImBuf(ibuf2);
2585                 }
2586
2587                 BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2588         }
2589
2590         return out;
2591 }
2592
2593 /*
2594  * returned ImBuf is refed!
2595  * you have to free after usage!
2596  */
2597
2598 ImBuf *BKE_sequencer_give_ibuf(SeqRenderData context, float cfra, int chanshown)
2599 {
2600         Editing *ed = BKE_sequencer_editing_get(context.scene, FALSE);
2601         int count;
2602         ListBase *seqbasep;
2603         
2604         if (ed == NULL) return NULL;
2605
2606         count = BLI_countlist(&ed->metastack);
2607         if ((chanshown < 0) && (count > 0)) {
2608                 count = MAX2(count + chanshown, 0);
2609                 seqbasep = ((MetaStack *)BLI_findlink(&ed->metastack, count))->oldbasep;
2610         }
2611         else {
2612                 seqbasep = ed->seqbasep;
2613         }
2614
2615         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2616 }
2617
2618 ImBuf *BKE_sequencer_give_ibuf_seqbase(SeqRenderData context, float cfra, int chanshown, ListBase *seqbasep)
2619 {
2620         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2621 }
2622
2623
2624 ImBuf *BKE_sequencer_give_ibuf_direct(SeqRenderData context, float cfra, Sequence *seq)
2625 {
2626         return seq_render_strip(context, seq, cfra);
2627 }
2628
2629 /* *********************** threading api ******************* */
2630
2631 static ListBase running_threads;
2632 static ListBase prefetch_wait;
2633 static ListBase prefetch_done;
2634
2635 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
2636 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
2637 static pthread_cond_t wakeup_cond          = PTHREAD_COND_INITIALIZER;
2638
2639 //static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
2640 //static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
2641
2642 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
2643 static pthread_cond_t frame_done_cond      = PTHREAD_COND_INITIALIZER;
2644
2645 static volatile int seq_thread_shutdown = TRUE; 
2646 static volatile int seq_last_given_monoton_cfra = 0;
2647 static int monoton_cfra = 0;
2648
2649 typedef struct PrefetchThread {
2650         struct PrefetchThread *next, *prev;
2651         
2652         Scene *scene;
2653         struct PrefetchQueueElem *current;
2654         pthread_t pthread;
2655         int running;
2656         
2657 } PrefetchThread;
2658
2659 typedef struct PrefetchQueueElem {
2660         struct PrefetchQueueElem *next, *prev;
2661         
2662         int rectx;
2663         int recty;
2664         float cfra;
2665         int chanshown;
2666         int preview_render_size;
2667
2668         int monoton_cfra;
2669
2670         ImBuf *ibuf;
2671 } PrefetchQueueElem;
2672
2673 void BKE_sequencer_give_ibuf_prefetch_request(SeqRenderData context, float cfra, int chanshown)
2674 {
2675         PrefetchQueueElem *e;
2676         if (seq_thread_shutdown) {
2677                 return;
2678         }
2679
2680         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
2681         e->rectx = context.rectx;
2682         e->recty = context.recty;
2683         e->cfra = cfra;
2684         e->chanshown = chanshown;
2685         e->preview_render_size = context.preview_render_size;
2686         e->monoton_cfra = monoton_cfra++;
2687
2688         pthread_mutex_lock(&queue_lock);
2689         BLI_addtail(&prefetch_wait, e);
2690         pthread_mutex_unlock(&queue_lock);
2691         
2692         pthread_mutex_lock(&wakeup_lock);
2693         pthread_cond_signal(&wakeup_cond);
2694         pthread_mutex_unlock(&wakeup_lock);
2695 }
2696
2697 ImBuf *BKE_sequencer_give_ibuf_threaded(SeqRenderData context, float cfra, int chanshown)
2698 {
2699         PrefetchQueueElem *e = NULL;
2700         int found_something = FALSE;
2701
2702         if (seq_thread_shutdown) {
2703                 return BKE_sequencer_give_ibuf(context, cfra, chanshown);
2704         }
2705
2706         while (!e) {
2707                 int success = FALSE;
2708                 pthread_mutex_lock(&queue_lock);
2709
2710                 for (e = prefetch_done.first; e; e = e->next) {
2711                         if (cfra == e->cfra &&
2712                             chanshown == e->chanshown &&
2713                             context.rectx == e->rectx &&
2714                             context.recty == e->recty &&
2715                             context.preview_render_size == e->preview_render_size)
2716                         {
2717                                 success = TRUE;
2718                                 found_something = TRUE;
2719                                 break;
2720                         }
2721                 }
2722
2723                 if (!e) {
2724                         for (e = prefetch_wait.first; e; e = e->next) {
2725                                 if (cfra == e->cfra &&
2726                                     chanshown == e->chanshown &&
2727                                     context.rectx == e->rectx &&
2728                                     context.recty == e->recty &&
2729                                     context.preview_render_size == e->preview_render_size)
2730                                 {
2731                                         found_something = TRUE;
2732                                         break;
2733                                 }
2734                         }
2735                 }
2736
2737                 if (!e) {
2738                         PrefetchThread *tslot;
2739
2740                         for (tslot = running_threads.first;
2741                              tslot;
2742                              tslot = tslot->next)
2743                         {
2744                                 if (tslot->current &&
2745                                     cfra == tslot->current->cfra &&
2746                                     chanshown == tslot->current->chanshown &&
2747                                     context.rectx == tslot->current->rectx &&
2748                                     context.recty == tslot->current->recty &&
2749                                     context.preview_render_size == tslot->current->preview_render_size)
2750                                 {
2751                                         found_something = TRUE;
2752                                         break;
2753                                 }
2754                         }
2755                 }
2756
2757                 /* e->ibuf is unrefed by render thread on next round. */
2758
2759                 if (e) {
2760                         seq_last_given_monoton_cfra = e->monoton_cfra;
2761                 }
2762
2763                 pthread_mutex_unlock(&queue_lock);
2764
2765                 if (!success) {
2766                         e = NULL;
2767
2768                         if (!found_something) {
2769                                 fprintf(stderr, "SEQ-THREAD: Requested frame not in queue ???\n");
2770                                 break;
2771                         }
2772                         pthread_mutex_lock(&frame_done_lock);
2773                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
2774                         pthread_mutex_unlock(&frame_done_lock);
2775                 }
2776         }
2777         
2778         return e ? e->ibuf : NULL;
2779 }
2780
2781 /* Functions to free imbuf and anim data on changes */
2782
2783 static void free_anim_seq(Sequence *seq)
2784 {
2785         if (seq->anim) {
2786                 IMB_free_anim(seq->anim);
2787                 seq->anim = NULL;
2788         }
2789 }
2790
2791 void BKE_sequence_invalidate_cache(Scene *scene, Sequence *seq)
2792 {
2793         Editing *ed = scene->ed;
2794         Sequence *cur;
2795         int left = seq->start, right = seq->start + seq->len;
2796
2797         /* invalidate cache for current sequence */
2798         BKE_sequencer_cache_cleanup_sequence(seq);
2799
2800         /* invalidate cache for all dependent sequences */
2801         SEQ_BEGIN (ed, cur)
2802         {
2803                 int cur_left = cur->start, cur_right = cur->start + cur->len;
2804
2805                 /* sequence is outside of changed one, shouldn't be invalidated */
2806                 if (cur_right < left || cur_left > right)
2807                         continue;
2808
2809                 /* sequence is below changed one, not dependent on it */
2810                 if (cur->machine < seq->machine)
2811                         continue;
2812
2813                 /* sequence is not blending with lower machines, no need to invalidate */
2814                 if ((cur->blend_mode == SEQ_BLEND_REPLACE) ||
2815                     (cur->blend_mode == SEQ_TYPE_CROSS && cur->blend_opacity == 100.0f))
2816                 {
2817                         continue;
2818                 }
2819
2820                 BKE_sequencer_cache_cleanup_sequence(cur);
2821         }
2822         SEQ_END
2823 }
2824
2825 void BKE_sequencer_free_imbuf(Scene *scene, ListBase *seqbase, int check_mem_usage, int keep_file_handles)
2826 {
2827         Sequence *seq;
2828
2829         if (check_mem_usage) {
2830                 /* Let the cache limitor take care of this (schlaile) */
2831                 /* While render let's keep all memory available for render 
2832                  * (ton)
2833                  * At least if free memory is tight...
2834                  * This can make a big difference in encoding speed
2835                  * (it is around 4 times(!) faster, if we do not waste time
2836                  * on freeing _all_ buffers every time on long timelines...)
2837                  * (schlaile)
2838                  */
2839         
2840                 uintptr_t mem_in_use;
2841                 uintptr_t mmap_in_use;
2842                 uintptr_t max;
2843         
2844                 mem_in_use = MEM_get_memory_in_use();
2845                 mmap_in_use = MEM_get_mapped_memory_in_use();
2846                 max = MEM_CacheLimiter_get_maximum();
2847         
2848                 if (max == 0 || mem_in_use + mmap_in_use <= max) {
2849                         return;
2850                 }
2851         }
2852
2853         BKE_sequencer_cache_cleanup();
2854         
2855         for (seq = seqbase->first; seq; seq = seq->next) {
2856                 if (seq->strip) {
2857                         if (seq->type == SEQ_TYPE_MOVIE && !keep_file_handles)
2858                                 free_anim_seq(seq);
2859                         if (seq->type == SEQ_TYPE_SPEED) {
2860                                 BKE_sequence_effect_speed_rebuild_map(scene, seq, 1);
2861                         }
2862                 }
2863                 if (seq->type == SEQ_TYPE_META) {
2864                         BKE_sequencer_free_imbuf(scene, &seq->seqbase, FALSE, keep_file_handles);
2865                 }
2866                 if (seq->type == SEQ_TYPE_SCENE) {
2867                         /* FIXME: recurs downwards, 
2868                          * but do recurs protection somehow! */
2869                 }
2870         }
2871         
2872 }
2873
2874 static int update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
2875 {
2876         Sequence *subseq;
2877         int free_imbuf = 0;
2878         
2879         /* recurs downwards to see if this seq depends on the changed seq */
2880         
2881         if (seq == NULL)
2882                 return 0;
2883         
2884         if (seq == changed_seq)
2885                 free_imbuf = 1;
2886         
2887         for (subseq = seq->seqbase.first; subseq; subseq = subseq->next)
2888                 if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change))
2889                         free_imbuf = TRUE;
2890         
2891         if (seq->seq1)
2892                 if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change))
2893                         free_imbuf = TRUE;
2894         if (seq->seq2 && (seq->seq2 != seq->seq1))
2895                 if (update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change))
2896                         free_imbuf = TRUE;
2897         if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
2898                 if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change))
2899                         free_imbuf = TRUE;
2900         
2901         if (free_imbuf) {
2902                 if (ibuf_change) {
2903                         if (seq->type == SEQ_TYPE_MOVIE)
2904                                 free_anim_seq(seq);
2905                         if (seq->type == SEQ_TYPE_SPEED) {
2906                                 BKE_sequence_effect_speed_rebuild_map(scene, seq, 1);
2907                         }
2908                 }
2909                 
2910                 if (len_change)
2911                         BKE_sequence_calc(scene, seq);
2912         }
2913         
2914         return free_imbuf;
2915 }
2916
2917 void BKE_sequencer_update_changed_seq_and_deps(Scene *scene, Sequence *changed_seq, int len_change, int ibuf_change)
2918 {
2919         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
2920         Sequence *seq;
2921         
2922         if (ed == NULL) return;
2923         
2924         for (seq = ed->seqbase.first; seq; seq = seq->next)
2925                 update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change);
2926 }
2927
2928 /* seq funcs's for transforming internally
2929  * notice the difference between start/end and left/right.
2930  *
2931  * left and right are the bounds at which the sequence is rendered,
2932  * start and end are from the start and fixed length of the sequence.
2933  */
2934 static int seq_tx_get_start(Sequence *seq)
2935 {
2936         return seq->start;
2937 }
2938 static int seq_tx_get_end(Sequence *seq)
2939 {
2940         return seq->start + seq->len;
2941 }
2942
2943 int BKE_sequence_tx_get_final_left(Sequence *seq, int metaclip)
2944 {
2945         if (metaclip && seq->tmp) {
2946                 /* return the range clipped by the parents range */
2947                 return maxi(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE));
2948         }
2949         else {
2950                 return (seq->start - seq->startstill) + seq->startofs;
2951         }
2952
2953 }
2954 int BKE_sequence_tx_get_final_right(Sequence *seq, int metaclip)
2955 {
2956         if (metaclip && seq->tmp) {
2957                 /* return the range clipped by the parents range */
2958                 return mini(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE));
2959         }
2960         else {
2961                 return ((seq->start + seq->len) + seq->endstill) - seq->endofs;
2962         }
2963 }
2964
2965 void BKE_sequence_tx_set_final_left(Sequence *seq, int val)
2966 {
2967         if (val < (seq)->start) {
2968                 seq->startstill = abs(val - (seq)->start);
2969                 seq->startofs = 0;
2970         }
2971         else {
2972                 seq->startofs = abs(val - (seq)->start);
2973                 seq->startstill = 0;
2974         }
2975 }
2976
2977 void BKE_sequence_tx_set_final_right(Sequence *seq, int val)
2978 {
2979         if (val > (seq)->start + (seq)->len) {
2980                 seq->endstill = abs(val - (seq->start + (seq)->len));
2981                 seq->endofs = 0;
2982         }
2983         else {
2984                 seq->endofs = abs(val - ((seq)->start + (seq)->len));
2985                 seq->endstill = 0;
2986         }
2987 }
2988
2989 /* used so we can do a quick check for single image seq
2990  * since they work a bit differently to normal image seq's (during transform) */
2991 int BKE_sequence_single_check(Sequence *seq)
2992 {
2993         return ((seq->len == 1) &&
2994                 (seq->type == SEQ_TYPE_IMAGE ||
2995                  ((seq->type & SEQ_TYPE_EFFECT) &&
2996                   BKE_sequence_effect_get_num_inputs(seq->type) == 0)));
2997 }
2998
2999 /* check if the selected seq's reference unselected seq's */
3000 int BKE_sequence_base_isolated_sel_check(ListBase *seqbase)
3001 {
3002         Sequence *seq;
3003         /* is there more than 1 select */
3004         int ok = FALSE;
3005
3006         for (seq = seqbase->first; seq; seq = seq->next) {
3007                 if (seq->flag & SELECT) {
3008                         ok = TRUE;
3009                         break;
3010                 }
3011         }
3012
3013         if (ok == FALSE)
3014                 return FALSE;
3015
3016         /* test relationships */
3017         for (seq = seqbase->first; seq; seq = seq->next) {
3018                 if ((seq->type & SEQ_TYPE_EFFECT) == 0)
3019                         continue;
3020
3021                 if (seq->flag & SELECT) {
3022                         if ( (seq->seq1 && (seq->seq1->flag & SELECT) == 0) ||
3023                              (seq->seq2 && (seq->seq2->flag & SELECT) == 0) ||
3024                              (seq->seq3 && (seq->seq3->flag & SELECT) == 0) )
3025                         {
3026                                 return FALSE;
3027                         }
3028                 }
3029                 else {
3030                         if ( (seq->seq1 && (seq->seq1->flag & SELECT)) ||
3031                              (seq->seq2 && (seq->seq2->flag & SELECT)) ||
3032                              (seq->seq3 && (seq->seq3->flag & SELECT)) )
3033                         {
3034                                 return FALSE;
3035                         }
3036                 }
3037         }
3038
3039         return TRUE;
3040 }
3041
3042 /* use to impose limits when dragging/extending - so impossible situations don't happen
3043  * Cant use the SEQ_LEFTSEL and SEQ_LEFTSEL directly because the strip may be in a metastrip */
3044 void BKE_sequence_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag)
3045 {
3046         if (leftflag) {
3047                 if (BKE_sequence_tx_get_final_left(seq, 0) >= BKE_sequence_tx_get_final_right(seq, 0)) {
3048                         BKE_sequence_tx_set_final_left(seq, BKE_sequence_tx_get_final_right(seq, 0) - 1);
3049                 }
3050
3051                 if (BKE_sequence_single_check(seq) == 0) {
3052                         if (BKE_sequence_tx_get_final_left(seq, 0) >= seq_tx_get_end(seq)) {
3053                                 BKE_sequence_tx_set_final_left(seq, seq_tx_get_end(seq) - 1);
3054                         }
3055
3056                         /* dosnt work now - TODO */
3057 #if 0
3058                         if (seq_tx_get_start(seq) >= seq_tx_get_final_right(seq, 0)) {
3059                                 int ofs;
3060                                 ofs = seq_tx_get_start(seq) - seq_tx_get_final_right(seq, 0);
3061                                 seq->start -= ofs;
3062                                 seq_tx_set_final_left(seq, seq_tx_get_final_left(seq, 0) + ofs);
3063                         }
3064 #endif
3065                 }
3066         }
3067
3068         if (rightflag) {
3069                 if (BKE_sequence_tx_get_final_right(seq, 0) <= BKE_sequence_tx_get_final_left(seq, 0)) {
3070                         BKE_sequence_tx_set_final_right(seq, BKE_sequence_tx_get_final_left(seq, 0) + 1);
3071                 }
3072
3073                 if (BKE_sequence_single_check(seq) == 0) {
3074                         if (BKE_sequence_tx_get_final_right(seq, 0) <= seq_tx_get_start(seq)) {
3075                                 BKE_sequence_tx_set_final_right(seq, seq_tx_get_start(seq) + 1);
3076                         }
3077                 }
3078         }
3079
3080         /* sounds cannot be extended past their endpoints */
3081         if (seq->type == SEQ_TYPE_SOUND_RAM) {
3082                 seq->startstill = 0;
3083                 seq->endstill = 0;
3084         }
3085 }
3086
3087 void BKE_sequence_single_fix(Sequence *seq)
3088 {
3089         int left, start, offset;
3090         if (!BKE_sequence_single_check(seq))
3091                 return;
3092
3093         /* make sure the image is always at the start since there is only one,
3094          * adjusting its start should be ok */
3095         left = BKE_sequence_tx_get_final_left(seq, 0);
3096         start = seq->start;
3097         if (start != left) {
3098                 offset = left - start;
3099                 BKE_sequence_tx_set_final_left(seq, BKE_sequence_tx_get_final_left(seq, 0) - offset);
3100                 BKE_sequence_tx_set_final_right(seq, BKE_sequence_tx_get_final_right(seq, 0) - offset);
3101                 seq->start += offset;
3102         }
3103 }
3104
3105 int BKE_sequence_tx_test(Sequence *seq)
3106 {
3107         return (seq->type < SEQ_TYPE_EFFECT) || (BKE_sequence_effect_get_num_inputs(seq->type) == 0);
3108 }
3109
3110 static int seq_overlap(Sequence *seq1, Sequence *seq2)
3111 {
3112         return (seq1 != seq2 && seq1->machine == seq2->machine &&
3113                 ((seq1->enddisp <= seq2->startdisp) || (seq1->startdisp >= seq2->enddisp)) == 0);
3114 }
3115
3116 int BKE_sequence_test_overlap(ListBase *seqbasep, Sequence *test)
3117 {
3118         Sequence *seq;
3119
3120         seq = seqbasep->first;
3121         while (seq) {
3122                 if (seq_overlap(test, seq))
3123                         return 1;
3124
3125                 seq = seq->next;
3126         }
3127         return 0;
3128 }
3129
3130
3131 void BKE_sequence_translate(Scene *evil_scene, Sequence *seq, int delta)
3132 {
3133         BKE_sequencer_offset_animdata(evil_scene, seq, delta);
3134         seq->start += delta;
3135
3136         if (seq->type == SEQ_TYPE_META) {
3137                 Sequence *seq_child;
3138                 for (seq_child = seq->seqbase.first; seq_child; seq_child = seq_child->next) {
3139                         BKE_sequence_translate(evil_scene, seq_child, delta);
3140                 }
3141         }
3142
3143         BKE_sequence_calc_disp(evil_scene, seq);
3144 }
3145
3146 void BKE_sequence_sound_init(Scene *scene, Sequence *seq)
3147 {
3148         if (seq->type == SEQ_TYPE_META) {
3149                 Sequence *seq_child;
3150                 for (seq_child = seq->seqbase.first; seq_child; seq_child = seq_child->next) {
3151                         BKE_sequence_sound_init(scene, seq_child);
3152                 }
3153         }
3154         else {
3155                 if (seq->sound) {
3156                         seq->scene_sound = sound_add_scene_sound_defaults(scene, seq);
3157                 }
3158                 if (seq->scene) {
3159                         sound_scene_add_scene_sound_defaults(scene, seq);
3160                 }
3161         }
3162 }
3163
3164 Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame)
3165 {
3166         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
3167         Sequence *seq, *best_seq = NULL;
3168         int best_machine = -1;
3169         
3170         if (!ed) return NULL;
3171         
3172         for (seq = ed->seqbasep->first; seq; seq = seq->next) {
3173                 if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame)
3174                         continue;
3175                 /* only use elements you can see - not */
3176                 if (ELEM5(seq->type, SEQ_TYPE_IMAGE, SEQ_TYPE_META, SEQ_TYPE_SCENE, SEQ_TYPE_MOVIE, SEQ_TYPE_COLOR)) {
3177                         if (seq->machine > best_machine) {
3178                                 best_seq = seq;
3179                                 best_machine = seq->machine;
3180                         }
3181                 }
3182         }
3183         return best_seq;
3184 }
3185
3186 /* return 0 if there werent enough space */
3187 int BKE_sequence_base_shuffle(ListBase *seqbasep, Sequence *test, Scene *evil_scene)
3188 {
3189         int orig_machine = test->machine;
3190         test->machine++;
3191         BKE_sequence_calc(evil_scene, test);
3192         while (BKE_sequence_test_overlap(seqbasep, test) ) {
3193                 if (test->machine >= MAXSEQ) {
3194                         break;
3195                 }
3196                 test->machine++;
3197                 BKE_sequence_calc(evil_scene, test); // XXX - I don't think this is needed since were only moving vertically, Campbell.
3198         }
3199
3200         
3201         if (test->machine >= MAXSEQ) {
3202                 /* Blender 2.4x would remove the strip.
3203                  * nicer to move it to the end */
3204
3205                 Sequence *seq;
3206                 int new_frame = test->enddisp;
3207
3208                 for (seq = seqbasep->first; seq; seq = seq->next) {
3209                         if (seq->machine == orig_machine)
3210                                 new_frame = MAX2(new_frame, seq->enddisp);
3211                 }
3212
3213                 test->machine = orig_machine;
3214                 new_frame = new_frame + (test->start - test->startdisp); /* adjust by the startdisp */
3215                 BKE_sequence_translate(evil_scene, test, new_frame - test->start);
3216
3217                 BKE_sequence_calc(evil_scene, test);
3218                 return 0;
3219         }
3220         else {
3221                 return 1;
3222         }
3223 }
3224
3225 static int shuffle_seq_time_offset_test(ListBase *seqbasep, char dir)
3226 {
3227         int offset = 0;
3228         Sequence *seq, *seq_other;
3229
3230         for (seq = seqbasep->first; seq; seq = seq->next) {
3231                 if (seq->tmp) {
3232                         for (seq_other = seqbasep->first; seq_other; seq_other = seq_other->next) {
3233                                 if (!seq_other->tmp && seq_overlap(seq, seq_other)) {
3234                                         if (dir == 'L') {
3235                                                 offset = MIN2(offset, seq_other->startdisp - seq->enddisp);
3236                                         }
3237                                         else {
3238                                                 offset = MAX2(offset, seq_other->enddisp - seq->startdisp);
3239                                         }
3240                                 }
3241                         }
3242                 }
3243         }
3244         return offset;
3245 }
3246
3247 static int shuffle_seq_time_offset(Scene *scene, ListBase *seqbasep, char dir)
3248 {
3249         int ofs = 0;
3250         int tot_ofs = 0;
3251         Sequence *seq;
3252         while ( (ofs = shuffle_seq_time_offset_test(seqbasep, dir)) ) {