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