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