4f1b324bc28bfba852b8799665686f3f5de42ad4
[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, render_size,
1132                              BKE_sequencer_give_stripelem(seq, cfra)->name);
1133                 frameno = 1;
1134         }
1135         else {
1136                 frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1137                 BLI_snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####", dir, render_size);
1138         }
1139
1140         BLI_path_abs(name, G.main->name);
1141         BLI_path_frame(name, frameno, 0);
1142
1143         strcat(name, ".jpg");
1144
1145         return TRUE;
1146 }
1147
1148 static ImBuf *seq_proxy_fetch(SeqRenderData context, Sequence *seq, int cfra)
1149 {
1150         char name[PROXY_MAXFILE];
1151         IMB_Proxy_Size psize = seq_rendersize_to_proxysize(context.preview_render_size);
1152         int size_flags;
1153         int render_size = context.preview_render_size;
1154
1155         /* dirty hack to distinguish 100% render size from PROXY_100 */
1156         if (render_size == 99) {
1157                 render_size = 100;
1158         }
1159
1160         if (!(seq->flag & SEQ_USE_PROXY)) {
1161                 return NULL;
1162         }
1163
1164         size_flags = seq->strip->proxy->build_size_flags;
1165
1166         /* only use proxies, if they are enabled (even if present!) */
1167         if (psize == IMB_PROXY_NONE || ((size_flags & psize) != psize)) {
1168                 return NULL;
1169         }
1170
1171         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1172                 int frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1173                 if (seq->strip->proxy->anim == NULL) {
1174                         if (seq_proxy_get_fname(seq, cfra, render_size, name) == 0) {
1175                                 return NULL;
1176                         }
1177  
1178                         seq->strip->proxy->anim = openanim(name, IB_rect, 0);
1179                 }
1180                 if (seq->strip->proxy->anim == NULL) {
1181                         return NULL;
1182                 }
1183  
1184                 seq_open_anim_file(seq);
1185
1186                 frameno = IMB_anim_index_get_frame_index(seq->anim, seq->strip->proxy->tc, frameno);
1187
1188                 return IMB_anim_absolute(seq->strip->proxy->anim, frameno, IMB_TC_NONE, IMB_PROXY_NONE);
1189         }
1190  
1191         if (seq_proxy_get_fname(seq, cfra, render_size, name) == 0) {
1192                 return NULL;
1193         }
1194
1195         if (BLI_exists(name)) {
1196                 return IMB_loadiffname(name, IB_rect);
1197         }
1198         else {
1199                 return NULL;
1200         }
1201 }
1202
1203 static void seq_proxy_build_frame(SeqRenderData context, Sequence *seq, int cfra, int proxy_render_size)
1204 {
1205         char name[PROXY_MAXFILE];
1206         int quality;
1207         int rectx, recty;
1208         int ok;
1209         ImBuf *ibuf;
1210
1211         if (!seq_proxy_get_fname(seq, cfra, proxy_render_size, name)) {
1212                 return;
1213         }
1214
1215         ibuf = seq_render_strip(context, seq, cfra);
1216
1217         rectx = (proxy_render_size * context.scene->r.xsch) / 100;
1218         recty = (proxy_render_size * context.scene->r.ysch) / 100;
1219
1220         if (ibuf->x != rectx || ibuf->y != recty) {
1221                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1222         }
1223
1224         /* depth = 32 is intentionally left in, otherwise ALPHA channels
1225          * won't work... */
1226         quality = seq->strip->proxy->quality;
1227         ibuf->ftype = JPG | quality;
1228
1229         /* unsupported feature only confuses other s/w */
1230         if (ibuf->planes == 32)
1231                 ibuf->planes = 24;
1232
1233         BLI_make_existing_file(name);
1234         
1235         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1236         if (ok == 0) {
1237                 perror(name);
1238         }
1239
1240         IMB_freeImBuf(ibuf);
1241 }
1242
1243 SeqIndexBuildContext *BKE_sequencer_proxy_rebuild_context(Main *bmain, Scene *scene, Sequence *seq)
1244 {
1245         SeqIndexBuildContext *context;
1246         Sequence *nseq;
1247
1248         if (!seq->strip || !seq->strip->proxy) {
1249                 return NULL;
1250         }
1251
1252         if (!(seq->flag & SEQ_USE_PROXY)) {
1253                 return NULL;
1254         }
1255
1256         context = MEM_callocN(sizeof(SeqIndexBuildContext), "seq proxy rebuild context");
1257
1258         nseq = BKE_sequence_dupli_recursive(scene, scene, seq, 0);
1259
1260         context->tc_flags   = nseq->strip->proxy->build_tc_flags;
1261         context->size_flags = nseq->strip->proxy->build_size_flags;
1262         context->quality    = nseq->strip->proxy->quality;
1263
1264         context->bmain = bmain;
1265         context->scene = scene;
1266         context->orig_seq = seq;
1267         context->seq = nseq;
1268
1269         if (nseq->type == SEQ_TYPE_MOVIE) {
1270                 seq_open_anim_file(nseq);
1271
1272                 if (nseq->anim) {
1273                         context->index_context = IMB_anim_index_rebuild_context(nseq->anim,
1274                                 context->tc_flags, context->size_flags, context->quality);
1275                 }
1276         }
1277
1278         return context;
1279 }
1280
1281 void BKE_sequencer_proxy_rebuild(SeqIndexBuildContext *context, short *stop, short *do_update, float *progress)
1282 {
1283         SeqRenderData render_context;
1284         Sequence *seq = context->seq;
1285         Scene *scene = context->scene;
1286         int cfra;
1287
1288         if (seq->type == SEQ_TYPE_MOVIE) {
1289                 if (context->index_context) {
1290                         IMB_anim_index_rebuild(context->index_context, stop, do_update, progress);
1291                 }
1292
1293                 return;
1294         }
1295
1296         if (!(seq->flag & SEQ_USE_PROXY)) {
1297                 return;
1298         }
1299
1300         /* that's why it is called custom... */
1301         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1302                 return;
1303         }
1304
1305         /* fail safe code */
1306
1307         render_context = BKE_sequencer_new_render_data(context->bmain, context->scene,
1308                                             (scene->r.size * (float) scene->r.xsch) / 100.0f + 0.5f,
1309                                             (scene->r.size * (float) scene->r.ysch) / 100.0f + 0.5f, 100);
1310
1311         for (cfra = seq->startdisp + seq->startstill;  cfra < seq->enddisp - seq->endstill; cfra++) {
1312                 if (context->size_flags & IMB_PROXY_25) {
1313                         seq_proxy_build_frame(render_context, seq, cfra, 25);
1314                 }
1315                 if (context->size_flags & IMB_PROXY_50) {
1316                         seq_proxy_build_frame(render_context, seq, cfra, 50);
1317                 }
1318                 if (context->size_flags & IMB_PROXY_75) {
1319                         seq_proxy_build_frame(render_context, seq, cfra, 75);
1320                 }
1321                 if (context->size_flags & IMB_PROXY_100) {
1322                         seq_proxy_build_frame(render_context, seq, cfra, 100);
1323                 }
1324
1325                 *progress = (float) cfra / (seq->enddisp - seq->endstill - seq->startdisp + seq->startstill);
1326                 *do_update = TRUE;
1327
1328                 if (*stop || G.is_break)
1329                         break;
1330         }
1331 }
1332
1333 void BKE_sequencer_proxy_rebuild_finish(SeqIndexBuildContext *context, short stop)
1334 {
1335         if (context->index_context) {
1336                 IMB_close_anim_proxies(context->seq->anim);
1337                 IMB_close_anim_proxies(context->orig_seq->anim);
1338                 IMB_anim_index_rebuild_finish(context->index_context, stop);
1339         }
1340
1341         seq_free_sequence_recurse(context->scene, context->seq);
1342
1343         MEM_freeN(context);
1344 }
1345
1346 /*********************** color balance *************************/
1347
1348 static StripColorBalance calc_cb(StripColorBalance *cb_)
1349 {
1350         StripColorBalance cb = *cb_;
1351         int c;
1352
1353         for (c = 0; c < 3; c++) {
1354                 cb.lift[c] = 2.0f - cb.lift[c];
1355         }
1356
1357         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1358                 for (c = 0; c < 3; c++) {
1359                         /* tweak to give more subtle results
1360                          * values above 1.0 are scaled */
1361                         if (cb.lift[c] > 1.0f)
1362                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0;
1363
1364                         cb.lift[c] = 2.0f - cb.lift[c];
1365                 }
1366         }
1367
1368         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1369                 for (c = 0; c < 3; c++) {
1370                         if (cb.gain[c] != 0.0f) {
1371                                 cb.gain[c] = 1.0f / cb.gain[c];
1372                         }
1373                         else {
1374                                 cb.gain[c] = 1000000; /* should be enough :) */
1375                         }
1376                 }
1377         }
1378
1379         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1380                 for (c = 0; c < 3; c++) {
1381                         if (cb.gamma[c] != 0.0f) {
1382                                 cb.gamma[c] = 1.0f / cb.gamma[c];
1383                         }
1384                         else {
1385                                 cb.gamma[c] = 1000000; /* should be enough :) */
1386                         }
1387                 }
1388         }
1389
1390         return cb;
1391 }
1392
1393 /* note: lift is actually 2-lift */
1394 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1395 {
1396         float x = (((in - 1.0f) * lift) + 1.0f) * gain;
1397
1398         /* prevent NaN */
1399         if (x < 0.f)
1400                 x = 0.f;
1401
1402         return powf(x, gamma) * mul;
1403 }
1404
1405 static void make_cb_table_byte(float lift, float gain, float gamma,
1406                                unsigned char *table, float mul)
1407 {
1408         int y;
1409
1410         for (y = 0; y < 256; y++) {
1411                 float v = color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1412
1413                 table[y] = FTOCHAR(v);
1414         }
1415 }
1416
1417 static void make_cb_table_float(float lift, float gain, float gamma,
1418                                 float *table, float mul)
1419 {
1420         int y;
1421
1422         for (y = 0; y < 256; y++) {
1423                 float v = color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1424
1425                 table[y] = v;
1426         }
1427 }
1428
1429 static void color_balance_byte_byte(Sequence *seq, unsigned char *rect, int width, int height, float mul)
1430 {
1431         unsigned char cb_tab[3][256];
1432         int c;
1433         unsigned char *p = rect;
1434         unsigned char *e = p + width * 4 * height;
1435
1436         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1437
1438         for (c = 0; c < 3; c++) {
1439                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1440         }
1441
1442         while (p < e) {
1443                 p[0] = cb_tab[0][p[0]];
1444                 p[1] = cb_tab[1][p[1]];
1445                 p[2] = cb_tab[2][p[2]];
1446                 
1447                 p += 4;
1448         }
1449 }
1450
1451 static void color_balance_byte_float(Sequence *seq, unsigned char *rect, float *rect_float, int width, int height, float mul)
1452 {
1453         float cb_tab[4][256];
1454         int c, i;
1455         unsigned char *p = rect;
1456         unsigned char *e = p + width * 4 * height;
1457         float *o;
1458         StripColorBalance cb;
1459
1460         o = rect_float;
1461
1462         cb = calc_cb(seq->strip->color_balance);
1463
1464         for (c = 0; c < 3; c++) {
1465                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1466         }
1467
1468         for (i = 0; i < 256; i++) {
1469                 cb_tab[3][i] = ((float)i) * (1.0f / 255.0f);
1470         }
1471
1472         while (p < e) {
1473                 o[0] = cb_tab[0][p[0]];
1474                 o[1] = cb_tab[1][p[1]];
1475                 o[2] = cb_tab[2][p[2]];
1476                 o[3] = cb_tab[3][p[3]];
1477
1478                 p += 4; o += 4;
1479         }
1480 }
1481
1482 static void color_balance_float_float(Sequence *seq, float *rect_float, int width, int height, float mul)
1483 {
1484         float *p = rect_float;
1485         float *e = rect_float + width * 4 * height;
1486         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1487
1488         while (p < e) {
1489                 int c;
1490                 for (c = 0; c < 3; c++) {
1491                         p[c] = color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1492                 }
1493                 p += 4;
1494         }
1495 }
1496
1497 typedef struct ColorBalanceInitData {
1498         Sequence *seq;
1499         ImBuf *ibuf;
1500         float mul;
1501 } ColorBalanceInitData;
1502
1503 typedef struct ColorBalanceThread {
1504         Sequence *seq;
1505         float mul;
1506
1507         int width, height;
1508
1509         unsigned char *rect;
1510         float *rect_float;
1511 } ColorBalanceThread;
1512
1513 static void color_balance_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1514 {
1515         ColorBalanceThread *handle = (ColorBalanceThread *) handle_v;
1516         ColorBalanceInitData *init_data = (ColorBalanceInitData *) init_data_v;
1517         ImBuf *ibuf = init_data->ibuf;
1518
1519         int offset = 4 * start_line * ibuf->x;
1520
1521         memset(handle, 0, sizeof(ColorBalanceThread));
1522
1523         handle->seq = init_data->seq;
1524         handle->mul = init_data->mul;
1525         handle->width = ibuf->x;
1526         handle->height = tot_line;
1527
1528         if (ibuf->rect)
1529                 handle->rect = (unsigned char *) ibuf->rect + offset;
1530
1531         if (ibuf->rect_float)
1532                 handle->rect_float = ibuf->rect_float + offset;
1533 }
1534
1535 static void *color_balance_do_thread(void *thread_data_v)
1536 {
1537         ColorBalanceThread *thread_data = (ColorBalanceThread *) thread_data_v;
1538         Sequence *seq = thread_data->seq;
1539         int width = thread_data->width, height = thread_data->height;
1540         unsigned char *rect = thread_data->rect;
1541         float *rect_float = thread_data->rect_float;
1542         float mul = thread_data->mul;
1543
1544         if (rect_float) {
1545                 color_balance_float_float(seq, rect_float, width, height, mul);
1546         }
1547         else if (seq->flag & SEQ_MAKE_FLOAT) {
1548                 color_balance_byte_float(seq, rect, rect_float, width, height, mul);
1549         }
1550         else {
1551                 color_balance_byte_byte(seq, rect, width, height, mul);
1552         }
1553
1554         return NULL;
1555 }
1556
1557 static void color_balance(Sequence *seq, ImBuf *ibuf, float mul)
1558 {
1559         if (!ibuf->rect_float && seq->flag & SEQ_MAKE_FLOAT)
1560                 imb_addrectfloatImBuf(ibuf);
1561
1562         if (BLI_thread_is_main()) {
1563                 /* color balance could have been called from prefetching job which
1564                  * is already multithreaded, so doing threading here makes no sense
1565                  */
1566                 ColorBalanceInitData init_data;
1567
1568                 init_data.seq = seq;
1569                 init_data.ibuf = ibuf;
1570                 init_data.mul = mul;
1571
1572                 IMB_processor_apply_threaded(ibuf->y, sizeof(ColorBalanceThread), &init_data,
1573                                          color_balance_init_handle, color_balance_do_thread);
1574
1575         }
1576         else {
1577                 ColorBalanceThread handle;
1578
1579                 handle.seq = seq;
1580                 handle.mul = mul;
1581                 handle.width = ibuf->x;
1582                 handle.height = ibuf->y;
1583                 handle.rect = (unsigned char *)ibuf->rect;
1584                 handle.rect_float = ibuf->rect_float;
1585
1586                 color_balance_do_thread(&handle);
1587         }
1588 }
1589
1590 /*
1591  *  input preprocessing for SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP and SEQ_TYPE_SCENE
1592  *
1593  *  Do all the things you can't really do afterwards using sequence effects
1594  *  (read: before rescaling to render resolution has been done)
1595  *
1596  *  Order is important!
1597  *
1598  *  - Deinterlace
1599  *  - Crop and transform in image source coordinate space
1600  *  - Flip X + Flip Y (could be done afterwards, backward compatibility)
1601  *  - Promote image to float data (affects pipeline operations afterwards)
1602  *  - Color balance (is most efficient in the byte -> float
1603  *    (future: half -> float should also work fine!)
1604  *    case, if done on load, since we can use lookup tables)
1605  *  - Premultiply
1606  */
1607
1608 int BKE_sequencer_input_have_to_preprocess(SeqRenderData UNUSED(context), Sequence *seq, float UNUSED(cfra))
1609 {
1610         float mul;
1611
1612         if (seq->flag & (SEQ_FILTERY | SEQ_USE_CROP | SEQ_USE_TRANSFORM | SEQ_FLIPX |
1613                          SEQ_FLIPY | SEQ_USE_COLOR_BALANCE | SEQ_MAKE_PREMUL))
1614         {
1615                 return TRUE;
1616         }
1617
1618         mul = seq->mul;
1619
1620         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
1621                 mul *= seq->blend_opacity / 100.0f;
1622         }
1623
1624         if (mul != 1.0f) {
1625                 return TRUE;
1626         }
1627
1628         if (seq->sat != 1.0f) {
1629                 return TRUE;
1630         }
1631                 
1632         return FALSE;
1633 }
1634
1635 static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf *ibuf,
1636                                int is_proxy_image, int is_preprocessed)
1637 {
1638         float mul;
1639
1640         ibuf = IMB_makeSingleUser(ibuf);
1641
1642         if ((seq->flag & SEQ_FILTERY) &&
1643             !ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP))
1644         {
1645                 IMB_filtery(ibuf);
1646         }
1647
1648         if (seq->flag & (SEQ_USE_CROP | SEQ_USE_TRANSFORM)) {
1649                 StripCrop c = {0};
1650                 StripTransform t = {0};
1651                 int sx, sy, dx, dy;
1652                 double xscale = 1.0;
1653                 double yscale = 1.0;
1654
1655                 if (is_proxy_image) {
1656                         double f = seq_rendersize_to_scale_factor(context.preview_render_size);
1657
1658                         if (f != 1.0) {
1659                                 IMB_scalefastImBuf(ibuf, ibuf->x / f, ibuf->y / f);
1660                         }
1661                 }
1662
1663                 if (seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1664                         c = *seq->strip->crop;
1665                 }
1666                 if (seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1667                         t = *seq->strip->transform;
1668                 }
1669
1670                 xscale = context.scene->r.xsch ? ((double) context.rectx / (double) context.scene->r.xsch) : 1.0;
1671                 yscale = context.scene->r.ysch ? ((double) context.recty / (double) context.scene->r.ysch) : 1.0;
1672
1673                 c.left *= xscale; c.right *= xscale;
1674                 c.top *= yscale; c.bottom *= yscale;
1675
1676                 t.xofs *= xscale; t.yofs *= yscale;
1677
1678                 sx = ibuf->x - c.left - c.right;
1679                 sy = ibuf->y - c.top - c.bottom;
1680                 dx = sx;
1681                 dy = sy;
1682
1683                 if (seq->flag & SEQ_USE_TRANSFORM) {
1684                         if (is_preprocessed) {
1685                                 dx = context.rectx;
1686                                 dy = context.recty;
1687                         }
1688                         else {
1689                                 dx = context.scene->r.xsch;
1690                                 dy = context.scene->r.ysch;
1691                         }
1692                 }
1693
1694                 if (c.top  + c.bottom >= ibuf->y ||
1695                     c.left + c.right  >= ibuf->x ||
1696                     t.xofs >= dx || t.yofs >= dy)
1697                 {
1698                         make_black_ibuf(ibuf);
1699                 }
1700                 else {
1701                         ImBuf *i = IMB_allocImBuf(dx, dy, 32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1702
1703                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1704                         
1705                         IMB_freeImBuf(ibuf);
1706
1707                         ibuf = i;
1708                 }
1709         } 
1710
1711         if (seq->flag & SEQ_FLIPX) {
1712                 IMB_flipx(ibuf);
1713         }
1714         
1715         if (seq->flag & SEQ_FLIPY) {
1716                 IMB_flipy(ibuf);
1717         }
1718
1719         if (seq->sat != 1.0f) {
1720                 IMB_saturation(ibuf, seq->sat);
1721         }
1722
1723         mul = seq->mul;
1724
1725         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
1726                 mul *= seq->blend_opacity / 100.0f;
1727         }
1728
1729         if (seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1730                 color_balance(seq, ibuf, mul);
1731                 mul = 1.0;
1732         }
1733
1734         if (seq->flag & SEQ_MAKE_FLOAT) {
1735                 if (!ibuf->rect_float)
1736                         IMB_float_from_rect_simple(ibuf);
1737
1738                 if (ibuf->rect) {
1739                         imb_freerectImBuf(ibuf);
1740                 }
1741         }
1742
1743         if (mul != 1.0f) {
1744                 multibuf(ibuf, mul);
1745         }
1746
1747         if (seq->flag & SEQ_MAKE_PREMUL) {
1748                 if (ibuf->planes == 32 && ibuf->zbuf == NULL) {
1749                         IMB_premultiply_alpha(ibuf);
1750                 }
1751         }
1752
1753
1754         if (ibuf->x != context.rectx || ibuf->y != context.recty) {
1755                 if (context.scene->r.mode & R_OSA) {
1756                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1757                 }
1758                 else {
1759                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1760                 }
1761         }
1762         return ibuf;
1763 }
1764
1765 static ImBuf *copy_from_ibuf_still(SeqRenderData context, Sequence *seq, float nr)
1766 {
1767         ImBuf *rval = NULL;
1768         ImBuf *ibuf = NULL;
1769
1770         if (nr == 0) {
1771                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL);
1772         }
1773         else if (nr == seq->len - 1) {
1774                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL);
1775         }
1776
1777         if (ibuf) {
1778                 rval = IMB_dupImBuf(ibuf);
1779                 IMB_freeImBuf(ibuf);
1780         }
1781
1782         return rval;
1783 }
1784
1785 static void copy_to_ibuf_still(SeqRenderData context, Sequence *seq, float nr, ImBuf *ibuf)
1786 {
1787         if (nr == 0 || nr == seq->len - 1) {
1788                 /* we have to store a copy, since the passed ibuf
1789                  * could be preprocessed afterwards (thereby silently
1790                  * changing the cached image... */
1791                 ibuf = IMB_dupImBuf(ibuf);
1792
1793                 if (nr == 0) {
1794                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
1795                 } 
1796
1797                 if (nr == seq->len - 1) {
1798                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
1799                 }
1800
1801                 IMB_freeImBuf(ibuf);
1802         }
1803 }
1804
1805 /*********************** strip rendering functions  *************************/
1806
1807 typedef struct RenderEffectInitData {
1808         struct SeqEffectHandle *sh;
1809         SeqRenderData context;
1810         Sequence *seq;
1811         float cfra, facf0, facf1;
1812         ImBuf *ibuf1, *ibuf2, *ibuf3;
1813
1814         ImBuf *out;
1815 } RenderEffectInitData;
1816
1817 typedef struct RenderEffectThread {
1818         struct SeqEffectHandle *sh;
1819         SeqRenderData context;
1820         Sequence *seq;
1821         float cfra, facf0, facf1;
1822         ImBuf *ibuf1, *ibuf2, *ibuf3;
1823
1824         ImBuf *out;
1825         int start_line, tot_line;
1826 } RenderEffectThread;
1827
1828 static void render_effect_execute_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1829 {
1830         RenderEffectThread *handle = (RenderEffectThread *) handle_v;
1831         RenderEffectInitData *init_data = (RenderEffectInitData *) init_data_v;
1832
1833         handle->sh = init_data->sh;
1834         handle->context = init_data->context;
1835         handle->seq = init_data->seq;
1836         handle->cfra = init_data->cfra;
1837         handle->facf0 = init_data->facf0;
1838         handle->facf1 = init_data->facf1;
1839         handle->ibuf1 = init_data->ibuf1;
1840         handle->ibuf2 = init_data->ibuf2;
1841         handle->ibuf3 = init_data->ibuf3;
1842         handle->out = init_data->out;
1843
1844         handle->start_line = start_line;
1845         handle->tot_line = tot_line;
1846 }
1847
1848 static void *render_effect_execute_do_thread(void *thread_data_v)
1849 {
1850         RenderEffectThread *thread_data = (RenderEffectThread *) thread_data_v;
1851
1852         thread_data->sh->execute_slice(thread_data->context, thread_data->seq, thread_data->cfra,
1853                                        thread_data->facf0, thread_data->facf1, thread_data->ibuf1,
1854                                        thread_data->ibuf2, thread_data->ibuf3, thread_data->start_line,
1855                                        thread_data->tot_line, thread_data->out);
1856
1857         return NULL;
1858 }
1859
1860 static ImBuf *seq_render_effect_execute_threaded(struct SeqEffectHandle *sh, SeqRenderData context, Sequence *seq,
1861                                                  float cfra, float facf0, float facf1,
1862                                                  ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
1863 {
1864         RenderEffectInitData init_data;
1865         ImBuf *out = sh->init_execution(context, ibuf1, ibuf2, ibuf3);
1866
1867         init_data.sh = sh;
1868         init_data.context = context;
1869         init_data.seq = seq;
1870         init_data.cfra = cfra;
1871         init_data.facf0 = facf0;
1872         init_data.facf1 = facf1;
1873         init_data.ibuf1 = ibuf1;
1874         init_data.ibuf2 = ibuf2;
1875         init_data.ibuf3 = ibuf3;
1876         init_data.out = out;
1877
1878         IMB_processor_apply_threaded(out->y, sizeof(RenderEffectThread), &init_data,
1879                                  render_effect_execute_init_handle, render_effect_execute_do_thread);
1880
1881         return out;
1882 }
1883
1884 static ImBuf *seq_render_effect_strip_impl(SeqRenderData context, Sequence *seq, float cfra)
1885 {
1886         float fac, facf;
1887         int early_out;
1888         int i;
1889         struct SeqEffectHandle sh = BKE_sequence_get_effect(seq);
1890         FCurve *fcu = NULL;
1891         ImBuf *ibuf[3];
1892         Sequence *input[3];
1893         ImBuf *out = NULL;
1894
1895         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1896
1897         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1898
1899         if (!sh.execute && !(sh.execute_slice && sh.init_execution)) {
1900                 /* effect not supported in this version... */
1901                 out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
1902                 return out;
1903         }
1904
1905         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1906                 sh.get_default_fac(seq, cfra, &fac, &facf);
1907                 
1908                 if ((context.scene->r.mode & R_FIELDS) == 0)
1909                         facf = fac;
1910         }
1911         else {
1912                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0, NULL);
1913                 if (fcu) {
1914                         fac = facf = evaluate_fcurve(fcu, cfra);
1915                         if (context.scene->r.mode & R_FIELDS) {
1916                                 facf = evaluate_fcurve(fcu, cfra + 0.5f);
1917                         }
1918                 }
1919                 else {
1920                         fac = facf = seq->effect_fader;
1921                 }
1922         }
1923
1924         early_out = sh.early_out(seq, fac, facf);
1925
1926         switch (early_out) {
1927                 case EARLY_NO_INPUT:
1928                         out = sh.execute(context, seq, cfra, fac, facf, NULL, NULL, NULL);
1929                         break;
1930                 case EARLY_DO_EFFECT:
1931                         for (i = 0; i < 3; i++) {
1932                                 if (input[i])
1933                                         ibuf[i] = seq_render_strip(context, input[i], cfra);
1934                         }
1935
1936                         if (ibuf[0] && ibuf[1]) {
1937                                 if (sh.multithreaded)
1938                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
1939                                 else
1940                                         out = sh.execute(context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
1941                         }
1942                         break;
1943                 case EARLY_USE_INPUT_1:
1944                         if (input[0]) {
1945                                 ibuf[0] = seq_render_strip(context, input[0], cfra);
1946                         }
1947                         if (ibuf[0]) {
1948                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
1949                                         out = IMB_dupImBuf(ibuf[0]);
1950                                 }
1951                                 else {
1952                                         out = ibuf[0];
1953                                         IMB_refImBuf(out);
1954                                 }
1955                         }
1956                         break;
1957                 case EARLY_USE_INPUT_2:
1958                         if (input[1]) {
1959                                 ibuf[1] = seq_render_strip(context, input[1], cfra);
1960                         }
1961                         if (ibuf[1]) {
1962                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
1963                                         out = IMB_dupImBuf(ibuf[1]);
1964                                 }
1965                                 else {
1966                                         out = ibuf[1];
1967                                         IMB_refImBuf(out);
1968                                 }
1969                         }
1970                         break;
1971         }
1972
1973         for (i = 0; i < 3; i++) {
1974                 IMB_freeImBuf(ibuf[i]);
1975         }
1976
1977         if (out == NULL) {
1978                 out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
1979         }
1980
1981         return out;
1982 }
1983
1984 static ImBuf *seq_render_movieclip_strip(SeqRenderData context, Sequence *seq, float nr)
1985 {
1986         ImBuf *ibuf = NULL;
1987         MovieClipUser user;
1988         float tloc[2], tscale, tangle;
1989
1990         if (!seq->clip) {
1991                 return NULL;
1992         }
1993
1994         memset(&user, 0, sizeof(MovieClipUser));
1995         
1996         BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs);
1997
1998         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
1999
2000         switch (seq_rendersize_to_proxysize(context.preview_render_size)) {
2001                 case IMB_PROXY_NONE:
2002                         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
2003                         break;
2004                 case IMB_PROXY_100:
2005                         user.render_size = MCLIP_PROXY_RENDER_SIZE_100;
2006                         break;
2007                 case IMB_PROXY_75:
2008                         user.render_size = MCLIP_PROXY_RENDER_SIZE_75;
2009                         break;
2010                 case IMB_PROXY_50:
2011                         user.render_size = MCLIP_PROXY_RENDER_SIZE_50;
2012                         break;
2013                 case IMB_PROXY_25:
2014                         user.render_size = MCLIP_PROXY_RENDER_SIZE_25;
2015                         break;
2016         }
2017
2018         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_UNDISTORTED) {
2019                 user.render_flag = MCLIP_PROXY_RENDER_UNDISTORT;
2020         }
2021
2022         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_STABILIZED) {
2023                 ibuf = BKE_movieclip_get_stable_ibuf(seq->clip, &user, tloc, &tscale, &tangle, 0);
2024         }
2025         else {
2026                 ibuf = BKE_movieclip_get_ibuf_flag(seq->clip, &user, 0, MOVIECLIP_CACHE_SKIP);
2027         }
2028
2029         return ibuf;
2030 }
2031
2032
2033 static ImBuf *seq_render_mask_strip(SeqRenderData context, Sequence *seq, float nr)
2034 {
2035         /* TODO - add option to rasterize to alpha imbuf? */
2036         ImBuf *ibuf = NULL;
2037         float *maskbuf;
2038         int i;
2039
2040         if (!seq->mask) {
2041                 return NULL;
2042         }
2043         else {
2044                 Mask *mask_temp;
2045                 MaskRasterHandle *mr_handle;
2046
2047                 mask_temp = BKE_mask_copy_nolib(seq->mask);
2048
2049                 BKE_mask_evaluate(mask_temp, seq->mask->sfra + nr, TRUE);
2050
2051                 maskbuf = MEM_mallocN(sizeof(float) * context.rectx * context.recty, __func__);
2052
2053                 mr_handle = BKE_maskrasterize_handle_new();
2054
2055                 BKE_maskrasterize_handle_init(mr_handle, mask_temp, context.rectx, context.recty, TRUE, TRUE, TRUE);
2056
2057                 BKE_mask_free(mask_temp);
2058                 MEM_freeN(mask_temp);
2059
2060                 BKE_maskrasterize_buffer(mr_handle, context.rectx, context.recty, maskbuf);
2061
2062                 BKE_maskrasterize_handle_free(mr_handle);
2063         }
2064
2065
2066         if (seq->flag & SEQ_MAKE_FLOAT) {
2067                 /* pixels */
2068                 float *fp_src;
2069                 float *fp_dst;
2070
2071                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rectfloat);
2072
2073                 fp_src = maskbuf;
2074                 fp_dst = ibuf->rect_float;
2075                 i = context.rectx * context.recty;
2076                 while (--i) {
2077                         fp_dst[0] = fp_dst[1] = fp_dst[2] = *fp_src;
2078                         fp_dst[3] = 1.0f;
2079
2080                         fp_src += 1;
2081                         fp_dst += 4;
2082                 }
2083         }
2084         else {
2085                 /* pixels */
2086                 float *fp_src;
2087                 unsigned char *ub_dst;
2088
2089                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2090
2091                 fp_src = maskbuf;
2092                 ub_dst = (unsigned char *)ibuf->rect;
2093                 i = context.rectx * context.recty;
2094                 while (--i) {
2095                         ub_dst[0] = ub_dst[1] = ub_dst[2] = (unsigned char)(*fp_src * 255.0f); /* already clamped */
2096                         ub_dst[3] = 255;
2097
2098                         fp_src += 1;
2099                         ub_dst += 4;
2100                 }
2101         }
2102
2103         MEM_freeN(maskbuf);
2104
2105         return ibuf;
2106 }
2107
2108 static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float nr)
2109 {
2110         ImBuf *ibuf = NULL;
2111         float frame;
2112         float oldcfra;
2113         Object *camera;
2114         ListBase oldmarkers;
2115         
2116         /* Old info:
2117          * Hack! This function can be called from do_render_seq(), in that case
2118          * the seq->scene can already have a Render initialized with same name,
2119          * so we have to use a default name. (compositor uses scene name to
2120          * find render).
2121          * However, when called from within the UI (image preview in sequencer)
2122          * we do want to use scene Render, that way the render result is defined
2123          * for display in render/imagewindow
2124          *
2125          * Hmm, don't see, why we can't do that all the time,
2126          * and since G.is_rendering is uhm, gone... (Peter)
2127          */
2128
2129         /* New info:
2130          * Using the same name for the renders works just fine as the do_render_seq()
2131          * render is not used while the scene strips are rendered.
2132          *
2133          * However rendering from UI (through sequencer_preview_area_draw) can crash in
2134          * very many cases since other renders (material preview, an actual render etc.)
2135          * can be started while this sequence preview render is running. The only proper
2136          * solution is to make the sequencer preview render a proper job, which can be
2137          * stopped when needed. This would also give a nice progress bar for the preview
2138          * space so that users know there's something happening.
2139          *
2140          * As a result the active scene now only uses OpenGL rendering for the sequencer
2141          * preview. This is far from nice, but is the only way to prevent crashes at this
2142          * time.
2143          *
2144          * -jahka
2145          */
2146
2147         int rendering = G.is_rendering;
2148         int doseq;
2149         int doseq_gl = G.is_rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
2150         int have_seq = FALSE;
2151         Scene *scene;
2152
2153         /* don't refer to seq->scene above this point!, it can be NULL */
2154         if (seq->scene == NULL) {
2155                 return NULL;
2156         }
2157
2158         scene = seq->scene;
2159         frame = scene->r.sfra + nr + seq->anim_startofs;
2160
2161         have_seq = (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first;
2162
2163         oldcfra = scene->r.cfra;
2164         scene->r.cfra = frame;
2165
2166         if (seq->scene_camera)  
2167                 camera = seq->scene_camera;
2168         else {  
2169                 BKE_scene_camera_switch_update(scene);
2170                 camera = scene->camera;
2171         }
2172
2173         if (have_seq == FALSE && camera == NULL) {
2174                 scene->r.cfra = oldcfra;
2175                 return NULL;
2176         }
2177
2178         /* prevent eternal loop */
2179         doseq = context.scene->r.scemode & R_DOSEQ;
2180         context.scene->r.scemode &= ~R_DOSEQ;
2181         
2182 #ifdef DURIAN_CAMERA_SWITCH
2183         /* stooping to new low's in hackyness :( */
2184         oldmarkers = scene->markers;
2185         scene->markers.first = scene->markers.last = NULL;
2186 #else
2187         (void)oldmarkers;
2188 #endif
2189         
2190         if (sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq == 0) && camera) {
2191                 char err_out[256] = "unknown";
2192                 /* for old scened this can be uninitialized,
2193                  * should probably be added to do_versions at some point if the functionality stays */
2194                 if (context.scene->r.seq_prev_type == 0)
2195                         context.scene->r.seq_prev_type = 3 /* == OB_SOLID */;
2196
2197                 /* opengl offscreen render */
2198                 BKE_scene_update_for_newframe(context.bmain, scene, scene->lay);
2199                 ibuf = sequencer_view3d_cb(scene, camera, context.rectx, context.recty,
2200                                            IB_rect, context.scene->r.seq_prev_type, TRUE, err_out);
2201                 if (ibuf == NULL) {
2202                         fprintf(stderr, "seq_render_scene_strip failed to get opengl buffer: %s\n", err_out);
2203                 }
2204         }
2205         else {
2206                 Render *re = RE_GetRender(scene->id.name);
2207                 RenderResult rres;
2208
2209                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
2210                 if (rendering || context.scene != scene) {
2211                         if (re == NULL)
2212                                 re = RE_NewRender(scene->id.name);
2213                         
2214                         RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE);
2215
2216                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
2217                         G.is_rendering = rendering;
2218                 }
2219                 
2220                 RE_AcquireResultImage(re, &rres);
2221                 
2222                 if (rres.rectf) {
2223                         ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
2224                         memcpy(ibuf->rect_float, rres.rectf, 4 * sizeof(float) * rres.rectx * rres.recty);
2225                         if (rres.rectz) {
2226                                 addzbuffloatImBuf(ibuf);
2227                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float) * rres.rectx * rres.recty);
2228                         }
2229
2230                         /* float buffers in the sequencer are not linear */
2231                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2232                                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
2233                         else
2234                                 ibuf->profile = IB_PROFILE_NONE;
2235                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
2236                 }
2237                 else if (rres.rect32) {
2238                         ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
2239                         memcpy(ibuf->rect, rres.rect32, 4 * rres.rectx * rres.recty);
2240                 }
2241                 
2242                 RE_ReleaseResultImage(re);
2243                 
2244                 // BIF_end_render_callbacks();
2245         }
2246         
2247         /* restore */
2248         context.scene->r.scemode |= doseq;
2249         
2250         scene->r.cfra = oldcfra;
2251
2252         if (frame != oldcfra)
2253                 BKE_scene_update_for_newframe(context.bmain, scene, scene->lay);
2254         
2255 #ifdef DURIAN_CAMERA_SWITCH
2256         /* stooping to new low's in hackyness :( */
2257         scene->markers = oldmarkers;
2258 #endif
2259
2260         return ibuf;
2261 }
2262
2263 static ImBuf *seq_render_strip(SeqRenderData context, Sequence *seq, float cfra)
2264 {
2265         ImBuf *ibuf = NULL;
2266         char name[FILE_MAX];
2267         int use_preprocess = BKE_sequencer_input_have_to_preprocess(context, seq, cfra);
2268         int is_proxy_image = FALSE;
2269         float nr = give_stripelem_index(seq, cfra);
2270         /* all effects are handled similarly with the exception of speed effect */
2271         int type = (seq->type & SEQ_TYPE_EFFECT && seq->type != SEQ_TYPE_SPEED) ? SEQ_TYPE_EFFECT : seq->type;
2272         int is_preprocessed = !ELEM3(type, SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_SCENE);
2273
2274         ibuf = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF);
2275
2276         /* currently, we cache preprocessed images in SEQ_STRIPELEM_IBUF,
2277          * but not(!) on SEQ_STRIPELEM_IBUF_ENDSTILL and ..._STARTSTILL */
2278         if (ibuf)
2279                 use_preprocess = FALSE;
2280
2281         if (ibuf == NULL)
2282                 ibuf = copy_from_ibuf_still(context, seq, nr);
2283         
2284         /* MOVIECLIPs have their own proxy management */
2285         if (ibuf == NULL && seq->type != SEQ_TYPE_MOVIECLIP) {
2286                 ibuf = seq_proxy_fetch(context, seq, cfra);
2287                 is_proxy_image = (ibuf != NULL);
2288         }
2289
2290         if (ibuf == NULL) switch (type) {
2291                         case SEQ_TYPE_META:
2292                         {
2293                                 ImBuf *meta_ibuf = NULL;
2294
2295                                 if (seq->seqbase.first)
2296                                         meta_ibuf = seq_render_strip_stack(
2297                                                 context, &seq->seqbase,
2298                                                 seq->start + nr, 0);
2299
2300                                 if (meta_ibuf) {
2301                                         ibuf = meta_ibuf;
2302                                         if (ibuf && use_preprocess) {
2303                                                 ImBuf *i = IMB_dupImBuf(ibuf);
2304
2305                                                 IMB_freeImBuf(ibuf);
2306
2307                                                 ibuf = i;
2308                                         }
2309                                 }
2310
2311                                 break;
2312                         }
2313                         case SEQ_TYPE_SPEED:
2314                         {
2315                                 ImBuf *child_ibuf = NULL;
2316
2317                                 float f_cfra;
2318                                 SpeedControlVars *s = (SpeedControlVars *)seq->effectdata;
2319
2320                                 BKE_sequence_effect_speed_rebuild_map(context.scene, seq, 0);
2321
2322                                 /* weeek! */
2323                                 f_cfra = seq->start + s->frameMap[(int)nr];
2324
2325                                 child_ibuf = seq_render_strip(context, seq->seq1, f_cfra);
2326
2327                                 if (child_ibuf) {
2328                                         ibuf = child_ibuf;
2329                                         if (ibuf && use_preprocess) {
2330                                                 ImBuf *i = IMB_dupImBuf(ibuf);
2331
2332                                                 IMB_freeImBuf(ibuf);
2333
2334                                                 ibuf = i;
2335                                         }
2336                                 }
2337                                 break;
2338                         }
2339                         case SEQ_TYPE_EFFECT:
2340                         {
2341                                 ibuf = seq_render_effect_strip_impl(context, seq, seq->start + nr);
2342                                 break;
2343                         }
2344                         case SEQ_TYPE_IMAGE:
2345                         {
2346                                 StripElem *s_elem = BKE_sequencer_give_stripelem(seq, cfra);
2347
2348                                 if (s_elem) {
2349                                         BLI_join_dirfile(name, sizeof(name), seq->strip->dir, s_elem->name);
2350                                         BLI_path_abs(name, G.main->name);
2351                                 }
2352
2353                                 if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect))) {
2354                                         /* we don't need both (speed reasons)! */
2355                                         if (ibuf->rect_float && ibuf->rect)
2356                                                 imb_freerectImBuf(ibuf);
2357
2358                                         /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2359                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
2360                                                 IMB_convert_profile(ibuf, IB_PROFILE_NONE);
2361
2362                                         copy_to_ibuf_still(context, seq, nr, ibuf);
2363
2364                                         s_elem->orig_width  = ibuf->x;
2365                                         s_elem->orig_height = ibuf->y;
2366                                 }
2367                                 break;
2368                         }
2369                         case SEQ_TYPE_MOVIE:
2370                         {
2371                                 seq_open_anim_file(seq);
2372
2373                                 if (seq->anim) {
2374                                         IMB_anim_set_preseek(seq->anim, seq->anim_preseek);
2375
2376                                         ibuf = IMB_anim_absolute(seq->anim, nr + seq->anim_startofs,
2377                                                                  seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
2378                                                                  seq_rendersize_to_proxysize(context.preview_render_size));
2379
2380                                         /* we don't need both (speed reasons)! */
2381                                         if (ibuf && ibuf->rect_float && ibuf->rect)
2382                                                 imb_freerectImBuf(ibuf);
2383                                         if (ibuf) {
2384                                                 seq->strip->stripdata->orig_width = ibuf->x;
2385                                                 seq->strip->stripdata->orig_height = ibuf->y;
2386                                         }
2387                                 }
2388                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2389                                 break;
2390                         }
2391                         case SEQ_TYPE_SCENE:
2392                         {
2393                                 /* scene can be NULL after deletions */
2394                                 ibuf = seq_render_scene_strip(context, seq, nr);
2395
2396                                 /* Scene strips update all animation, so we need to restore original state.*/
2397                                 BKE_animsys_evaluate_all_animation(context.bmain, context.scene, cfra);
2398
2399                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2400                                 break;
2401                         }
2402                         case SEQ_TYPE_MOVIECLIP:
2403                         {
2404                                 ibuf = seq_render_movieclip_strip(context, seq, nr);
2405
2406                                 if (ibuf && use_preprocess) {
2407                                         ImBuf *i = IMB_dupImBuf(ibuf);
2408
2409                                         IMB_freeImBuf(ibuf);
2410
2411                                         ibuf = i;
2412                                 }
2413
2414                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2415                                 break;
2416                         }
2417                 case SEQ_TYPE_MASK:
2418                 {
2419                         /* ibuf is alwats new */
2420                         ibuf = seq_render_mask_strip(context, seq, nr);
2421
2422                         copy_to_ibuf_still(context, seq, nr, ibuf);
2423                         break;
2424                 }
2425         }
2426
2427         if (ibuf == NULL)
2428                 ibuf = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2429
2430         if (ibuf->x != context.rectx || ibuf->y != context.recty)
2431                 use_preprocess = TRUE;
2432
2433         if (use_preprocess)
2434                 ibuf = input_preprocess(context, seq, cfra, ibuf, is_proxy_image, is_preprocessed);
2435
2436         BKE_sequencer_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf);
2437
2438         return ibuf;
2439 }
2440
2441 /*********************** strip stack rendering functions *************************/
2442
2443 static int seq_must_swap_input_in_blend_mode(Sequence *seq)
2444 {
2445         int swap_input = FALSE;
2446
2447         /* bad hack, to fix crazy input ordering of 
2448          * those two effects */
2449
2450         if (ELEM3(seq->blend_mode, SEQ_TYPE_ALPHAOVER, SEQ_TYPE_ALPHAUNDER, SEQ_TYPE_OVERDROP)) {
2451                 swap_input = TRUE;
2452         }
2453         
2454         return swap_input;
2455 }
2456
2457 static int seq_get_early_out_for_blend_mode(Sequence *seq)
2458 {
2459         struct SeqEffectHandle sh = BKE_sequence_get_blend(seq);
2460         float facf = seq->blend_opacity / 100.0f;
2461         int early_out = sh.early_out(seq, facf, facf);
2462         
2463         if (ELEM(early_out, EARLY_DO_EFFECT, EARLY_NO_INPUT)) {
2464                 return early_out;
2465         }
2466
2467         if (seq_must_swap_input_in_blend_mode(seq)) {
2468                 if (early_out == EARLY_USE_INPUT_2) {
2469                         return EARLY_USE_INPUT_1;
2470                 }
2471                 else if (early_out == EARLY_USE_INPUT_1) {
2472                         return EARLY_USE_INPUT_2;
2473                 }
2474         }
2475         return early_out;
2476 }
2477
2478 static ImBuf *seq_render_strip_stack(SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown)
2479 {
2480         Sequence *seq_arr[MAXSEQ + 1];
2481         int count;
2482         int i;
2483         ImBuf *out = NULL;
2484
2485         count = get_shown_sequences(seqbasep, cfra, chanshown, (Sequence **)&seq_arr);
2486
2487         if (count == 0) {
2488                 return NULL;
2489         }
2490
2491 #if 0 /* commentind since this breaks keyframing, since it resets the value on draw */
2492         if (scene->r.cfra != cfra) {
2493                 /* XXX for prefetch and overlay offset!..., very bad!!! */
2494                 AnimData *adt = BKE_animdata_from_id(&scene->id);
2495                 BKE_animsys_evaluate_animdata(scene, &scene->id, adt, cfra, ADT_RECALC_ANIM);
2496         }
2497 #endif
2498
2499         out = BKE_sequencer_cache_get(context, seq_arr[count - 1],  cfra, SEQ_STRIPELEM_IBUF_COMP);
2500
2501         if (out) {
2502                 return out;
2503         }
2504         
2505         if (count == 1) {
2506                 out = seq_render_strip(context, seq_arr[0], cfra);
2507                 BKE_sequencer_cache_put(context, seq_arr[0], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2508
2509                 return out;
2510         }
2511
2512
2513         for (i = count - 1; i >= 0; i--) {
2514                 int early_out;
2515                 Sequence *seq = seq_arr[i];
2516
2517                 out = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP);
2518
2519                 if (out) {
2520                         break;
2521                 }
2522                 if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2523                         out = seq_render_strip(context, seq, cfra);
2524                         break;
2525                 }
2526
2527                 early_out = seq_get_early_out_for_blend_mode(seq);
2528
2529                 switch (early_out) {
2530                         case EARLY_NO_INPUT:
2531                         case EARLY_USE_INPUT_2:
2532                                 out = seq_render_strip(context, seq, cfra);
2533                                 break;
2534                         case EARLY_USE_INPUT_1:
2535                                 if (i == 0) {
2536                                         out = IMB_allocImBuf(context.rectx, context.recty, 32, IB_rect);
2537                                 }
2538                                 break;
2539                         case EARLY_DO_EFFECT:
2540                                 if (i == 0) {
2541                                         out = seq_render_strip(context, seq, cfra);
2542                                 }
2543
2544                                 break;
2545                 }
2546                 if (out) {
2547                         break;
2548                 }
2549         }
2550
2551         BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2552
2553         i++;
2554
2555         for (; i < count; i++) {
2556                 Sequence *seq = seq_arr[i];
2557
2558                 if (seq_get_early_out_for_blend_mode(seq) == EARLY_DO_EFFECT) {
2559                         struct SeqEffectHandle sh = BKE_sequence_get_blend(seq);
2560                         ImBuf *ibuf1 = out;
2561                         ImBuf *ibuf2 = seq_render_strip(context, seq, cfra);
2562
2563                         float facf = seq->blend_opacity / 100.0f;
2564                         int swap_input = seq_must_swap_input_in_blend_mode(seq);
2565
2566                         if (swap_input) {
2567                                 if (sh.multithreaded)
2568                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL);
2569                                 else
2570                                         out = sh.execute(context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL);
2571                         }
2572                         else {
2573                                 if (sh.multithreaded)
2574                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL);
2575                                 else
2576                                         out = sh.execute(context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL);
2577                         }
2578                 
2579                         IMB_freeImBuf(ibuf1);
2580                         IMB_freeImBuf(ibuf2);
2581                 }
2582
2583                 BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out);
2584         }
2585
2586         return out;
2587 }
2588
2589 /*
2590  * returned ImBuf is refed!
2591  * you have to free after usage!
2592  */
2593
2594 ImBuf *BKE_sequencer_give_ibuf(SeqRenderData context, float cfra, int chanshown)
2595 {
2596         Editing *ed = BKE_sequencer_editing_get(context.scene, FALSE);
2597         int count;
2598         ListBase *seqbasep;
2599         
2600         if (ed == NULL) return NULL;
2601
2602         count = BLI_countlist(&ed->metastack);
2603         if ((chanshown < 0) && (count > 0)) {
2604                 count = MAX2(count + chanshown, 0);
2605                 seqbasep = ((MetaStack *)BLI_findlink(&ed->metastack, count))->oldbasep;
2606         }
2607         else {
2608                 seqbasep = ed->seqbasep;
2609         }
2610
2611         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2612 }
2613
2614 ImBuf *BKE_sequencer_give_ibuf_seqbase(SeqRenderData context, float cfra, int chanshown, ListBase *seqbasep)
2615 {
2616         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2617 }
2618
2619
2620 ImBuf *BKE_sequencer_give_ibuf_direct(SeqRenderData context, float cfra, Sequence *seq)
2621 {
2622         return seq_render_strip(context, seq, cfra);
2623 }
2624
2625 /* *********************** threading api ******************* */
2626
2627 static ListBase running_threads;
2628 static ListBase prefetch_wait;
2629 static ListBase prefetch_done;
2630
2631 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
2632 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
2633 static pthread_cond_t wakeup_cond          = PTHREAD_COND_INITIALIZER;
2634
2635 //static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
2636 //static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
2637
2638 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
2639 static pthread_cond_t frame_done_cond      = PTHREAD_COND_INITIALIZER;
2640
2641 static volatile int seq_thread_shutdown = TRUE; 
2642 static volatile int seq_last_given_monoton_cfra = 0;
2643 static int monoton_cfra = 0;
2644
2645 typedef struct PrefetchThread {
2646         struct PrefetchThread *next, *prev;
2647         
2648         Scene *scene;
2649         struct PrefetchQueueElem *current;
2650         pthread_t pthread;
2651         int running;
2652         
2653 } PrefetchThread;
2654
2655 typedef struct PrefetchQueueElem {
2656         struct PrefetchQueueElem *next, *prev;
2657         
2658         int rectx;
2659         int recty;
2660         float cfra;
2661         int chanshown;
2662         int preview_render_size;
2663
2664         int monoton_cfra;
2665
2666         ImBuf *ibuf;
2667 } PrefetchQueueElem;
2668
2669 void BKE_sequencer_give_ibuf_prefetch_request(SeqRenderData context, float cfra, int chanshown)
2670 {
2671         PrefetchQueueElem *e;
2672         if (seq_thread_shutdown) {
2673                 return;
2674         }
2675
2676         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
2677         e->rectx = context.rectx;
2678         e->recty = context.recty;
2679         e->cfra = cfra;
2680         e->chanshown = chanshown;
2681         e->preview_render_size = context.preview_render_size;
2682         e->monoton_cfra = monoton_cfra++;
2683
2684         pthread_mutex_lock(&queue_lock);
2685         BLI_addtail(&prefetch_wait, e);
2686         pthread_mutex_unlock(&queue_lock);
2687         
2688         pthread_mutex_lock(&wakeup_lock);
2689         pthread_cond_signal(&wakeup_cond);
2690         pthread_mutex_unlock(&wakeup_lock);
2691 }
2692
2693 ImBuf *BKE_sequencer_give_ibuf_threaded(SeqRenderData context, float cfra, int chanshown)
2694 {
2695         PrefetchQueueElem *e = NULL;
2696         int found_something = FALSE;
2697
2698         if (seq_thread_shutdown) {
2699                 return BKE_sequencer_give_ibuf(context, cfra, chanshown);
2700         }
2701
2702         while (!e) {
2703                 int success = FALSE;
2704                 pthread_mutex_lock(&queue_lock);
2705
2706                 for (e = prefetch_done.first; e; e = e->next) {
2707                         if (cfra == e->cfra &&
2708                             chanshown == e->chanshown &&
2709                             context.rectx == e->rectx &&
2710                             context.recty == e->recty &&
2711                             context.preview_render_size == e->preview_render_size)
2712                         {
2713                                 success = TRUE;
2714                                 found_something = TRUE;
2715                                 break;
2716                         }
2717                 }
2718
2719                 if (!e) {
2720                         for (e = prefetch_wait.first; e; e = e->next) {
2721                                 if (cfra == e->cfra &&
2722                                     chanshown == e->chanshown &&
2723                                     context.rectx == e->rectx &&
2724                                     context.recty == e->recty &&
2725                                     context.preview_render_size == e->preview_render_size)
2726                                 {
2727                                         found_something = TRUE;
2728                                         break;
2729                                 }
2730                         }
2731                 }
2732
2733                 if (!e) {
2734                         PrefetchThread *tslot;
2735
2736                         for (tslot = running_threads.first;
2737                              tslot;
2738                              tslot = tslot->next)
2739                         {
2740                                 if (tslot->current &&
2741                                     cfra == tslot->current->cfra &&
2742                                     chanshown == tslot->current->chanshown &&
2743                                     context.rectx == tslot->current->rectx &&
2744                                     context.recty == tslot->current->recty &&
2745                                     context.preview_render_size == tslot->current->preview_render_size)
2746                                 {
2747                                         found_something = TRUE;
2748                                         break;
2749                                 }
2750                         }
2751                 }
2752
2753                 /* e->ibuf is unrefed by render thread on next round. */
2754
2755                 if (e) {
2756                         seq_last_given_monoton_cfra = e->monoton_cfra;
2757                 }
2758
2759                 pthread_mutex_unlock(&queue_lock);
2760
2761                 if (!success) {
2762                         e = NULL;
2763
2764                         if (!found_something) {
2765                                 fprintf(stderr, "SEQ-THREAD: Requested frame not in queue ???\n");
2766                                 break;
2767                         }
2768                         pthread_mutex_lock(&frame_done_lock);
2769                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
2770                         pthread_mutex_unlock(&frame_done_lock);
2771                 }
2772         }
2773         
2774         return e ? e->ibuf : NULL;
2775 }
2776
2777 /* Functions to free imbuf and anim data on changes */
2778
2779 static void free_anim_seq(Sequence *seq)
2780 {
2781         if (seq->anim) {
2782                 IMB_free_anim(seq->anim);
2783                 seq->anim = NULL;
2784         }
2785 }
2786
2787 void BKE_sequence_invalidate_cache(Scene *scene, Sequence *seq)
2788 {
2789         Editing *ed = scene->ed;
2790         Sequence *cur;
2791         int left = seq->startdisp, right = seq->enddisp;
2792
2793         /* invalidate cache for current sequence */
2794         BKE_sequencer_cache_cleanup_sequence(seq);
2795
2796         /* invalidate cache for all dependent sequences */
2797         SEQ_BEGIN (ed, cur)
2798         {
2799                 int cur_left = cur->startdisp, cur_right = cur->enddisp;
2800
2801                 if (cur == seq)
2802                         continue;
2803
2804                 /* sequence is outside of changed one, shouldn't be invalidated */
2805                 if (cur_right < left || cur_left > right)
2806                         continue;
2807
2808                 /* sequence is below changed one, not dependent on it */
2809                 if (cur->machine < seq->machine)
2810                         continue;
2811
2812                 /* sequence is not blending with lower machines, no need to invalidate */
2813                 if ((cur->blend_mode == SEQ_BLEND_REPLACE) ||
2814                     (cur->blend_mode == SEQ_TYPE_CROSS && cur->blend_opacity == 100.0f))
2815                 {
2816                         continue;
2817                 }
2818
2819                 BKE_sequencer_cache_cleanup_sequence(cur);
2820         }
2821         SEQ_END
2822 }
2823
2824 void BKE_sequencer_free_imbuf(Scene *scene, ListBase *seqbase, int check_mem_usage, int keep_file_handles)
2825 {
2826         Sequence *seq;
2827
2828         if (check_mem_usage) {
2829                 /* Let the cache limitor take care of this (schlaile) */
2830                 /* While render let's keep all memory available for render 
2831                  * (ton)
2832                  * At least if free memory is tight...
2833                  * This can make a big difference in encoding speed
2834                  * (it is around 4 times(!) faster, if we do not waste time
2835                  * on freeing _all_ buffers every time on long timelines...)
2836                  * (schlaile)
2837                  */
2838         
2839                 uintptr_t mem_in_use;
2840                 uintptr_t mmap_in_use;
2841                 uintptr_t max;
2842         
2843                 mem_in_use = MEM_get_memory_in_use();
2844                 mmap_in_use = MEM_get_mapped_memory_in_use();
2845                 max = MEM_CacheLimiter_get_maximum();
2846         
2847                 if (max == 0 || mem_in_use + mmap_in_use <= max) {
2848                         return;
2849                 }
2850         }
2851
2852         BKE_sequencer_cache_cleanup();
2853         
2854         for (seq = seqbase->first; seq; seq = seq->next) {
2855                 if (seq->strip) {
2856                         if (seq->type == SEQ_TYPE_MOVIE && !keep_file_handles)
2857                                 free_anim_seq(seq);
2858                         if (seq->type == SEQ_TYPE_SPEED) {
2859                                 BKE_sequence_effect_speed_rebuild_map(scene, seq, 1);
2860                         }
2861                 }
2862                 if (seq->type == SEQ_TYPE_META) {
2863                         BKE_sequencer_free_imbuf(scene, &seq->seqbase, FALSE, keep_file_handles);
2864                 }
2865                 if (seq->type == SEQ_TYPE_SCENE) {
2866                         /* FIXME: recurs downwards, 
2867                          * but do recurs protection somehow! */
2868                 }
2869         }
2870         
2871 }
2872
2873 static int update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
2874 {
2875         Sequence *subseq;
2876         int free_imbuf = 0;
2877         
2878         /* recurs downwards to see if this seq depends on the changed seq */
2879         
2880         if (seq == NULL)
2881                 return 0;
2882         
2883         if (seq == changed_seq)
2884                 free_imbuf = 1;
2885         
2886         for (subseq = seq->seqbase.first; subseq; subseq = subseq->next)
2887                 if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change))
2888                         free_imbuf = TRUE;
2889         
2890         if (seq->seq1)
2891                 if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change))
2892                         free_imbuf = TRUE;
2893         if (seq->seq2 && (seq->seq2 != seq->seq1))
2894                 if (update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change))
2895                         free_imbuf = TRUE;
2896         if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
2897                 if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change))
2898                         free_imbuf = TRUE;
2899         
2900         if (free_imbuf) {
2901                 if (ibuf_change) {
2902                         if (seq->type == SEQ_TYPE_MOVIE)
2903                                 free_anim_seq(seq);
2904                         if (seq->type == SEQ_TYPE_SPEED) {
2905                                 BKE_sequence_effect_speed_rebuild_map(scene, seq, 1);
2906                         }
2907                 }
2908                 
2909                 if (len_change)
2910                         BKE_sequence_calc(scene, seq);
2911         }
2912         
2913         return free_imbuf;
2914 }
2915
2916 void BKE_sequencer_update_changed_seq_and_deps(Scene *scene, Sequence *changed_seq, int len_change, int ibuf_change)
2917 {
2918         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
2919         Sequence *seq;
2920         
2921         if (ed == NULL) return;
2922         
2923         for (seq = ed->seqbase.first; seq; seq = seq->next)
2924                 update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change);
2925 }
2926
2927 /* seq funcs's for transforming internally
2928  * notice the difference between start/end and left/right.
2929  *
2930  * left and right are the bounds at which the sequence is rendered,
2931  * start and end are from the start and fixed length of the sequence.
2932  */
2933 static int seq_tx_get_start(Sequence *seq)
2934 {
2935         return seq->start;
2936 }
2937 static int seq_tx_get_end(Sequence *seq)
2938 {
2939         return seq->start + seq->len;
2940 }
2941
2942 int BKE_sequence_tx_get_final_left(Sequence *seq, int metaclip)
2943 {
2944         if (metaclip && seq->tmp) {
2945                 /* return the range clipped by the parents range */
2946                 return maxi(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE));
2947         }
2948         else {
2949                 return (seq->start - seq->startstill) + seq->startofs;
2950         }
2951
2952 }
2953 int BKE_sequence_tx_get_final_right(Sequence *seq, int metaclip)
2954 {
2955         if (metaclip && seq->tmp) {
2956                 /* return the range clipped by the parents range */
2957                 return mini(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE));
2958         }
2959         else {
2960                 return ((seq->start + seq->len) + seq->endstill) - seq->endofs;
2961         }
2962 }
2963
2964 void BKE_sequence_tx_set_final_left(Sequence *seq, int val)
2965 {
2966         if (val < (seq)->start) {
2967                 seq->startstill = abs(val - (seq)->start);
2968                 seq->startofs = 0;
2969         }
2970         else {
2971                 seq->startofs = abs(val - (seq)->start);
2972                 seq->startstill = 0;
2973         }
2974 }
2975
2976 void BKE_sequence_tx_set_final_right(Sequence *seq, int val)
2977 {
2978         if (val > (seq)->start + (seq)->len) {
2979                 seq->endstill = abs(val - (seq->start + (seq)->len));
2980                 seq->endofs = 0;
2981         }
2982         else {
2983                 seq->endofs = abs(val - ((seq)->start + (seq)->len));
2984                 seq->endstill = 0;
2985         }
2986 }
2987
2988 /* used so we can do a quick check for single image seq
2989  * since they work a bit differently to normal image seq's (during transform) */
2990 int BKE_sequence_single_check(Sequence *seq)
2991 {
2992         return ((seq->len == 1) &&
2993                 (seq->type == SEQ_TYPE_IMAGE ||
2994                  ((seq->type & SEQ_TYPE_EFFECT) &&
2995                   BKE_sequence_effect_get_num_inputs(seq->type) == 0)));
2996 }
2997
2998 /* check if the selected seq's reference unselected seq's */
2999 int BKE_sequence_base_isolated_sel_check(ListBase *seqbase)
3000 {
3001         Sequence *seq;
3002         /* is there more than 1 select */
3003         int ok = FALSE;
3004
3005         for (seq = seqbase->first; seq; seq = seq->next) {
3006                 if (seq->flag & SELECT) {
3007                         ok = TRUE;
3008                         break;
3009                 }
3010         }
3011
3012         if (ok == FALSE)
3013                 return FALSE;
3014
3015         /* test relationships */
3016         for (seq = seqbase->first; seq; seq = seq->next) {
3017                 if ((seq->type & SEQ_TYPE_EFFECT) == 0)
3018                         continue;
3019
3020                 if (seq->flag & SELECT) {
3021                         if ( (seq->seq1 && (seq->seq1->flag & SELECT) == 0) ||
3022                              (seq->seq2 && (seq->seq2->flag & SELECT) == 0) ||
3023                              (seq->seq3 && (seq->seq3->flag & SELECT) == 0) )
3024                         {
3025                                 return FALSE;
3026                         }
3027                 }
3028                 else {
3029                         if ( (seq->seq1 && (seq->seq1->flag & SELECT)) ||
3030                              (seq->seq2 && (seq->seq2->flag & SELECT)) ||
3031                              (seq->seq3 && (seq->seq3->flag & SELECT)) )
3032                         {
3033                                 return FALSE;
3034                         }
3035                 }
3036         }
3037
3038         return TRUE;
3039 }
3040
3041 /* use to impose limits when dragging/extending - so impossible situations don't happen
3042  * Cant use the SEQ_LEFTSEL and SEQ_LEFTSEL directly because the strip may be in a metastrip */
3043 void BKE_sequence_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag)
3044 {
3045         if (leftflag) {
3046                 if (BKE_sequence_tx_get_final_left(seq, 0) >= BKE_sequence_tx_get_final_right(seq, 0)) {
3047                         BKE_sequence_tx_set_final_left(seq, BKE_sequence_tx_get_final_right(seq, 0) - 1);
3048                 }
3049
3050                 if (BKE_sequence_single_check(seq) == 0) {
3051                         if (BKE_sequence_tx_get_final_left(seq, 0) >= seq_tx_get_end(seq)) {
3052                                 BKE_sequence_tx_set_final_left(seq, seq_tx_get_end(seq) - 1);
3053                         }
3054
3055                         /* dosnt work now - TODO */
3056 #if 0
3057                         if (seq_tx_get_start(seq) >= seq_tx_get_final_right(seq, 0)) {
3058                                 int ofs;
3059                                 ofs = seq_tx_get_start(seq) - seq_tx_get_final_right(seq, 0);
3060                                 seq->start -= ofs;
3061                                 seq_tx_set_final_left(seq, seq_tx_get_final_left(seq, 0) + ofs);
3062                         }
3063 #endif
3064                 }
3065         }
3066
3067         if (rightflag) {
3068                 if (BKE_sequence_tx_get_final_right(seq, 0) <= BKE_sequence_tx_get_final_left(seq, 0)) {
3069                         BKE_sequence_tx_set_final_right(seq, BKE_sequence_tx_get_final_left(seq, 0) + 1);
3070                 }
3071
3072                 if (BKE_sequence_single_check(seq) == 0) {
3073                         if (BKE_sequence_tx_get_final_right(seq, 0) <= seq_tx_get_start(seq)) {
3074                                 BKE_sequence_tx_set_final_right(seq, seq_tx_get_start(seq) + 1);
3075                         }
3076                 }
3077         }
3078
3079         /* sounds cannot be extended past their endpoints */
3080         if (seq->type == SEQ_TYPE_SOUND_RAM) {
3081                 seq->startstill = 0;
3082                 seq->endstill = 0;
3083         }
3084 }
3085
3086 void BKE_sequence_single_fix(Sequence *seq)
3087 {
3088         int left, start, offset;
3089         if (!BKE_sequence_single_check(seq))
3090                 return;
3091
3092         /* make sure the image is always at the start since there is only one,
3093          * adjusting its start should be ok */
3094         left = BKE_sequence_tx_get_final_left(seq, 0);
3095         start = seq->start;
3096         if (start != left) {
3097                 offset = left - start;
3098                 BKE_sequence_tx_set_final_left(seq, BKE_sequence_tx_get_final_left(seq, 0) - offset);
3099                 BKE_sequence_tx_set_final_right(seq, BKE_sequence_tx_get_final_right(seq, 0) - offset);
3100                 seq->start += offset;
3101         }
3102 }
3103
3104 int BKE_sequence_tx_test(Sequence *seq)
3105 {
3106         return (seq->type < SEQ_TYPE_EFFECT) || (BKE_sequence_effect_get_num_inputs(seq->type) == 0);
3107 }
3108
3109 static int seq_overlap(Sequence *seq1, Sequence *seq2)
3110 {
3111         return (seq1 != seq2 && seq1->machine == seq2->machine &&
3112                 ((seq1->enddisp <= seq2->startdisp) || (seq1->startdisp >= seq2->enddisp)) == 0);
3113 }
3114
3115 int BKE_sequence_test_overlap(ListBase *seqbasep, Sequence *test)
3116 {
3117         Sequence *seq;
3118
3119         seq = seqbasep->first;
3120         while (seq) {
3121                 if (seq_overlap(test, seq))
3122                         return 1;
3123
3124                 seq = seq->next;
3125         }
3126         return 0;
3127 }
3128
3129
3130 void BKE_sequence_translate(Scene *evil_scene, Sequence *seq, int delta)
3131 {
3132         BKE_sequencer_offset_animdata(evil_scene, seq, delta);
3133         seq->start += delta;
3134
3135         if (seq->type == SEQ_TYPE_META) {
3136                 Sequence *seq_child;
3137                 for (seq_child = seq->seqbase.first; seq_child; seq_child = seq_child->next) {
3138                         BKE_sequence_translate(evil_scene, seq_child, delta);
3139                 }
3140         }
3141
3142         BKE_sequence_calc_disp(evil_scene, seq);
3143 }
3144
3145 void BKE_sequence_sound_init(Scene *scene, Sequence *seq)
3146 {
3147         if (seq->type == SEQ_TYPE_META) {
3148                 Sequence *seq_child;
3149                 for (seq_child = seq->seqbase.first; seq_child; seq_child = seq_child->next) {
3150                         BKE_sequence_sound_init(scene, seq_child);
3151                 }
3152         }
3153         else {
3154                 if (seq->sound) {
3155                         seq->scene_sound = sound_add_scene_sound_defaults(scene, seq);
3156                 }
3157                 if (seq->scene) {
3158                         sound_scene_add_scene_sound_defaults(scene, seq);
3159                 }
3160         }
3161 }
3162
3163 Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame)
3164 {
3165         Editing *ed = BKE_sequencer_editing_get(scene, FALSE);
3166         Sequence *seq, *best_seq = NULL;
3167         int best_machine = -1;
3168         
3169         if (!ed) return NULL;
3170         
3171         for (seq = ed->seqbasep->first; seq; seq = seq->next) {
3172                 if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame)
3173                         continue;
3174                 /* only use elements you can see - not */
3175                 if (ELEM5(seq->type, SEQ_TYPE_IMAGE, SEQ_TYPE_META, SEQ_TYPE_SCENE, SEQ_TYPE_MOVIE, SEQ_TYPE_COLOR)) {
3176                         if (seq->machine > best_machine) {
3177                                 best_seq = seq;
3178                                 best_machine = seq->machine;
3179                         }
3180                 }
3181         }
3182         return best_seq;
3183 }
3184
3185 /* return 0 if there werent enough space */
3186 int BKE_sequence_base_shuffle(ListBase *seqbasep, Sequence *test, Scene *evil_scene)
3187 {
3188         int orig_machine = test->machine;
3189         test->machine++;
3190         BKE_sequence_calc(evil_scene, test);
3191         while (BKE_sequence_test_overlap(seqbasep, test) ) {
3192                 if (test->machine >= MAXSEQ) {
3193                         break;
3194                 }
3195                 test->machine++;
3196                 BKE_sequence_calc(evil_scene, test); // XXX - I don't think this is needed since were only moving vertically, Campbell.
3197         }
3198
3199         
3200         if (test->machine >= MAXSEQ) {
3201                 /* Blender 2.4x would remove the strip.
3202                  * nicer to move it to the end */
3203
3204                 Sequence *seq;
3205                 int new_frame = test->enddisp;
3206
3207                 for (seq = seqbasep->first; seq; seq = seq->next) {
3208                         if (seq->machine == orig_machine)
3209                                 new_frame = MAX2(new_frame, seq->enddisp);
3210                 }
3211
3212                 test->machine = orig_machine;
3213                 new_frame = new_frame + (test->start - test->startdisp); /* adjust by the startdisp */
3214                 BKE_sequence_translate(evil_scene, test, new_frame - test->start);
3215
3216                 BKE_sequence_calc(evil_scene, test);
3217                 return 0;
3218         }
3219         else {
3220                 return 1;
3221         }
3222 }
3223
3224 static int shuffle_seq_time_offset_test(ListBase *seqbasep, char dir)
3225 {
3226         int offset = 0;
3227         Sequence *seq, *seq_other;
3228
3229         for (seq = seqbasep->first; seq; seq = seq->next) {
3230                 if (seq->tmp) {
3231                         for (seq_other = seqbasep->first; seq_other; seq_other = seq_other->next) {
3232                                 if (!seq_other->tmp && seq_overlap(seq, seq_other)) {
3233                                         if (dir == 'L') {
3234                                                 offset = MIN2(offset, seq_other->startdisp - seq->enddisp);
3235                                         }
3236                                         else {
3237                                                 offset = MAX2(offset, seq_other->enddisp - seq->startdisp);
3238                                         }
3239                                 }
3240                         }
3241                 }
3242         }
3243         return offset;
3244 }
3245
3246 static int shuffle_seq_time_offset(Scene *scene, ListBase *seqbasep, char dir)
3247 {
3248         int ofs = 0;
3249