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