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