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