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