Merging r39631 through r39633 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                 break;
718         case SEQ_SOUND:
719 #ifdef WITH_AUDASPACE
720                 if(!seq->sound)
721                         return;
722                 seq->len = ceil(AUD_getInfo(seq->sound->playback_handle).length * FPS);
723                 seq->len -= seq->anim_startofs;
724                 seq->len -= seq->anim_endofs;
725                 if (seq->len < 0) {
726                         seq->len = 0;
727                 }
728                 seq->strip->len = seq->len;
729 #else
730                 return;
731 #endif
732                 break;
733         case SEQ_SCENE:
734         {
735                 /* 'seq->scenenr' should be replaced with something more reliable */
736                 Scene * sce = G.main->scene.first;
737                 int nr = 1;
738                 
739                 while(sce) {
740                         if(nr == seq->scenenr) {
741                                 break;
742                         }
743                         nr++;
744                         sce= sce->id.next;
745                 }
746
747                 if (sce) {
748                         seq->scene = sce;
749                 }
750
751                 seq->len= seq->scene->r.efra - seq->scene->r.sfra + 1;
752                 seq->len -= seq->anim_startofs;
753                 seq->len -= seq->anim_endofs;
754                 if (seq->len < 0) {
755                         seq->len = 0;
756                 }
757                 seq->strip->len = seq->len;
758                 break;
759         }
760         }
761
762         free_proxy_seq(seq);
763
764         if(lock_range) {
765                 seq_tx_set_final_left(seq, prev_startdisp);
766                 seq_tx_set_final_right(seq, prev_enddisp);
767                 seq_single_fix(seq);
768         }
769         
770         calc_sequence(scene, seq);
771 }
772
773 void sort_seq(Scene *scene)
774 {
775         /* all strips together per kind, and in order of y location ("machine") */
776         ListBase seqbase, effbase;
777         Editing *ed= seq_give_editing(scene, FALSE);
778         Sequence *seq, *seqt;
779
780         
781         if(ed==NULL) return;
782
783         seqbase.first= seqbase.last= NULL;
784         effbase.first= effbase.last= NULL;
785
786         while( (seq= ed->seqbasep->first) ) {
787                 BLI_remlink(ed->seqbasep, seq);
788
789                 if(seq->type & SEQ_EFFECT) {
790                         seqt= effbase.first;
791                         while(seqt) {
792                                 if(seqt->machine>=seq->machine) {
793                                         BLI_insertlinkbefore(&effbase, seqt, seq);
794                                         break;
795                                 }
796                                 seqt= seqt->next;
797                         }
798                         if(seqt==NULL) BLI_addtail(&effbase, seq);
799                 }
800                 else {
801                         seqt= seqbase.first;
802                         while(seqt) {
803                                 if(seqt->machine>=seq->machine) {
804                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
805                                         break;
806                                 }
807                                 seqt= seqt->next;
808                         }
809                         if(seqt==NULL) BLI_addtail(&seqbase, seq);
810                 }
811         }
812
813         BLI_movelisttolist(&seqbase, &effbase);
814         *(ed->seqbasep)= seqbase;
815 }
816
817
818 static int clear_scene_in_allseqs_cb(Sequence *seq, void *arg_pt)
819 {
820         if(seq->scene==(Scene *)arg_pt)
821                 seq->scene= NULL;
822         return 1;
823 }
824
825 void clear_scene_in_allseqs(Main *bmain, Scene *scene)
826 {
827         Scene *scene_iter;
828
829         /* when a scene is deleted: test all seqs */
830         for(scene_iter= bmain->scene.first; scene_iter; scene_iter= scene_iter->id.next) {
831                 if(scene_iter != scene && scene_iter->ed) {
832                         seqbase_recursive_apply(&scene_iter->ed->seqbase, clear_scene_in_allseqs_cb, scene);
833                 }
834         }
835 }
836
837 typedef struct SeqUniqueInfo {
838         Sequence *seq;
839         char name_src[32];
840         char name_dest[32];
841         int count;
842         int match;
843 } SeqUniqueInfo;
844
845 /*
846 static void seqbase_unique_name(ListBase *seqbasep, Sequence *seq)
847 {
848         BLI_uniquename(seqbasep, seq, "Sequence", '.', offsetof(Sequence, name), SEQ_NAME_MAXSTR);
849 }*/
850
851 static void seqbase_unique_name(ListBase *seqbasep, SeqUniqueInfo *sui)
852 {
853         Sequence *seq;
854         for(seq=seqbasep->first; seq; seq= seq->next) {
855                 if (sui->seq != seq && strcmp(sui->name_dest, seq->name+2)==0) {
856                         sprintf(sui->name_dest, "%.17s.%03d",  sui->name_src, sui->count++); /*24 - 2 for prefix, -1 for \0 */
857                         sui->match= 1; /* be sure to re-scan */
858                 }
859         }
860 }
861
862 static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt)
863 {
864         if(seq->seqbase.first)
865                 seqbase_unique_name(&seq->seqbase, (SeqUniqueInfo *)arg_pt);
866         return 1;
867 }
868
869 void seqbase_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq)
870 {
871         SeqUniqueInfo sui;
872         char *dot;
873         sui.seq= seq;
874         strcpy(sui.name_src, seq->name+2);
875         strcpy(sui.name_dest, seq->name+2);
876
877         sui.count= 1;
878         sui.match= 1; /* assume the worst to start the loop */
879
880         /* Strip off the suffix */
881         if ((dot=strrchr(sui.name_src, '.'))) {
882                 *dot= '\0';
883                 dot++;
884
885                 if(*dot)
886                         sui.count= atoi(dot) + 1;
887         }
888
889         while(sui.match) {
890                 sui.match= 0;
891                 seqbase_unique_name(seqbasep, &sui);
892                 seqbase_recursive_apply(seqbasep, seqbase_unique_name_recursive_cb, &sui);
893         }
894
895         strcpy(seq->name+2, sui.name_dest);
896 }
897
898 static const char *give_seqname_by_type(int type)
899 {
900         switch(type) {
901         case SEQ_META:       return "Meta";
902         case SEQ_IMAGE:      return "Image";
903         case SEQ_SCENE:      return "Scene";
904         case SEQ_MOVIE:      return "Movie";
905         case SEQ_SOUND:      return "Audio";
906         case SEQ_CROSS:      return "Cross";
907         case SEQ_GAMCROSS:   return "Gamma Cross";
908         case SEQ_ADD:        return "Add";
909         case SEQ_SUB:        return "Sub";
910         case SEQ_MUL:        return "Mul";
911         case SEQ_ALPHAOVER:  return "Alpha Over";
912         case SEQ_ALPHAUNDER: return "Alpha Under";
913         case SEQ_OVERDROP:   return "Over Drop";
914         case SEQ_WIPE:       return "Wipe";
915         case SEQ_GLOW:       return "Glow";
916         case SEQ_TRANSFORM:  return "Transform";
917         case SEQ_COLOR:      return "Color";
918         case SEQ_MULTICAM:   return "Multicam";
919         case SEQ_ADJUSTMENT: return "Adjustment";
920         case SEQ_SPEED:      return "Speed";
921         default:
922                 return NULL;
923         }
924 }
925
926 const char *give_seqname(Sequence *seq)
927 {
928         const char *name = give_seqname_by_type(seq->type);
929
930         if (!name) {
931                 if(seq->type<SEQ_EFFECT) {
932                         return seq->strip->dir;
933                 } else if(seq->type==SEQ_PLUGIN) {
934                         if(!(seq->flag & SEQ_EFFECT_NOT_LOADED) &&
935                            seq->plugin && seq->plugin->doit) {
936                                 return seq->plugin->pname;
937                         } else {
938                                 return "Plugin";
939                         }
940                 } else {
941                         return "Effect";
942                 }
943         }
944         return name;
945 }
946
947 /* ***************** DO THE SEQUENCE ***************** */
948
949 static void make_black_ibuf(ImBuf *ibuf)
950 {
951         unsigned int *rect;
952         float *rect_float;
953         int tot;
954
955         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL)) return;
956
957         tot= ibuf->x*ibuf->y;
958
959         rect= ibuf->rect;
960         rect_float = ibuf->rect_float;
961
962         if (rect) {
963                 memset(rect,       0, tot * sizeof(char) * 4);
964         }
965
966         if (rect_float) {
967                 memset(rect_float, 0, tot * sizeof(float) * 4);
968         }
969 }
970
971 static void multibuf(ImBuf *ibuf, float fmul)
972 {
973         char *rt;
974         float *rt_float;
975
976         int a, mul, icol;
977
978         mul= (int)(256.0f * fmul);
979         rt= (char *)ibuf->rect;
980         rt_float = ibuf->rect_float;
981
982         if (rt) {
983                 a= ibuf->x*ibuf->y;
984                 while(a--) {
985
986                         icol= (mul*rt[0])>>8;
987                         if(icol>254) rt[0]= 255; else rt[0]= icol;
988                         icol= (mul*rt[1])>>8;
989                         if(icol>254) rt[1]= 255; else rt[1]= icol;
990                         icol= (mul*rt[2])>>8;
991                         if(icol>254) rt[2]= 255; else rt[2]= icol;
992                         icol= (mul*rt[3])>>8;
993                         if(icol>254) rt[3]= 255; else rt[3]= icol;
994                         
995                         rt+= 4;
996                 }
997         }
998         if (rt_float) {
999                 a= ibuf->x*ibuf->y;
1000                 while(a--) {
1001                         rt_float[0] *= fmul;
1002                         rt_float[1] *= fmul;
1003                         rt_float[2] *= fmul;
1004                         rt_float[3] *= fmul;
1005                         
1006                         rt_float += 4;
1007                 }
1008         }
1009 }
1010
1011 static float give_stripelem_index(Sequence *seq, float cfra)
1012 {
1013         float nr;
1014         int sta = seq->start;
1015         int end = seq->start+seq->len-1;
1016
1017         if (seq->type & SEQ_EFFECT) {
1018                 end = seq->enddisp;
1019         } 
1020
1021         if(end < sta) {
1022                 return -1;
1023         }
1024
1025         if(seq->flag&SEQ_REVERSE_FRAMES) {      
1026                 /*reverse frame in this sequence */
1027                 if(cfra <= sta) nr= end - sta;
1028                 else if(cfra >= end) nr= 0;
1029                 else nr= end - cfra;
1030         } else {
1031                 if(cfra <= sta) nr= 0;
1032                 else if(cfra >= end) nr= end - sta;
1033                 else nr= cfra - sta;
1034         }
1035         
1036         if (seq->strobe < 1.0f) seq->strobe = 1.0f;
1037         
1038         if (seq->strobe > 1.0f) {
1039                 nr -= fmodf((double)nr, (double)seq->strobe);
1040         }
1041
1042         return nr;
1043 }
1044
1045 StripElem *give_stripelem(Sequence *seq, int cfra)
1046 {
1047         StripElem *se= seq->strip->stripdata;
1048
1049         if(seq->type == SEQ_IMAGE) { /* only 
1050                                         IMAGE strips use the whole array,
1051                                         MOVIE strips use only 
1052                                         the first element, all other strips
1053                                         don't use this... */
1054                 int nr = (int) give_stripelem_index(seq, cfra);
1055
1056                 if (nr == -1 || se == NULL) return NULL;
1057         
1058                 se += nr + seq->anim_startofs;
1059         }
1060         return se;
1061 }
1062
1063 static int evaluate_seq_frame_gen(Sequence ** seq_arr, ListBase *seqbase, int cfra)
1064 {
1065         Sequence *seq;
1066         int totseq=0;
1067
1068         memset(seq_arr, 0, sizeof(Sequence*) * (MAXSEQ+1));
1069
1070         seq= seqbase->first;
1071         while(seq) {
1072                 if(seq->startdisp <=cfra && seq->enddisp > cfra) {
1073                         seq_arr[seq->machine]= seq;
1074                         totseq++;
1075                 }
1076                 seq= seq->next;
1077         }
1078
1079         return totseq;
1080 }
1081
1082 int evaluate_seq_frame(Scene *scene, int cfra)
1083 {
1084         Editing *ed= seq_give_editing(scene, FALSE);
1085         Sequence *seq_arr[MAXSEQ+1];
1086
1087         if(ed==NULL) return 0;
1088         return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
1089 }
1090
1091 static int video_seq_is_rendered(Sequence * seq)
1092 {
1093         return (seq && !(seq->flag & SEQ_MUTE) && seq->type != SEQ_SOUND);
1094 }
1095
1096 static int get_shown_sequences( ListBase * seqbasep, int cfra, int chanshown, Sequence ** seq_arr_out)
1097 {
1098         Sequence *seq_arr[MAXSEQ+1];
1099         int b = chanshown;
1100         int cnt = 0;
1101
1102         if (b > MAXSEQ) {
1103                 return 0;
1104         }
1105
1106         if(evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
1107                 if (b == 0) {
1108                         b = MAXSEQ;
1109                 }
1110                 for (; b > 0; b--) {
1111                         if (video_seq_is_rendered(seq_arr[b])) {
1112                                 break;
1113                         }
1114                 }
1115         }
1116         
1117         chanshown = b;
1118
1119         for (;b > 0; b--) {
1120                 if (video_seq_is_rendered(seq_arr[b])) {
1121                         if (seq_arr[b]->blend_mode == SEQ_BLEND_REPLACE) {
1122                                 break;
1123                         }
1124                 }
1125         }
1126
1127         for (;b <= chanshown && b >= 0; b++) {
1128                 if (video_seq_is_rendered(seq_arr[b])) {
1129                         seq_arr_out[cnt++] = seq_arr[b];
1130                 }
1131         }
1132
1133         return cnt;
1134 }
1135
1136
1137 /* **********************************************************************
1138    proxy management
1139    ********************************************************************** */
1140
1141 #define PROXY_MAXFILE (2*FILE_MAXDIR+FILE_MAXFILE)
1142
1143 static IMB_Proxy_Size seq_rendersize_to_proxysize(int size)
1144 {
1145         if (size >= 100) {
1146                 return IMB_PROXY_NONE;
1147         }
1148         if (size >= 75) {
1149                 return IMB_PROXY_75;
1150         }
1151         if (size >= 50) {
1152                 return IMB_PROXY_50;
1153         }
1154         return IMB_PROXY_25;
1155 }
1156
1157 static void seq_open_anim_file(Sequence * seq)
1158 {
1159         char name[FILE_MAXDIR+FILE_MAXFILE];
1160         StripProxy * proxy;
1161
1162         if(seq->anim != NULL) {
1163                 return;
1164         }
1165
1166         BLI_join_dirfile(name, sizeof(name), 
1167                          seq->strip->dir, seq->strip->stripdata->name);
1168         BLI_path_abs(name, G.main->name);
1169         
1170         seq->anim = openanim(name, IB_rect |
1171                              ((seq->flag & SEQ_FILTERY) ? 
1172                               IB_animdeinterlace : 0));
1173
1174         if (seq->anim == NULL) {
1175                 return;
1176         }
1177
1178         proxy = seq->strip->proxy;
1179
1180         if (proxy == NULL) {
1181                 return;
1182         }
1183
1184         if (seq->flag & SEQ_USE_PROXY_CUSTOM_DIR) {
1185                 IMB_anim_set_index_dir(seq->anim, seq->strip->proxy->dir);
1186         }
1187 }
1188
1189
1190 static int seq_proxy_get_fname(SeqRenderData context, Sequence * seq, int cfra, char * name)
1191 {
1192         int frameno;
1193         char dir[FILE_MAXDIR];
1194
1195         if (!seq->strip->proxy) {
1196                 return FALSE;
1197         }
1198
1199         /* MOVIE tracks (only exception: custom files) are now handled 
1200            internally by ImBuf module for various reasons: proper time code 
1201            support, quicker index build, using one file instead 
1202            of a full directory of jpeg files, etc. Trying to support old
1203            and new method at once could lead to funny effects, if people
1204            have both, a directory full of jpeg files and proxy avis, so
1205            sorry folks, please rebuild your proxies... */
1206
1207         if (seq->flag & (SEQ_USE_PROXY_CUSTOM_DIR|SEQ_USE_PROXY_CUSTOM_FILE)) {
1208                 strcpy(dir, seq->strip->proxy->dir);
1209         } else if (seq->type == SEQ_IMAGE) {
1210                 snprintf(dir, PROXY_MAXFILE, "%s/BL_proxy", seq->strip->dir);
1211         } else {
1212                 return FALSE;
1213         }
1214
1215         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1216                 BLI_join_dirfile(name, PROXY_MAXFILE, 
1217                                  dir, seq->strip->proxy->file);
1218                 BLI_path_abs(name, G.main->name);
1219
1220                 return TRUE;
1221         }
1222
1223         /* generate a separate proxy directory for each preview size */
1224
1225         if (seq->type == SEQ_IMAGE) {
1226                 snprintf(name, PROXY_MAXFILE, "%s/images/%d/%s_proxy", dir,
1227                          context.preview_render_size, 
1228                          give_stripelem(seq, cfra)->name);
1229                 frameno = 1;
1230         } else {
1231                 frameno = (int) give_stripelem_index(seq, cfra) 
1232                         + seq->anim_startofs;
1233                 snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####", dir, 
1234                          context.preview_render_size);
1235         }
1236
1237         BLI_path_abs(name, G.main->name);
1238         BLI_path_frame(name, frameno, 0);
1239
1240         strcat(name, ".jpg");
1241
1242         return TRUE;
1243 }
1244
1245 static struct ImBuf * seq_proxy_fetch(SeqRenderData context, Sequence * seq, int cfra)
1246 {
1247         char name[PROXY_MAXFILE];
1248
1249         if (!(seq->flag & SEQ_USE_PROXY)) {
1250                 return NULL;
1251         }
1252
1253         /* rendering at 100% ? No real sense in proxy-ing, right? */
1254         if (context.preview_render_size == 100) {
1255                 return NULL;
1256         }
1257
1258         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1259                 int frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1260                 if (seq->strip->proxy->anim == NULL) {
1261                         if (seq_proxy_get_fname(context, seq, cfra, name)==0) {
1262                                 return NULL;
1263                         }
1264  
1265                         seq->strip->proxy->anim = openanim(name, IB_rect);
1266                 }
1267                 if (seq->strip->proxy->anim==NULL) {
1268                         return NULL;
1269                 }
1270  
1271                 seq_open_anim_file(seq);
1272
1273                 frameno = IMB_anim_index_get_frame_index(
1274                         seq->anim, seq->strip->proxy->tc, frameno);
1275
1276                 return IMB_anim_absolute(seq->strip->proxy->anim, frameno,
1277                                          IMB_TC_NONE, IMB_PROXY_NONE);
1278         }
1279  
1280         if (seq_proxy_get_fname(context, seq, cfra, name) == 0) {
1281                 return NULL;
1282         }
1283
1284         if (BLI_exists(name)) {
1285                 return IMB_loadiffname(name, IB_rect);
1286         } else {
1287                 return NULL;
1288         }
1289 }
1290
1291 static void seq_proxy_build_frame(SeqRenderData context,
1292                                   Sequence* seq, int cfra,
1293                                   int proxy_render_size)
1294 {
1295         char name[PROXY_MAXFILE];
1296         int quality;
1297         int rectx, recty;
1298         int ok;
1299         struct ImBuf * ibuf;
1300
1301         if (!seq_proxy_get_fname(context, seq, cfra, name)) {
1302                 return;
1303         }
1304
1305         ibuf = seq_render_strip(context, seq, cfra);
1306
1307         rectx = (proxy_render_size * context.scene->r.xsch) / 100;
1308         recty = (proxy_render_size * context.scene->r.ysch) / 100;
1309
1310         if (ibuf->x != rectx || ibuf->y != recty) {
1311                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1312         }
1313
1314         /* quality is fixed, otherwise one has to generate separate
1315            directories for every quality...
1316
1317            depth = 32 is intentionally left in, otherwise ALPHA channels
1318            won't work... */
1319         quality = seq->strip->proxy->quality;
1320         ibuf->ftype= JPG | quality;
1321
1322         /* unsupported feature only confuses other s/w */
1323         if(ibuf->depth==32)
1324                 ibuf->depth= 24;
1325
1326         BLI_make_existing_file(name);
1327         
1328         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1329         if (ok == 0) {
1330                 perror(name);
1331         }
1332
1333         IMB_freeImBuf(ibuf);
1334 }
1335
1336 void seq_proxy_rebuild(struct Main * bmain, Scene *scene, Sequence * seq,
1337                        short *stop, short *do_update, float *progress)
1338 {
1339         SeqRenderData context;
1340         int cfra;
1341         int tc_flags;
1342         int size_flags;
1343         int quality;
1344
1345         if (!seq->strip || !seq->strip->proxy) {
1346                 return;
1347         }
1348
1349         if (!(seq->flag & SEQ_USE_PROXY)) {
1350                 return;
1351         }
1352
1353         tc_flags   = seq->strip->proxy->build_tc_flags;
1354         size_flags = seq->strip->proxy->build_size_flags;
1355         quality    = seq->strip->proxy->quality;
1356
1357         if (seq->type == SEQ_MOVIE) {
1358                 seq_open_anim_file(seq);
1359
1360                 if (seq->anim) {
1361                         IMB_anim_index_rebuild(
1362                                 seq->anim, tc_flags, size_flags, quality,
1363                                 stop, do_update, progress);
1364                 }
1365                 return;
1366         }
1367
1368         if (!(seq->flag & SEQ_USE_PROXY)) {
1369                 return;
1370         }
1371
1372         /* that's why it is called custom... */
1373         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1374                 return;
1375         }
1376
1377         /* fail safe code */
1378
1379         context = seq_new_render_data(
1380                 bmain, scene, 
1381                 (scene->r.size * (float) scene->r.xsch) / 100.0f + 0.5f, 
1382                 (scene->r.size * (float) scene->r.ysch) / 100.0f + 0.5f, 
1383                 100);
1384
1385         for (cfra = seq->startdisp + seq->startstill; 
1386              cfra < seq->enddisp - seq->endstill; cfra++) {
1387                 if (size_flags & IMB_PROXY_25) {
1388                         seq_proxy_build_frame(context, seq, cfra, 25);
1389                 }
1390                 if (size_flags & IMB_PROXY_50) {
1391                         seq_proxy_build_frame(context, seq, cfra, 50);
1392                 }
1393                 if (size_flags & IMB_PROXY_75) {
1394                         seq_proxy_build_frame(context, seq, cfra, 75);
1395                 }
1396
1397                 *progress= (float)cfra/(seq->enddisp - seq->endstill - seq->startdisp + seq->startstill);
1398                 *do_update= 1;
1399
1400                 if(*stop || G.afbreek)
1401                         break;
1402         }
1403 }
1404
1405
1406 /* **********************************************************************
1407    color balance 
1408    ********************************************************************** */
1409
1410 static StripColorBalance calc_cb(StripColorBalance * cb_)
1411 {
1412         StripColorBalance cb = *cb_;
1413         int c;
1414
1415         for (c = 0; c < 3; c++) {
1416                 cb.lift[c] = 2.0f - cb.lift[c];
1417         }
1418
1419         if(cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1420                 for (c = 0; c < 3; c++) {
1421                         /* tweak to give more subtle results
1422                          * values above 1.0 are scaled */
1423                         if(cb.lift[c] > 1.0f)
1424                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0;
1425
1426                         cb.lift[c] = 2.0f - cb.lift[c];
1427                 }
1428         }
1429
1430         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1431                 for (c = 0; c < 3; c++) {
1432                         if (cb.gain[c] != 0.0f) {
1433                                 cb.gain[c] = 1.0f / cb.gain[c];
1434                         } else {
1435                                 cb.gain[c] = 1000000; /* should be enough :) */
1436                         }
1437                 }
1438         }
1439
1440         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1441                 for (c = 0; c < 3; c++) {
1442                         if (cb.gamma[c] != 0.0f) {
1443                                 cb.gamma[c] = 1.0f/cb.gamma[c];
1444                         } else {
1445                                 cb.gamma[c] = 1000000; /* should be enough :) */
1446                         }
1447                 }
1448         }
1449
1450         return cb;
1451 }
1452
1453 /* note: lift is actually 2-lift */
1454 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1455 {
1456         float x= (((in - 1.0f) * lift) + 1.0f) * gain;
1457
1458         /* prevent NaN */
1459         if (x < 0.f) x = 0.f;
1460
1461         return powf(x, gamma) * mul;
1462 }
1463
1464 static void make_cb_table_byte(float lift, float gain, float gamma,
1465                                    unsigned char * table, float mul)
1466 {
1467         int y;
1468
1469         for (y = 0; y < 256; y++) {
1470                 float v= color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1471                 CLAMP(v, 0.0f, 1.0f);
1472                 table[y] = v * 255;
1473         }
1474 }
1475
1476 static void make_cb_table_float(float lift, float gain, float gamma,
1477                                 float * table, float mul)
1478 {
1479         int y;
1480
1481         for (y = 0; y < 256; y++) {
1482                 float v= color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1483                 table[y] = v;
1484         }
1485 }
1486
1487 static void color_balance_byte_byte(Sequence * seq, ImBuf* ibuf, float mul)
1488 {
1489         unsigned char cb_tab[3][256];
1490         int c;
1491         unsigned char * p = (unsigned char*) ibuf->rect;
1492         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1493
1494         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1495
1496         for (c = 0; c < 3; c++) {
1497                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c],
1498                                    cb_tab[c], mul);
1499         }
1500
1501         while (p < e) {
1502                 p[0] = cb_tab[0][p[0]];
1503                 p[1] = cb_tab[1][p[1]];
1504                 p[2] = cb_tab[2][p[2]];
1505                 
1506                 p += 4;
1507         }
1508 }
1509
1510 static void color_balance_byte_float(Sequence * seq, ImBuf* ibuf, float mul)
1511 {
1512         float cb_tab[4][256];
1513         int c,i;
1514         unsigned char * p = (unsigned char*) ibuf->rect;
1515         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1516         float * o;
1517         StripColorBalance cb;
1518
1519         imb_addrectfloatImBuf(ibuf);
1520
1521         o = ibuf->rect_float;
1522
1523         cb = calc_cb(seq->strip->color_balance);
1524
1525         for (c = 0; c < 3; c++) {
1526                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1527         }
1528
1529         for (i = 0; i < 256; i++) {
1530                 cb_tab[3][i] = ((float)i)*(1.0f/255.0f);
1531         }
1532
1533         while (p < e) {
1534                 o[0] = cb_tab[0][p[0]];
1535                 o[1] = cb_tab[1][p[1]];
1536                 o[2] = cb_tab[2][p[2]];
1537                 o[3] = cb_tab[3][p[3]];
1538
1539                 p += 4; o += 4;
1540         }
1541 }
1542
1543 static void color_balance_float_float(Sequence * seq, ImBuf* ibuf, float mul)
1544 {
1545         float * p = ibuf->rect_float;
1546         float * e = ibuf->rect_float + ibuf->x * 4* ibuf->y;
1547         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1548
1549         while (p < e) {
1550                 int c;
1551                 for (c = 0; c < 3; c++) {
1552                         p[c]= color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1553                 }
1554                 p += 4;
1555         }
1556 }
1557
1558 static void color_balance(Sequence * seq, ImBuf* ibuf, float mul)
1559 {
1560         if (ibuf->rect_float) {
1561                 color_balance_float_float(seq, ibuf, mul);
1562         } else if(seq->flag & SEQ_MAKE_FLOAT) {
1563                 color_balance_byte_float(seq, ibuf, mul);
1564         } else {
1565                 color_balance_byte_byte(seq, ibuf, mul);
1566         }
1567 }
1568
1569 /*
1570   input preprocessing for SEQ_IMAGE, SEQ_MOVIE and SEQ_SCENE
1571
1572   Do all the things you can't really do afterwards using sequence effects
1573   (read: before rescaling to render resolution has been done)
1574
1575   Order is important!
1576
1577   - Deinterlace
1578   - Crop and transform in image source coordinate space
1579   - Flip X + Flip Y (could be done afterwards, backward compatibility)
1580   - Promote image to float data (affects pipeline operations afterwards)
1581   - Color balance (is most efficient in the byte -> float 
1582         (future: half -> float should also work fine!)
1583         case, if done on load, since we can use lookup tables)
1584   - Premultiply
1585
1586 */
1587
1588 int input_have_to_preprocess(
1589         SeqRenderData UNUSED(context), Sequence * seq, float UNUSED(cfra))
1590 {
1591         float mul;
1592
1593         if (seq->flag & (SEQ_FILTERY|SEQ_USE_CROP|SEQ_USE_TRANSFORM|SEQ_FLIPX|
1594                          SEQ_FLIPY|SEQ_USE_COLOR_BALANCE|SEQ_MAKE_PREMUL)) {
1595                 return TRUE;
1596         }
1597
1598         mul = seq->mul;
1599
1600         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1601                 mul *= seq->blend_opacity / 100.0f;
1602         }
1603
1604         if (mul != 1.0f) {
1605                 return TRUE;
1606         }
1607
1608         if (seq->sat != 1.0f) {
1609                 return TRUE;
1610         }
1611                 
1612         return FALSE;
1613 }
1614
1615 static ImBuf * input_preprocess(
1616         SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf * ibuf)
1617 {
1618         float mul;
1619
1620         ibuf = IMB_makeSingleUser(ibuf);
1621
1622         if((seq->flag & SEQ_FILTERY) && seq->type != SEQ_MOVIE) {
1623                 IMB_filtery(ibuf);
1624         }
1625
1626         if(seq->flag & (SEQ_USE_CROP|SEQ_USE_TRANSFORM)) {
1627                 StripCrop c= {0};
1628                 StripTransform t= {0};
1629                 int sx,sy,dx,dy;
1630
1631                 if(seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1632                         c = *seq->strip->crop;
1633                 }
1634                 if(seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1635                         t = *seq->strip->transform;
1636                 }
1637
1638                 sx = ibuf->x - c.left - c.right;
1639                 sy = ibuf->y - c.top - c.bottom;
1640                 dx = sx;
1641                 dy = sy;
1642
1643                 if (seq->flag & SEQ_USE_TRANSFORM) {
1644                         dx = context.scene->r.xsch;
1645                         dy = context.scene->r.ysch;
1646                 }
1647
1648                 if (c.top + c.bottom >= ibuf->y || c.left + c.right >= ibuf->x ||
1649                                 t.xofs >= dx || t.yofs >= dy) {
1650                         make_black_ibuf(ibuf);
1651                 } else {
1652                         ImBuf * i = IMB_allocImBuf(dx, dy,32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1653
1654                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1655                         
1656                         IMB_freeImBuf(ibuf);
1657
1658                         ibuf = i;
1659                 }
1660         } 
1661
1662         if(seq->flag & SEQ_FLIPX) {
1663                 IMB_flipx(ibuf);
1664         }
1665         
1666         if(seq->flag & SEQ_FLIPY) {
1667                 IMB_flipy(ibuf);
1668         }
1669
1670         if(seq->sat != 1.0f) {
1671                 /* inline for now, could become an imbuf function */
1672                 int i;
1673                 unsigned char *rct= (unsigned char *)ibuf->rect;
1674                 float *rctf= ibuf->rect_float;
1675                 const float sat= seq->sat;
1676                 float hsv[3];
1677
1678                 if(rct) {
1679                         float rgb[3];
1680                         for (i = ibuf->x * ibuf->y; i > 0; i--, rct+=4) {
1681                                 rgb_byte_to_float(rct, rgb);
1682                                 rgb_to_hsv(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
1683                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rgb, rgb+1, rgb+2);
1684                                 rgb_float_to_byte(rgb, rct);
1685                         }
1686                 }
1687
1688                 if(rctf) {
1689                         for (i = ibuf->x * ibuf->y; i > 0; i--, rctf+=4) {
1690                                 rgb_to_hsv(rctf[0], rctf[1], rctf[2], hsv, hsv+1, hsv+2);
1691                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rctf, rctf+1, rctf+2);
1692                         }
1693                 }
1694         }
1695
1696         mul = seq->mul;
1697
1698         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1699                 mul *= seq->blend_opacity / 100.0f;
1700         }
1701
1702         if(seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1703                 color_balance(seq, ibuf, mul);
1704                 mul = 1.0;
1705         }
1706
1707         if(seq->flag & SEQ_MAKE_FLOAT) {
1708                 if (!ibuf->rect_float)
1709                         IMB_float_from_rect_simple(ibuf);
1710
1711                 if (ibuf->rect) {
1712                         imb_freerectImBuf(ibuf);
1713                 }
1714         }
1715
1716         if(mul != 1.0f) {
1717                 multibuf(ibuf, mul);
1718         }
1719
1720         if(seq->flag & SEQ_MAKE_PREMUL) {
1721                 if(ibuf->depth == 32 && ibuf->zbuf == NULL) {
1722                         IMB_premultiply_alpha(ibuf);
1723                 }
1724         }
1725
1726
1727         if(ibuf->x != context.rectx || ibuf->y != context.recty ) {
1728                 if(context.scene->r.mode & R_OSA) {
1729                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1730                 } else {
1731                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1732                 }
1733         }
1734         return ibuf;
1735 }
1736
1737 static ImBuf * copy_from_ibuf_still(SeqRenderData context, Sequence * seq, 
1738                                     float nr)
1739 {
1740         ImBuf * rval = NULL;
1741         ImBuf * ibuf = NULL;
1742
1743         if (nr == 0) {
1744                 ibuf = seq_stripelem_cache_get(
1745                         context, seq, seq->start, 
1746                         SEQ_STRIPELEM_IBUF_STARTSTILL);
1747         } else if (nr == seq->len - 1) {
1748                 ibuf = seq_stripelem_cache_get(
1749                         context, seq, seq->start, 
1750                         SEQ_STRIPELEM_IBUF_ENDSTILL);
1751         }
1752
1753         if (ibuf) {
1754                 rval = IMB_dupImBuf(ibuf);
1755                 IMB_freeImBuf(ibuf);
1756         }
1757
1758         return rval;
1759 }
1760
1761 static void copy_to_ibuf_still(SeqRenderData context, Sequence * seq, float nr,
1762                                ImBuf * ibuf)
1763 {
1764         if (nr == 0 || nr == seq->len - 1) {
1765                 /* we have to store a copy, since the passed ibuf
1766                    could be preprocessed afterwards (thereby silently
1767                    changing the cached image... */
1768                 ibuf = IMB_dupImBuf(ibuf);
1769
1770                 if (nr == 0) {
1771                         seq_stripelem_cache_put(
1772                                 context, seq, seq->start, 
1773                                 SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
1774                 } 
1775
1776                 if (nr == seq->len - 1) {
1777                         seq_stripelem_cache_put(
1778                                 context, seq, seq->start, 
1779                                 SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
1780                 }
1781
1782                 IMB_freeImBuf(ibuf);
1783         }
1784 }
1785
1786 /* **********************************************************************
1787    strip rendering functions
1788    ********************************************************************** */
1789
1790 static ImBuf* seq_render_strip_stack( 
1791         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown);
1792
1793 static ImBuf * seq_render_strip(
1794         SeqRenderData context, Sequence * seq, float cfra);
1795
1796
1797 static ImBuf* seq_render_effect_strip_impl(
1798         SeqRenderData context, Sequence *seq, float cfra)
1799 {
1800         float fac, facf;
1801         int early_out;
1802         int i;
1803         struct SeqEffectHandle sh = get_sequence_effect(seq);
1804         FCurve *fcu= NULL;
1805         ImBuf * ibuf[3];
1806         Sequence *input[3];
1807         ImBuf * out = NULL;
1808
1809         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1810
1811         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1812
1813         if (!sh.execute) { /* effect not supported in this version... */
1814                 out = IMB_allocImBuf((short)context.rectx, 
1815                                      (short)context.recty, 32, IB_rect);
1816                 return out;
1817         }
1818
1819         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1820                 sh.get_default_fac(seq, cfra, &fac, &facf);
1821                 
1822                 if ((context.scene->r.mode & R_FIELDS)==0)
1823                         facf= fac;
1824         }
1825         else {
1826                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0);
1827                 if (fcu) {
1828                         fac = facf = evaluate_fcurve(fcu, cfra);
1829                         if( context.scene->r.mode & R_FIELDS ) {
1830                                 facf = evaluate_fcurve(fcu, cfra + 0.5f);
1831                         }
1832                 } else {
1833                         fac = facf = seq->effect_fader;
1834                 }
1835         }
1836
1837         early_out = sh.early_out(seq, fac, facf);
1838
1839         switch (early_out) {
1840         case EARLY_NO_INPUT:
1841                 out = sh.execute(context, seq, cfra, fac, facf, 
1842                                  NULL, NULL, NULL);
1843                 break;
1844         case EARLY_DO_EFFECT:
1845                 for(i=0; i<3; i++) {
1846                         if(input[i])
1847                                 ibuf[i] = seq_render_strip(
1848                                         context, input[i], cfra);
1849                 }
1850
1851                 if (ibuf[0] && ibuf[1]) {
1852                         out = sh.execute(context, seq, cfra, fac, facf,  
1853                                          ibuf[0], ibuf[1], ibuf[2]);
1854                 }
1855                 break;
1856         case EARLY_USE_INPUT_1:
1857                 if (input[0]) {
1858                         ibuf[0] = seq_render_strip(context, input[0], cfra);
1859                 }
1860                 if (ibuf[0]) {
1861                         if (input_have_to_preprocess(context, seq, cfra)) {
1862                                 out = IMB_dupImBuf(ibuf[0]);
1863                         } else {
1864                                 out = ibuf[0];
1865                                 IMB_refImBuf(out);
1866                         }
1867                 }
1868                 break;
1869         case EARLY_USE_INPUT_2:
1870                 if (input[1]) {
1871                         ibuf[1] = seq_render_strip(context, input[1], cfra);
1872                 }
1873                 if (ibuf[1]) {
1874                         if (input_have_to_preprocess(context, seq, cfra)) {
1875                                 out = IMB_dupImBuf(ibuf[1]);
1876                         } else {
1877                                 out = ibuf[1];
1878                                 IMB_refImBuf(out);
1879                         }
1880                 }
1881                 break;
1882         }
1883
1884         for (i = 0; i < 3; i++) {
1885                 IMB_freeImBuf(ibuf[i]);
1886         }
1887
1888         if (out == NULL) {
1889                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
1890         }
1891
1892         return out;
1893 }
1894
1895
1896 static ImBuf * seq_render_scene_strip_impl(
1897         SeqRenderData context, Sequence * seq, float nr)
1898 {
1899         ImBuf * ibuf = NULL;
1900         float frame= seq->sfra + nr + seq->anim_startofs;
1901         float oldcfra;
1902         Object *camera;
1903         ListBase oldmarkers;
1904         
1905         /* Old info:
1906            Hack! This function can be called from do_render_seq(), in that case
1907            the seq->scene can already have a Render initialized with same name,
1908            so we have to use a default name. (compositor uses scene name to
1909            find render).
1910            However, when called from within the UI (image preview in sequencer)
1911            we do want to use scene Render, that way the render result is defined
1912            for display in render/imagewindow
1913            
1914            Hmm, don't see, why we can't do that all the time,
1915            and since G.rendering is uhm, gone... (Peter)
1916         */
1917
1918         /* New info:
1919            Using the same name for the renders works just fine as the do_render_seq()
1920            render is not used while the scene strips are rendered.
1921            
1922            However rendering from UI (through sequencer_preview_area_draw) can crash in
1923            very many cases since other renders (material preview, an actual render etc.)
1924            can be started while this sequence preview render is running. The only proper
1925            solution is to make the sequencer preview render a proper job, which can be
1926            stopped when needed. This would also give a nice progress bar for the preview
1927            space so that users know there's something happening.
1928
1929            As a result the active scene now only uses OpenGL rendering for the sequencer
1930            preview. This is far from nice, but is the only way to prevent crashes at this
1931            time. 
1932
1933            -jahka
1934         */
1935
1936         int rendering = G.rendering;
1937         int doseq;
1938         int doseq_gl= G.rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
1939         int have_seq= FALSE;
1940         Scene *scene;
1941
1942         /* dont refer to seq->scene above this point!, it can be NULL */
1943         if(seq->scene == NULL) {
1944                 return NULL;
1945         }
1946
1947         scene= seq->scene;
1948
1949         have_seq= (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first;
1950
1951         oldcfra= scene->r.cfra; 
1952         scene->r.cfra= frame;
1953
1954         if(seq->scene_camera)   
1955                 camera= seq->scene_camera;
1956         else {  
1957                 scene_camera_switch_update(scene);
1958                 camera= scene->camera;
1959         }
1960
1961         if(have_seq==FALSE && camera==NULL) {
1962                 scene->r.cfra= oldcfra;
1963                 return NULL;
1964         }
1965
1966         /* prevent eternal loop */
1967         doseq= context.scene->r.scemode & R_DOSEQ;
1968         context.scene->r.scemode &= ~R_DOSEQ;
1969         
1970 #ifdef DURIAN_CAMERA_SWITCH
1971         /* stooping to new low's in hackyness :( */
1972         oldmarkers= scene->markers;
1973         scene->markers.first= scene->markers.last= NULL;
1974 #endif
1975         
1976         if(sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq==0) && camera) {
1977                 char err_out[256]= "unknown";
1978                 /* for old scened this can be uninitialized, should probably be added to do_versions at some point if the functionality stays */
1979                 if(context.scene->r.seq_prev_type==0)
1980                         context.scene->r.seq_prev_type = 3 /* ==OB_SOLID */; 
1981
1982                 /* opengl offscreen render */
1983                 scene_update_for_newframe(context.bmain, scene, scene->lay);
1984                 ibuf= sequencer_view3d_cb(scene, camera, context.rectx, context.recty, IB_rect, context.scene->r.seq_prev_type, err_out);
1985                 if(ibuf == NULL) {
1986                         fprintf(stderr, "seq_render_scene_strip_impl failed to get opengl buffer: %s\n", err_out);
1987                 }
1988         }
1989         else {
1990                 Render *re = RE_GetRender(scene->id.name);
1991                 RenderResult rres;
1992
1993                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
1994                 if(rendering || context.scene != scene) {
1995                         if(re==NULL)
1996                                 re= RE_NewRender(scene->id.name);
1997                         
1998                         RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE);
1999
2000                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
2001                         G.rendering = rendering;
2002                 }
2003                 
2004                 RE_AcquireResultImage(re, &rres);
2005                 
2006                 if(rres.rectf) {
2007                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
2008                         memcpy(ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
2009                         if(rres.rectz) {
2010                                 addzbuffloatImBuf(ibuf);
2011                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
2012                         }
2013
2014                         /* float buffers in the sequencer are not linear */
2015                         ibuf->profile= IB_PROFILE_LINEAR_RGB;
2016                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
2017                 }
2018                 else if (rres.rect32) {
2019                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
2020                         memcpy(ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
2021                 }
2022                 
2023                 RE_ReleaseResultImage(re);
2024                 
2025                 // BIF_end_render_callbacks();
2026         }
2027         
2028         /* restore */
2029         context.scene->r.scemode |= doseq;
2030         
2031         scene->r.cfra = oldcfra;
2032
2033         if(frame != oldcfra)
2034                 scene_update_for_newframe(context.bmain, scene, scene->lay);
2035         
2036 #ifdef DURIAN_CAMERA_SWITCH
2037         /* stooping to new low's in hackyness :( */
2038         scene->markers= oldmarkers;
2039 #endif
2040
2041         return ibuf;
2042 }
2043
2044 static ImBuf * seq_render_strip(SeqRenderData context, Sequence * seq, float cfra)
2045 {
2046         ImBuf * ibuf = NULL;
2047         char name[FILE_MAXDIR+FILE_MAXFILE];
2048         int use_preprocess = input_have_to_preprocess(context, seq, cfra);
2049         float nr = give_stripelem_index(seq, cfra);
2050         /* all effects are handled similarly with the exception of speed effect */
2051         int type = (seq->type & SEQ_EFFECT && seq->type != SEQ_SPEED) ? SEQ_EFFECT : seq->type;
2052
2053         ibuf = seq_stripelem_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF);
2054
2055         /* currently, we cache preprocessed images in SEQ_STRIPELEM_IBUF,
2056            but not(!) on SEQ_STRIPELEM_IBUF_ENDSTILL and ..._STARTSTILL */
2057         if (ibuf)
2058                 use_preprocess = FALSE;
2059
2060         if (ibuf == NULL)
2061                 ibuf = copy_from_ibuf_still(context, seq, nr);
2062         
2063         if (ibuf == NULL)
2064                 ibuf = seq_proxy_fetch(context, seq, cfra);
2065
2066         if(ibuf == NULL) switch(type) {
2067                 case SEQ_META:
2068                 {
2069                         ImBuf * meta_ibuf = NULL;
2070
2071                         if(seq->seqbase.first)
2072                                 meta_ibuf = seq_render_strip_stack(
2073                                         context, &seq->seqbase,
2074                                         seq->start + nr, 0);
2075
2076                         if(meta_ibuf) {
2077                                 ibuf = meta_ibuf;
2078                                 if(ibuf && use_preprocess) {
2079                                         struct ImBuf * i = IMB_dupImBuf(ibuf);
2080
2081                                         IMB_freeImBuf(ibuf);
2082
2083                                         ibuf = i;
2084                                 }
2085                         }
2086                         break;
2087                 }
2088                 case SEQ_SPEED:
2089                 {
2090                         ImBuf * child_ibuf = NULL;
2091
2092                         float f_cfra;
2093                         SpeedControlVars * s = (SpeedControlVars *)seq->effectdata;
2094
2095                         sequence_effect_speed_rebuild_map(context.scene,seq, 0);
2096
2097                         /* weeek! */
2098                         f_cfra = seq->start + s->frameMap[(int) nr];
2099
2100                         child_ibuf = seq_render_strip(context,seq->seq1,f_cfra);
2101
2102                         if (child_ibuf) {
2103                                 ibuf = child_ibuf;
2104                                 if(ibuf && use_preprocess) {
2105                                         struct ImBuf * i = IMB_dupImBuf(ibuf);
2106
2107                                         IMB_freeImBuf(ibuf);
2108
2109                                         ibuf = i;
2110                                 }
2111                         }
2112                         break;
2113                 }
2114                 case SEQ_EFFECT:
2115                 {
2116                         ibuf = seq_render_effect_strip_impl(
2117                                 context, seq, seq->start + nr);
2118                         break;
2119                 }
2120                 case SEQ_IMAGE:
2121                 {
2122                         StripElem * s_elem = give_stripelem(seq, cfra);
2123
2124                         if (s_elem) {
2125                                 BLI_join_dirfile(name, sizeof(name), seq->strip->dir, s_elem->name);
2126                                 BLI_path_abs(name, G.main->name);
2127                         }
2128
2129                         if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect))) {
2130                                 /* we don't need both (speed reasons)! */
2131                                 if (ibuf->rect_float && ibuf->rect)
2132                                         imb_freerectImBuf(ibuf);
2133
2134                                 /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2135                                 if(ibuf->profile == IB_PROFILE_LINEAR_RGB)
2136                                         IMB_convert_profile(ibuf, IB_PROFILE_NONE);
2137
2138                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2139
2140                                 s_elem->orig_width  = ibuf->x;
2141                                 s_elem->orig_height = ibuf->y;
2142                         }
2143                         break;
2144                 }
2145                 case SEQ_MOVIE:
2146                 {
2147                         seq_open_anim_file(seq);
2148
2149                         if(seq->anim) {
2150                                 IMB_anim_set_preseek(seq->anim,
2151                                                      seq->anim_preseek);
2152
2153                                 ibuf = IMB_anim_absolute(
2154                                         seq->anim, nr + seq->anim_startofs, 
2155                                         seq->strip->proxy ? 
2156                                         seq->strip->proxy->tc
2157                                         : IMB_TC_RECORD_RUN, 
2158                                         seq_rendersize_to_proxysize(
2159                                                 context.preview_render_size));
2160
2161                                 /* we don't need both (speed reasons)! */
2162                                 if (ibuf && ibuf->rect_float && ibuf->rect)
2163                                         imb_freerectImBuf(ibuf);
2164                                 if (ibuf) {
2165                                         seq->strip->stripdata->orig_width = ibuf->x;
2166                                         seq->strip->stripdata->orig_height = ibuf->y;
2167                                 }
2168                         }
2169                         copy_to_ibuf_still(context, seq, nr, ibuf);
2170                         break;
2171                 }
2172                 case SEQ_SCENE:
2173                 {       // scene can be NULL after deletions
2174                         ibuf = seq_render_scene_strip_impl(context, seq, nr);
2175
2176                         /* Scene strips update all animation, so we need to restore original state.*/
2177                         BKE_animsys_evaluate_all_animation(context.bmain, cfra);
2178
2179                         copy_to_ibuf_still(context, seq, nr, ibuf);
2180                         break;
2181                 }
2182         }
2183
2184         if (ibuf == NULL)
2185                 ibuf = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
2186
2187         if (ibuf->x != context.rectx || ibuf->y != context.recty)
2188                 use_preprocess = TRUE;
2189
2190         if (use_preprocess)
2191                 ibuf = input_preprocess(context, seq, cfra, ibuf);
2192
2193         seq_stripelem_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf);
2194
2195         return ibuf;
2196 }
2197
2198 /* **********************************************************************
2199    strip stack rendering functions
2200    ********************************************************************** */
2201
2202 static int seq_must_swap_input_in_blend_mode(Sequence * seq)
2203 {
2204         int swap_input = FALSE;
2205
2206         /* bad hack, to fix crazy input ordering of 
2207            those two effects */
2208
2209         if (ELEM3(seq->blend_mode, SEQ_ALPHAOVER, SEQ_ALPHAUNDER, SEQ_OVERDROP)) {
2210                 swap_input = TRUE;
2211         }
2212         
2213         return swap_input;
2214 }
2215
2216 static int seq_get_early_out_for_blend_mode(Sequence * seq)
2217 {
2218         struct SeqEffectHandle sh = get_sequence_blend(seq);
2219         float facf = seq->blend_opacity / 100.0f;
2220         int early_out = sh.early_out(seq, facf, facf);
2221         
2222         if (ELEM(early_out, EARLY_DO_EFFECT, EARLY_NO_INPUT)) {
2223                 return early_out;
2224         }
2225
2226         if (seq_must_swap_input_in_blend_mode(seq)) {
2227                 if (early_out == EARLY_USE_INPUT_2) {
2228                         return EARLY_USE_INPUT_1;
2229                 } else if (early_out == EARLY_USE_INPUT_1) {
2230                         return EARLY_USE_INPUT_2;
2231                 }
2232         }
2233         return early_out;
2234 }
2235
2236 static ImBuf* seq_render_strip_stack(
2237         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown)
2238 {
2239         Sequence* seq_arr[MAXSEQ+1];
2240         int count;
2241         int i;
2242         ImBuf* out = NULL;
2243
2244         count = get_shown_sequences(seqbasep, cfra, chanshown, (Sequence **)&seq_arr);
2245
2246         if (count == 0) {
2247                 return NULL;
2248         }
2249
2250 #if 0 /* commentind since this breaks keyframing, since it resets the value on draw */
2251         if(scene->r.cfra != cfra) {
2252                 // XXX for prefetch and overlay offset!..., very bad!!!
2253                 AnimData *adt= BKE_animdata_from_id(&scene->id);
2254                 BKE_animsys_evaluate_animdata(&scene->id, adt, cfra, ADT_RECALC_ANIM);
2255         }
2256 #endif
2257
2258         out = seq_stripelem_cache_get(context, seq_arr[count - 1], 
2259                                       cfra, SEQ_STRIPELEM_IBUF_COMP);
2260
2261         if (out) {
2262                 return out;
2263         }
2264         
2265         if(count == 1) {
2266                 out = seq_render_strip(context, seq_arr[0], cfra);
2267                 seq_stripelem_cache_put(context, seq_arr[0], cfra, 
2268                                         SEQ_STRIPELEM_IBUF_COMP, out);
2269
2270                 return out;
2271         }
2272
2273
2274         for (i = count - 1; i >= 0; i--) {
2275                 int early_out;
2276                 Sequence *seq = seq_arr[i];
2277
2278                 out = seq_stripelem_cache_get(
2279                         context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP);
2280
2281                 if (out) {
2282                         break;
2283                 }
2284                 if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2285                         out = seq_render_strip(context, seq, cfra);
2286                         break;
2287                 }
2288
2289                 early_out = seq_get_early_out_for_blend_mode(seq);
2290
2291                 switch (early_out) {
2292                 case EARLY_NO_INPUT:
2293                 case EARLY_USE_INPUT_2:
2294                         out = seq_render_strip(context, seq, cfra);
2295                         break;
2296                 case EARLY_USE_INPUT_1:
2297                         if (i == 0) {
2298                                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
2299                         }
2300                         break;
2301                 case EARLY_DO_EFFECT:
2302                         if (i == 0) {
2303                                 out = seq_render_strip(context, seq, cfra);
2304                         }
2305
2306                         break;
2307                 }
2308                 if (out) {
2309                         break;
2310                 }
2311         }
2312
2313         seq_stripelem_cache_put(context, seq_arr[i], cfra, 
2314                                 SEQ_STRIPELEM_IBUF_COMP, out);
2315
2316
2317         i++;
2318
2319         for (; i < count; i++) {
2320                 Sequence * seq = seq_arr[i];
2321
2322                 if (seq_get_early_out_for_blend_mode(seq) == EARLY_DO_EFFECT) {
2323                         struct SeqEffectHandle sh = get_sequence_blend(seq);
2324                         ImBuf * ibuf1 = out;
2325                         ImBuf * ibuf2 = seq_render_strip(context, seq, cfra);
2326
2327                         float facf = seq->blend_opacity / 100.0f;
2328                         int swap_input = seq_must_swap_input_in_blend_mode(seq);
2329
2330                         if (swap_input) {
2331                                 out = sh.execute(context, seq, cfra, 
2332                                                  facf, facf, 
2333                                                  ibuf2, ibuf1, NULL);
2334                         } else {
2335                                 out = sh.execute(context, seq, cfra, 
2336                                                  facf, facf, 
2337                                                  ibuf1, ibuf2, NULL);
2338                         }
2339                 
2340                         IMB_freeImBuf(ibuf1);
2341                         IMB_freeImBuf(ibuf2);
2342                 }
2343
2344                 seq_stripelem_cache_put(context, seq_arr[i], cfra,
2345                                         SEQ_STRIPELEM_IBUF_COMP, out);
2346         }
2347
2348         return out;
2349 }
2350
2351 /*
2352  * returned ImBuf is refed!
2353  * you have to free after usage!
2354  */
2355
2356 ImBuf *give_ibuf_seq(SeqRenderData context, float cfra, int chanshown)
2357 {
2358         Editing *ed= seq_give_editing(context.scene, FALSE);
2359         int count;
2360         ListBase *seqbasep;
2361         
2362         if(ed==NULL) return NULL;
2363
2364         count = BLI_countlist(&ed->metastack);
2365         if((chanshown < 0) && (count > 0)) {
2366                 count = MAX2(count + chanshown, 0);
2367                 seqbasep= ((MetaStack*)BLI_findlink(&ed->metastack, count))->oldbasep;
2368         } else {
2369                 seqbasep= ed->seqbasep;
2370         }
2371
2372         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2373 }
2374
2375 ImBuf *give_ibuf_seqbase(SeqRenderData context, float cfra, int chanshown, ListBase *seqbasep)
2376 {
2377         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2378 }
2379
2380
2381 ImBuf *give_ibuf_seq_direct(SeqRenderData context, float cfra, Sequence *seq)
2382 {
2383         return seq_render_strip(context, seq, cfra);
2384 }
2385
2386 #if 0
2387 /* check used when we need to change seq->blend_mode but not to effect or audio strips */
2388 static int seq_can_blend(Sequence *seq)
2389 {
2390         if (ELEM4(seq->type, SEQ_IMAGE, SEQ_META, SEQ_SCENE, SEQ_MOVIE)) {
2391                 return 1;
2392         } else {
2393                 return 0;
2394         }
2395 }
2396 #endif
2397
2398 /* *********************** threading api ******************* */
2399
2400 static ListBase running_threads;
2401 static ListBase prefetch_wait;
2402 static ListBase prefetch_done;
2403
2404 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
2405 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
2406 static pthread_cond_t  wakeup_cond         = PTHREAD_COND_INITIALIZER;
2407
2408 //static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
2409 //static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
2410
2411 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
2412 static pthread_cond_t  frame_done_cond     = PTHREAD_COND_INITIALIZER;
2413
2414 static volatile int seq_thread_shutdown = TRUE; 
2415 static volatile int seq_last_given_monoton_cfra = 0;
2416 static int monoton_cfra = 0;
2417
2418 typedef struct PrefetchThread {
2419         struct PrefetchThread *next, *prev;
2420         
2421         Scene *scene;
2422         struct PrefetchQueueElem *current;
2423         pthread_t pthread;
2424         int running;
2425         
2426 } PrefetchThread;
2427
2428 typedef struct PrefetchQueueElem {
2429         struct PrefetchQueueElem *next, *prev;
2430         
2431         int rectx;
2432         int recty;
2433         float cfra;
2434         int chanshown;
2435         int preview_render_size;
2436
2437         int monoton_cfra;
2438
2439         struct ImBuf * ibuf;
2440 } PrefetchQueueElem;
2441
2442 #if 0
2443 static void *seq_prefetch_thread(void * This_)
2444 {
2445         PrefetchThread * This = This_;
2446
2447         while (!seq_thread_shutdown) {
2448                 PrefetchQueueElem *e;
2449                 int s_last;
2450
2451                 pthread_mutex_lock(&queue_lock);
2452                 e = prefetch_wait.first;
2453                 if (e) {
2454                         BLI_remlink(&prefetch_wait, e);
2455                 }
2456                 s_last = seq_last_given_monoton_cfra;
2457
2458                 This->current = e;
2459
2460                 pthread_mutex_unlock(&queue_lock);
2461
2462                 if (!e) {
2463                         pthread_mutex_lock(&prefetch_ready_lock);
2464
2465                         This->running = FALSE;
2466
2467                         pthread_cond_signal(&prefetch_ready_cond);
2468                         pthread_mutex_unlock(&prefetch_ready_lock);
2469
2470                         pthread_mutex_lock(&wakeup_lock);
2471                         if (!seq_thread_shutdown) {
2472                                 pthread_cond_wait(&wakeup_cond, &wakeup_lock);
2473                         }
2474                         pthread_mutex_unlock(&wakeup_lock);
2475                         continue;
2476                 }
2477
2478                 This->running = TRUE;
2479                 
2480                 if (e->cfra >= s_last) { 
2481                         e->ibuf = give_ibuf_seq_impl(This->scene, 
2482                                 e->rectx, e->recty, e->cfra, e->chanshown,
2483                                 e->preview_render_size);
2484                 }
2485
2486                 pthread_mutex_lock(&queue_lock);
2487
2488                 BLI_addtail(&prefetch_done, e);
2489
2490                 for (e = prefetch_wait.first; e; e = e->next) {
2491                         if (s_last > e->monoton_cfra) {
2492                                 BLI_remlink(&prefetch_wait, e);
2493                                 MEM_freeN(e);
2494                         }
2495                 }
2496
2497                 for (e = prefetch_done.first; e; e = e->next) {
2498                         if (s_last > e->monoton_cfra) {
2499                                 if (e->ibuf) {
2500                                         IMB_cache_limiter_unref(e->ibuf);
2501                                 }
2502                                 BLI_remlink(&prefetch_done, e);
2503                                 MEM_freeN(e);
2504                         }
2505                 }
2506
2507                 pthread_mutex_unlock(&queue_lock);
2508
2509                 pthread_mutex_lock(&frame_done_lock);
2510                 pthread_cond_signal(&frame_done_cond);
2511                 pthread_mutex_unlock(&frame_done_lock);
2512         }
2513         return 0;
2514 }
2515
2516 static void seq_start_threads(Scene *scene)
2517 {
2518         int i;
2519
2520         running_threads.first = running_threads.last = NULL;
2521         prefetch_wait.first = prefetch_wait.last = NULL;
2522         prefetch_done.first = prefetch_done.last = NULL;
2523
2524         seq_thread_shutdown = FALSE;
2525         seq_last_given_monoton_cfra = monoton_cfra = 0;
2526
2527         /* since global structures are modified during the processing
2528            of one frame, only one render thread is currently possible... 
2529
2530            (but we code, in the hope, that we can remove this restriction
2531            soon...)
2532         */
2533
2534         fprintf(stderr, "SEQ-THREAD: seq_start_threads\n");
2535
2536         for (i = 0; i < 1; i++) {
2537                 PrefetchThread *t = MEM_callocN(sizeof(PrefetchThread), "prefetch_thread");
2538                 t->scene= scene;
2539                 t->running = TRUE;
2540                 BLI_addtail(&running_threads, t);
2541
2542                 pthread_create(&t->pthread, NULL, seq_prefetch_thread, t);
2543         }
2544
2545         /* init malloc mutex */
2546         BLI_init_threads(0, 0, 0);
2547 }
2548
2549 static void seq_stop_threads()
2550 {
2551         PrefetchThread *tslot;
2552         PrefetchQueueElem *e;
2553
2554         fprintf(stderr, "SEQ-THREAD: seq_stop_threads()\n");
2555
2556         if (seq_thread_shutdown) {
2557                 fprintf(stderr, "SEQ-THREAD: ... already stopped\n");
2558                 return;
2559         }
2560         
2561         pthread_mutex_lock(&wakeup_lock);
2562
2563         seq_thread_shutdown = TRUE;
2564
2565                 pthread_cond_broadcast(&wakeup_cond);
2566                 pthread_mutex_unlock(&wakeup_lock);
2567
2568         for(tslot = running_threads.first; tslot; tslot= tslot->next) {
2569                 pthread_join(tslot->pthread, NULL);
2570         }
2571
2572
2573         for (e = prefetch_wait.first; e; e = e->next) {
2574                 BLI_remlink(&prefetch_wait, e);
2575                 MEM_freeN(e);
2576         }
2577
2578         for (e = prefetch_done.first; e; e = e->next) {
2579                 if (e->ibuf) {
2580                         IMB_cache_limiter_unref(e->ibuf);
2581                 }
2582                 BLI_remlink(&prefetch_done, e);
2583                 MEM_freeN(e);
2584         }
2585
2586         BLI_freelistN(&running_threads);
2587
2588         /* deinit malloc mutex */
2589         BLI_end_threads(0);
2590 }
2591 #endif
2592
2593 void give_ibuf_prefetch_request(SeqRenderData context, float cfra, int chanshown)
2594 {
2595         PrefetchQueueElem *e;
2596         if (seq_thread_shutdown) {
2597                 return;
2598         }
2599
2600         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
2601         e->rectx = context.rectx;
2602         e->recty = context.recty;
2603         e->cfra = cfra;
2604         e->chanshown = chanshown;
2605         e->preview_render_size = context.preview_render_size;
2606         e->monoton_cfra = monoton_cfra++;
2607
2608         pthread_mutex_lock(&queue_lock);
2609         BLI_addtail(&prefetch_wait, e);
2610         pthread_mutex_unlock(&queue_lock);
2611         
2612         pthread_mutex_lock(&wakeup_lock);
2613         pthread_cond_signal(&wakeup_cond);
2614         pthread_mutex_unlock(&wakeup_lock);
2615 }
2616
2617 #if 0
2618 static void seq_wait_for_prefetch_ready()
2619 {
2620         PrefetchThread *tslot;
2621
2622         if (seq_thread_shutdown) {
2623                 return;
2624         }
2625
2626         fprintf(stderr, "SEQ-THREAD: rendering prefetch frames...\n");
2627
2628         pthread_mutex_lock(&prefetch_ready_lock);
2629
2630         for(;;) {
2631                 for(tslot = running_threads.first; tslot; tslot= tslot->next) {
2632                         if (tslot->running) {
2633                                 break;
2634                         }
2635                 }
2636                 if (!tslot) {
2637                         break;
2638                 }
2639                 pthread_cond_wait(&prefetch_ready_cond, &prefetch_ready_lock);
2640         }
2641
2642         pthread_mutex_unlock(&prefetch_ready_lock);
2643
2644         fprintf(stderr, "SEQ-THREAD: prefetch done\n");
2645 }
2646 #endif
2647
2648 ImBuf *give_ibuf_seq_threaded(SeqRenderData context, float cfra, int chanshown)
2649 {
2650         PrefetchQueueElem *e = NULL;
2651         int found_something = FALSE;
2652
2653         if (seq_thread_shutdown) {
2654                 return give_ibuf_seq(context, cfra, chanshown);
2655         }
2656
2657         while (!e) {
2658                 int success = FALSE;
2659                 pthread_mutex_lock(&queue_lock);
2660
2661                 for (e = prefetch_done.first; e; e = e->next) {
2662                         if (cfra == e->cfra &&
2663                                 chanshown == e->chanshown &&
2664                                 context.rectx == e->rectx && 
2665                                 context.recty == e->recty &&
2666                                 context.preview_render_size == e->preview_render_size) {
2667                                 success = TRUE;
2668                                 found_something = TRUE;
2669                                 break;
2670                         }
2671                 }
2672
2673                 if (!e) {
2674                         for (e = prefetch_wait.first; e; e = e->next) {
2675                                 if (cfra == e->cfra &&
2676                                         chanshown == e->chanshown &&
2677                                         context.rectx == e->rectx && 
2678                                         context.recty == e->recty &&
2679                                         context.preview_render_size == e->preview_render_size) {
2680                                         found_something = TRUE;
2681                                         break;
2682                                 }
2683                         }
2684                 }
2685
2686                 if (!e) {
2687                         PrefetchThread *tslot;
2688
2689                         for(tslot = running_threads.first; 
2690                                 tslot; tslot= tslot->next) {
2691                                 if (tslot->current &&
2692                                         cfra == tslot->current->cfra &&
2693                                         chanshown == tslot->current->chanshown &&
2694                                         context.rectx == tslot->current->rectx && 
2695                                         context.recty == tslot->current->recty &&
2696                                         context.preview_render_size== tslot->current->preview_render_size){
2697                                         found_something = TRUE;
2698                                         break;
2699                                 }
2700                         }
2701                 }
2702
2703                 /* e->ibuf is unrefed by render thread on next round. */
2704
2705                 if (e) {
2706                         seq_last_given_monoton_cfra = e->monoton_cfra;
2707                 }
2708
2709                 pthread_mutex_unlock(&queue_lock);
2710
2711                 if (!success) {
2712                         e = NULL;
2713
2714                         if (!found_something) {
2715                                 fprintf(stderr, 
2716                                         "SEQ-THREAD: Requested frame "
2717                                         "not in queue ???\n");
2718                                 break;
2719                         }
2720                         pthread_mutex_lock(&frame_done_lock);
2721                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
2722                         pthread_mutex_unlock(&frame_done_lock);
2723                 }
2724         }
2725         
2726         return e ? e->ibuf : NULL;
2727 }
2728
2729 /* Functions to free imbuf and anim data on changes */
2730
2731 static void free_anim_seq(Sequence *seq)
2732 {
2733         if(seq->anim) {
2734                 IMB_free_anim(seq->anim);
2735                 seq->anim = NULL;
2736         }
2737 }
2738
2739 void free_imbuf_seq(Scene *scene, ListBase * seqbase, int check_mem_usage,
2740                     int keep_file_handles)
2741 {
2742         Sequence *seq;
2743
2744         if (check_mem_usage) {
2745                 /* Let the cache limitor take care of this (schlaile) */
2746                 /* While render let's keep all memory available for render 
2747                    (ton)
2748                    At least if free memory is tight...
2749                    This can make a big difference in encoding speed
2750                    (it is around 4 times(!) faster, if we do not waste time
2751                    on freeing _all_ buffers every time on long timelines...)
2752                    (schlaile)
2753                 */
2754         
2755                 uintptr_t mem_in_use;
2756                 uintptr_t mmap_in_use;
2757                 uintptr_t max;
2758         
2759                 mem_in_use= MEM_get_memory_in_use();
2760                 mmap_in_use= MEM_get_mapped_memory_in_use();
2761                 max = MEM_CacheLimiter_get_maximum();
2762         
2763                 if (max == 0 || mem_in_use + mmap_in_use <= max) {
2764                         return;
2765                 }
2766         }
2767
2768         seq_stripelem_cache_cleanup();
2769         
2770         for(seq= seqbase->first; seq; seq= seq->next) {
2771                 if(seq->strip) {
2772                         if(seq->type==SEQ_MOVIE && !keep_file_handles)
2773                                 free_anim_seq(seq);
2774                         if(seq->type==SEQ_SPEED) {
2775                                 sequence_effect_speed_rebuild_map(scene, seq, 1);
2776                         }
2777                 }
2778                 if(seq->type==SEQ_META) {
2779                         free_imbuf_seq(scene, &seq->seqbase, FALSE, keep_file_handles);
2780                 }
2781                 if(seq->type==SEQ_SCENE) {
2782                         /* FIXME: recurs downwards, 
2783                            but do recurs protection somehow! */
2784                 }
2785         }
2786         
2787 }
2788
2789 static int update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
2790 {
2791         Sequence *subseq;
2792         int free_imbuf = 0;
2793         
2794         /* recurs downwards to see if this seq depends on the changed seq */
2795         
2796         if(seq == NULL)
2797                 return 0;
2798         
2799         if(seq == changed_seq)
2800                 free_imbuf = 1;
2801         
2802         for(subseq=seq->seqbase.first; subseq; subseq=subseq->next)
2803                 if(update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change))
2804                         free_imbuf = TRUE;
2805         
2806         if(seq->seq1)
2807                 if(update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change))
2808                         free_imbuf = TRUE;
2809         if(seq->seq2 && (seq->seq2 != seq->seq1))
2810                 if(update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change))
2811                         free_imbuf = TRUE;
2812         if(seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
2813                 if(update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change))
2814                         free_imbuf = TRUE;
2815         
2816         if(free_imbuf) {
2817                 if(ibuf_change) {
2818                         if(seq->type == SEQ_MOVIE)
2819                                 free_anim_seq(seq);
2820                         if(seq->type == SEQ_SPEED) {
2821                                 sequence_effect_speed_rebuild_map(scene, seq, 1);
2822                         }
2823                 }
2824                 
2825                 if(len_change)
2826                         calc_sequence(scene, seq);
2827         }
2828         
2829         return free_imbuf;
2830 }
2831
2832 void update_changed_seq_and_deps(Scene *scene, Sequence *changed_seq, int len_change, int ibuf_change)
2833 {
2834         Editing *ed= seq_give_editing(scene, FALSE);
2835         Sequence *seq;
2836         
2837         if (ed==NULL) return;
2838         
2839         for (seq=ed->seqbase.first; seq; seq=seq->next)
2840                 update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change);
2841 }
2842
2843 /* seq funcs's for transforming internally
2844  notice the difference between start/end and left/right.
2845
2846  left and right are the bounds at which the sequence is rendered,
2847 start and end are from the start and fixed length of the sequence.
2848 */
2849 int seq_tx_get_start(Sequence *seq) {
2850         return seq->start;
2851 }
2852 int seq_tx_get_end(Sequence *seq)
2853 {
2854         return seq->start+seq->len;
2855 }
2856
2857 int seq_tx_get_final_left(Sequence *seq, int metaclip)
2858 {
2859         if (metaclip && seq->tmp) {
2860                 /* return the range clipped by the parents range */
2861                 return MAX2( seq_tx_get_final_left(seq, 0), seq_tx_get_final_left((Sequence *)seq->tmp, 1) );
2862         } else {
2863                 return (seq->start - seq->startstill) + seq->startofs;
2864         }
2865
2866 }
2867 int seq_tx_get_final_right(Sequence *seq, int metaclip)
2868 {
2869         if (metaclip && seq->tmp) {
2870                 /* return the range clipped by the parents range */
2871                 return MIN2( seq_tx_get_final_right(seq, 0), seq_tx_get_final_right((Sequence *)seq->tmp, 1) );
2872         } else {
2873                 return ((seq->start+seq->len) + seq->endstill) - seq->endofs;
2874         }
2875 }
2876
2877 void seq_tx_set_final_left(Sequence *seq, int val)
2878 {
2879         if (val < (seq)->start) {
2880                 seq->startstill = abs(val - (seq)->start);
2881                 seq->startofs = 0;
2882         } else {
2883                 seq->startofs = abs(val - (seq)->start);
2884                 seq->startstill = 0;
2885         }
2886 }
2887
2888 void seq_tx_set_final_right(Sequence *seq, int val)
2889 {
2890         if (val > (seq)->start + (seq)->len) {
2891                 seq->endstill = abs(val - (seq->start + (seq)->len));
2892                 seq->endofs = 0;
2893         } else {
2894                 seq->endofs = abs(val - ((seq)->start + (seq)->len));
2895                 seq->endstill = 0;
2896         }
2897 }
2898
2899 /* used so we can do a quick check for single image seq
2900    since they work a bit differently to normal image seq's (during transform) */
2901 int seq_single_check(Sequence *seq)
2902 {
2903         return (seq->len==1 && (
2904                         seq->type == SEQ_IMAGE 
2905                         || ((seq->type & SEQ_EFFECT) && 
2906                             get_sequence_effect_num_inputs(seq->type) == 0)));
2907 }
2908
2909 /* check if the selected seq's reference unselected seq's */
2910 int seqbase_isolated_sel_check(ListBase *seqbase)
2911 {
2912         Sequence *seq;
2913         /* is there more than 1 select */
2914         int ok= FALSE;
2915
2916         for(seq= seqbase->first; seq; seq= seq->next) {
2917                 if(seq->flag & SELECT) {
2918                         ok= TRUE;
2919                         break;
2920                 }
2921         }
2922
2923         if(ok == FALSE)
2924                 return FALSE;
2925
2926         /* test relationships */
2927         for(seq= seqbase->first; seq; seq= seq->next) {
2928                 if((seq->type & SEQ_EFFECT)==0)
2929                         continue;
2930
2931                 if(seq->flag & SELECT) {
2932                         if( (seq->seq1 && (seq->seq1->flag & SELECT)==0) ||
2933                                 (seq->seq2 && (seq->seq2->flag & SELECT)==0) ||
2934                                 (seq->seq3 && (seq->seq3->flag & SELECT)==0) )
2935                                 return FALSE;
2936                 }
2937                 else {
2938                         if( (seq->seq1 && (seq->seq1->flag & SELECT)) ||
2939                                 (seq->seq2 && (seq->seq2->flag & SELECT)) ||
2940                                 (seq->seq3 && (seq->seq3->flag & SELECT)) )
2941                                 return FALSE;
2942                 }
2943         }
2944
2945         return TRUE;
2946 }
2947
2948 /* use to impose limits when dragging/extending - so impossible situations dont happen
2949  * Cant use the SEQ_LEFTSEL and SEQ_LEFTSEL directly because the strip may be in a metastrip */
2950 void seq_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag)
2951 {
2952         if(leftflag) {
2953                 if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_final_right(seq, 0)) {
2954                         seq_tx_set_final_left(seq, seq_tx_get_final_right(seq, 0)-1);
2955                 }
2956
2957                 if (seq_single_check(seq)==0) {
2958                         if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_end(seq)) {
2959                                 seq_tx_set_final_left(seq, seq_tx_get_end(seq)-1);
2960                         }
2961
2962                         /* dosnt work now - TODO */
2963                         /*
2964                         if (seq_tx_get_start(seq) >= seq_tx_get_final_right(seq, 0)) {
2965                                 int ofs;
2966                                 ofs = seq_tx_get_start(seq) - seq_tx_get_final_right(seq, 0);
2967                                 seq->start -= ofs;
2968                                 seq_tx_set_final_left(seq, seq_tx_get_final_left(seq, 0) + ofs );
2969                         }*/
2970
2971                 }
2972         }
2973
2974         if(rightflag) {
2975                 if (seq_tx_get_final_right(seq, 0) <=  seq_tx_get_final_left(seq, 0)) {
2976                         seq_tx_set_final_right(seq, seq_tx_get_final_left(seq, 0)+1);
2977                 }
2978
2979                 if (seq_single_check(seq)==0) {
2980                         if (seq_tx_get_final_right(seq, 0) <= seq_tx_get_start(seq)) {
2981                                 seq_tx_set_final_right(seq, seq_tx_get_start(seq)+1);
2982                         }
2983                 }
2984         }
2985
2986         /* sounds cannot be extended past their endpoints */
2987         if (seq->type == SEQ_SOUND) {
2988                 seq->startstill= 0;
2989                 seq->endstill= 0;
2990         }
2991 }
2992
2993 void seq_single_fix(Sequence *seq)
2994 {
2995         int left, start, offset;
2996         if (!seq_single_check(seq))
2997                 return;
2998
2999         /* make sure the image is always at the start since there is only one,
3000            adjusting its start should be ok */
3001         left = seq_tx_get_final_left(seq, 0);
3002         start = seq->start;
3003         if (start != left) {
3004                 offset = left - start;
3005                 seq_tx_set_final_left( seq, seq_tx_get_final_left(seq, 0) - offset );
3006                 seq_tx_set_final_right( seq, seq_tx_get_final_right(seq, 0) - offset );
3007                 seq->start += offset;
3008         }
3009 }
3010
3011 int seq_tx_test(Sequence * seq)
3012 {
3013         return (seq->type < SEQ_EFFECT) || (get_sequence_effect_num_inputs(seq->type) == 0);
3014 }
3015
3016 static int seq_overlap(Sequence *seq1, Sequence *seq2)
3017 {
3018         return (seq1 != seq2 && seq1->machine == seq2->machine &&
3019                         ((seq1->enddisp <= seq2->startdisp) || (seq1->startdisp >= seq2->enddisp))==0);
3020 }
3021
3022 int seq_test_overlap(ListBase * seqbasep, Sequence *test)
3023 {
3024         Sequence *seq;
3025
3026         seq= seqbasep->first;
3027         while(seq) {
3028                 if(seq_overlap(test, seq))
3029                         return 1;
3030
3031                 seq= seq->next;
3032         }
3033         return 0;
3034 }
3035
3036
3037 void seq_translate(Scene *evil_scene, Sequence *seq, int delta)
3038 {
3039         seq_offset_animdata(evil_scene, seq, delta);
3040         seq->start += delta;
3041
3042         if(seq->type==SEQ_META) {
3043                 Sequence *seq_child;
3044                 for(seq_child= seq->seqbase.first; seq_child; seq_child= seq_child->next) {
3045                         seq_translate(evil_scene, seq_child, delta);
3046                 }
3047         }
3048
3049         calc_sequence_disp(evil_scene, seq);
3050 }
3051
3052 void seq_sound_init(Scene *scene, Sequence *seq)
3053 {
3054         if(seq->type==SEQ_META) {
3055                 Sequence *seq_child;
3056                 for(seq_child= seq->seqbase.first; seq_child; seq_child= seq_child->next) {
3057                         seq_sound_init(scene, seq_child);
3058                 }
3059         }
3060         else {
3061                 if(seq->sound) {
3062                         seq->scene_sound = sound_add_scene_sound(scene, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3063                 }
3064                 if(seq->scene) {
3065                         sound_scene_add_scene_sound(scene, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3066                 }
3067         }
3068 }
3069
3070 Sequence *seq_foreground_frame_get(Scene *scene, int frame)
3071 {
3072         Editing *ed= seq_give_editing(scene, FALSE);
3073         Sequence *seq, *best_seq=NULL;
3074         int best_machine = -1;
3075         
3076         if(!ed) return NULL;
3077         
3078         for (seq=ed->seqbasep->first; seq; seq= seq->next) {
3079                 if(seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame)
3080                         continue;
3081                 /* only use elements you can see - not */
3082                 if (ELEM5(seq->type, SEQ_IMAGE, SEQ_META, SEQ_SCENE, SEQ_MOVIE, SEQ_COLOR)) {
3083                         if (seq->machine > best_machine) {
3084                                 best_seq = seq;
3085                                 best_machine = seq->machine;
3086                         }
3087                 }
3088         }
3089         return best_seq;
3090 }
3091
3092 /* return 0 if there werent enough space */
3093 int shuffle_seq(ListBase * seqbasep, Sequence *test, Scene *evil_scene)
3094 {
3095         int orig_machine= test->machine;
3096         test->machine++;
3097         calc_sequence(evil_scene, test);
3098         while( seq_test_overlap(seqbasep, test) ) {
3099                 if(test->machine >= MAXSEQ) {
3100                         break;
3101                 }
3102                 test->machine++;
3103                 calc_sequence(evil_scene, test); // XXX - I dont think this is needed since were only moving vertically, Campbell.
3104         }
3105
3106         
3107         if(test->machine >= MAXSEQ) {
3108                 /* Blender 2.4x would remove the strip.
3109                  * nicer to move it to the end */
3110
3111                 Sequence *seq;
3112                 int new_frame= test->enddisp;
3113
3114                 for(seq= seqbasep->first; seq; seq= seq->next) {
3115                         if (seq->machine == orig_machine)
3116                                 new_frame = MAX2(new_frame, seq->enddisp);
3117                 }
3118
3119                 test->machine= orig_machine;
3120                 new_frame = new_frame + (test->start-test->startdisp); /* adjust by the startdisp */
3121                 seq_translate(evil_scene, test, new_frame - test->start);
3122
3123                 calc_sequence(evil_scene, test);
3124                 return 0;
3125         } else {
3126                 return 1;
3127         }
3128 }
3129
3130 static int shuffle_seq_time_offset_test(ListBase * seqbasep, char dir)
3131 {
3132         int offset= 0;
3133         Sequence *seq, *seq_other;
3134
3135         for(seq= seqbasep->first; seq; seq= seq->next) {
3136                 if(seq->tmp) {
3137                         for(seq_other= seqbasep->first; seq_other; seq_other= seq_other->next) {
3138                                 if(!seq_other->tmp && seq_overlap(seq, seq_other)) {
3139                                         if(dir=='L') {
3140                                                 offset= MIN2(offset, seq_other->startdisp - seq->enddisp);
3141                                         }
3142                                         else {
3143                                                 offset= MAX2(offset, seq_other->enddisp - seq->startdisp);
3144                                         }
3145                                 }
3146                         }
3147                 }
3148         }
3149         return offset;
3150 }
3151
3152 static int shuffle_seq_time_offset(Scene* scene, ListBase * seqbasep, char dir)
3153 {
3154         int ofs= 0;
3155         int tot_ofs= 0;
3156         Sequence *seq;
3157         while( (ofs= shuffle_seq_time_offset_test(seqbasep, dir)) ) {
3158                 for(seq= seqbasep->first; seq; seq= seq->next) {
3159                         if(seq->tmp) {
3160                                 /* seq_test_overlap only tests display values */
3161                                 seq->startdisp +=       ofs;
3162                                 seq->enddisp +=         ofs;
3163                         }
3164                 }
3165
3166                 tot_ofs+= ofs;
3167         }
3168
3169         for(seq= seqbasep->first; seq; seq= seq->next) {
3170                 if(seq->tmp)
3171                         calc_sequence_disp(scene, seq); /* corrects dummy startdisp/enddisp values */
3172         }
3173
3174         return tot_ofs;
3175 }
3176
3177 int shuffle_seq_time(ListBase * seqbasep, Scene *evil_scene)
3178 {
3179         /* note: seq->tmp is used to tag strips to move */
3180
3181         Sequence *seq;
3182
3183         int offset_l = shuffle_seq_time_offset(evil_scene, seqbasep, 'L');
3184         int offset_r = shuffle_seq_time_offset(evil_scene, seqbasep, 'R');
3185         int offset = (-offset_l < offset_r) ?  offset_l:offset_r;
3186
3187         if(offset) {
3188                 for(seq= seqbasep->first; seq; seq= seq->next) {
3189                         if(seq->tmp) {
3190                                 seq_translate(evil_scene, seq, offset);
3191                                 seq->flag &= ~SEQ_OVERLAP;
3192                         }
3193                 }
3194         }
3195
3196         return offset? 0:1;
3197 }
3198
3199 void seq_update_sound(Scene* scene, Sequence *seq)
3200 {
3201         if(seq->scene_sound)
3202         {
3203                 sound_move_scene_sound(scene, seq->scene_sound, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3204                 /* mute is set in seq_update_muting_recursive */
3205         }
3206 }
3207
3208 static void seq_update_muting_recursive(Scene *scene, ListBase *seqbasep, Sequence *metaseq, int mute)
3209 {
3210         Sequence *seq;
3211         int seqmute;
3212
3213         /* for sound we go over full meta tree to update muted state,
3214            since sound is played outside of evaluating the imbufs, */
3215         for(seq=seqbasep->first; seq; seq=seq->next) {
3216                 seqmute= (mute || (seq->flag & SEQ_MUTE));
3217
3218                 if(seq->type == SEQ_META) {
3219                         /* if this is the current meta sequence, unmute because
3220                            all sequences above this were set to mute */
3221                         if(seq == metaseq)
3222                                 seqmute= 0;
3223
3224                         seq_update_muting_recursive(scene, &seq->seqbase, metaseq, seqmute);
3225                 }
3226                 else if(ELEM(seq->type, SEQ_SOUND, SEQ_SCENE)) {
3227                         if(seq->scene_sound) {
3228                                 sound_mute_scene_sound(scene, seq->scene_sound, seqmute);
3229                         }
3230                 }
3231         }
3232 }
3233
3234 void seq_update_muting(Scene *scene, Editing *ed)
3235 {
3236         if(ed) {
3237                 /* mute all sounds up to current metastack list */
3238                 MetaStack *ms= ed->metastack.last;
3239
3240                 if(ms)
3241                         seq_update_muting_recursive(scene, &ed->seqbase, ms->parseq, 1);
3242                 else
3243                         seq_update_muting_recursive(scene, &ed->seqbase, NULL, 0);
3244         }
3245 }
3246
3247 /* in cases where we done know the sequence's listbase */
3248 ListBase *seq_seqbase(ListBase *seqbase, Sequence *seq)
3249 {
3250         Sequence *iseq;
3251         ListBase *lb= NULL;
3252
3253         for(iseq= seqbase->first; iseq; iseq= iseq->next) {
3254                 if(seq==iseq) {
3255                         return seqbase;
3256                 }
3257                 else if(iseq->seqbase.first && (lb= seq_seqbase(&iseq->seqbase, seq))) {
3258                         return lb;
3259                 }
3260         }
3261
3262         return NULL;
3263 }
3264
3265 Sequence *seq_metastrip(ListBase * seqbase, Sequence * meta, Sequence *seq)
3266 {
3267         Sequence * iseq;
3268
3269         for(iseq = seqbase->first; iseq; iseq = iseq->next) {
3270                 Sequence * rval;
3271
3272                 if (seq == iseq) {
3273                         return meta;
3274                 } else if(iseq->seqbase.first && 
3275                         (rval = seq_metastrip(&iseq->seqbase, iseq, seq))) {
3276                         return rval;
3277                 }
3278         }
3279
3280         return NULL;
3281 }
3282
3283 int seq_swap(Sequence *seq_a, Sequence *seq_b, const char **error_str)
3284 {
3285         char name[sizeof(seq_a->name)];
3286
3287         if(seq_a->len != seq_b->len) {
3288                 *error_str= "Strips must be the same length";
3289                 return 0;
3290         }
3291
3292         /* type checking, could be more advanced but disalow sound vs non-sound copy */
3293         if(seq_a->type != seq_b->type) {
3294                 if(seq_a->type == SEQ_SOUND || seq_b->type == SEQ_SOUND) {
3295                         *error_str= "Strips were not compatible";
3296                         return 0;
3297                 }