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