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