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