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