synched with trunk at revision 34793
[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                 }
732
733                 seq->len= seq->scene->r.efra - seq->scene->r.sfra + 1;
734                 seq->len -= seq->anim_startofs;
735                 seq->len -= seq->anim_endofs;
736                 if (seq->len < 0) {
737                         seq->len = 0;
738                 }
739                 seq->strip->len = seq->len;
740                 break;
741         }
742         }
743
744         free_proxy_seq(seq);
745
746         if(lock_range) {
747                 seq_tx_set_final_left(seq, prev_startdisp);
748                 seq_tx_set_final_right(seq, prev_enddisp);
749                 seq_single_fix(seq);
750         }
751         
752         calc_sequence(scene, seq);
753 }
754
755 void sort_seq(Scene *scene)
756 {
757         /* all strips together per kind, and in order of y location ("machine") */
758         ListBase seqbase, effbase;
759         Editing *ed= seq_give_editing(scene, FALSE);
760         Sequence *seq, *seqt;
761
762         
763         if(ed==NULL) return;
764
765         seqbase.first= seqbase.last= 0;
766         effbase.first= effbase.last= 0;
767
768         while( (seq= ed->seqbasep->first) ) {
769                 BLI_remlink(ed->seqbasep, seq);
770
771                 if(seq->type & SEQ_EFFECT) {
772                         seqt= effbase.first;
773                         while(seqt) {
774                                 if(seqt->machine>=seq->machine) {
775                                         BLI_insertlinkbefore(&effbase, seqt, seq);
776                                         break;
777                                 }
778                                 seqt= seqt->next;
779                         }
780                         if(seqt==0) BLI_addtail(&effbase, seq);
781                 }
782                 else {
783                         seqt= seqbase.first;
784                         while(seqt) {
785                                 if(seqt->machine>=seq->machine) {
786                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
787                                         break;
788                                 }
789                                 seqt= seqt->next;
790                         }
791                         if(seqt==0) BLI_addtail(&seqbase, seq);
792                 }
793         }
794
795         BLI_movelisttolist(&seqbase, &effbase);
796         *(ed->seqbasep)= seqbase;
797 }
798
799
800 static int clear_scene_in_allseqs_cb(Sequence *seq, void *arg_pt)
801 {
802         if(seq->scene==(Scene *)arg_pt)
803                 seq->scene= NULL;
804         return 1;
805 }
806
807 void clear_scene_in_allseqs(Main *bmain, Scene *scene)
808 {
809         Scene *scene_iter;
810
811         /* when a scene is deleted: test all seqs */
812         for(scene_iter= bmain->scene.first; scene_iter; scene_iter= scene_iter->id.next) {
813                 if(scene_iter != scene && scene_iter->ed) {
814                         seqbase_recursive_apply(&scene_iter->ed->seqbase, clear_scene_in_allseqs_cb, scene);
815                 }
816         }
817 }
818
819 typedef struct SeqUniqueInfo {
820         Sequence *seq;
821         char name_src[32];
822         char name_dest[32];
823         int count;
824         int match;
825 } SeqUniqueInfo;
826
827 /*
828 static void seqbase_unique_name(ListBase *seqbasep, Sequence *seq)
829 {
830          BLI_uniquename(seqbasep, seq, "Sequence", '.', offsetof(Sequence, name), SEQ_NAME_MAXSTR);
831 }*/
832
833 static void seqbase_unique_name(ListBase *seqbasep, SeqUniqueInfo *sui)
834 {
835         Sequence *seq;
836         for(seq=seqbasep->first; seq; seq= seq->next) {
837                 if (sui->seq != seq && strcmp(sui->name_dest, seq->name+2)==0) {
838                         sprintf(sui->name_dest, "%.17s.%03d",  sui->name_src, sui->count++); /*24 - 2 for prefix, -1 for \0 */
839                         sui->match= 1; /* be sure to re-scan */
840                 }
841         }
842 }
843
844 static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt)
845 {
846         if(seq->seqbase.first)
847                 seqbase_unique_name(&seq->seqbase, (SeqUniqueInfo *)arg_pt);
848         return 1;
849 }
850
851 void seqbase_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq)
852 {
853         SeqUniqueInfo sui;
854         char *dot;
855         sui.seq= seq;
856         strcpy(sui.name_src, seq->name+2);
857         strcpy(sui.name_dest, seq->name+2);
858
859         sui.count= 1;
860         sui.match= 1; /* assume the worst to start the loop */
861
862         /* Strip off the suffix */
863         if ((dot=strrchr(sui.name_src, '.'))) {
864                 *dot= '\0';
865                 dot++;
866
867                 if(*dot)
868                         sui.count= atoi(dot) + 1;
869         }
870
871         while(sui.match) {
872                 sui.match= 0;
873                 seqbase_unique_name(seqbasep, &sui);
874                 seqbase_recursive_apply(seqbasep, seqbase_unique_name_recursive_cb, &sui);
875         }
876
877         strcpy(seq->name+2, sui.name_dest);
878 }
879
880 static const char *give_seqname_by_type(int type)
881 {
882         switch(type) {
883         case SEQ_META:       return "Meta";
884         case SEQ_IMAGE:      return "Image";
885         case SEQ_SCENE:      return "Scene";
886         case SEQ_MOVIE:      return "Movie";
887         case SEQ_SOUND:      return "Audio";
888         case SEQ_CROSS:      return "Cross";
889         case SEQ_GAMCROSS:   return "Gamma Cross";
890         case SEQ_ADD:        return "Add";
891         case SEQ_SUB:        return "Sub";
892         case SEQ_MUL:        return "Mul";
893         case SEQ_ALPHAOVER:  return "Alpha Over";
894         case SEQ_ALPHAUNDER: return "Alpha Under";
895         case SEQ_OVERDROP:   return "Over Drop";
896         case SEQ_WIPE:       return "Wipe";
897         case SEQ_GLOW:       return "Glow";
898         case SEQ_TRANSFORM:  return "Transform";
899         case SEQ_COLOR:      return "Color";
900         case SEQ_MULTICAM:   return "Multicam";
901         case SEQ_SPEED:      return "Speed";
902         default:
903                 return NULL;
904         }
905 }
906
907 const char *give_seqname(Sequence *seq)
908 {
909         const char *name = give_seqname_by_type(seq->type);
910
911         if (!name) {
912                 if(seq->type<SEQ_EFFECT) {
913                         return seq->strip->dir;
914                 } else if(seq->type==SEQ_PLUGIN) {
915                         if(!(seq->flag & SEQ_EFFECT_NOT_LOADED) &&
916                            seq->plugin && seq->plugin->doit) {
917                                 return seq->plugin->pname;
918                         } else {
919                                 return "Plugin";
920                         }
921                 } else {
922                         return "Effect";
923                 }
924         }
925         return name;
926 }
927
928 /* ***************** DO THE SEQUENCE ***************** */
929
930 static void make_black_ibuf(ImBuf *ibuf)
931 {
932         unsigned int *rect;
933         float *rect_float;
934         int tot;
935
936         if(ibuf==0 || (ibuf->rect==0 && ibuf->rect_float==0)) return;
937
938         tot= ibuf->x*ibuf->y;
939
940         rect= ibuf->rect;
941         rect_float = ibuf->rect_float;
942
943         if (rect) {
944                 memset(rect,       0, tot * sizeof(char) * 4);
945         }
946
947         if (rect_float) {
948                 memset(rect_float, 0, tot * sizeof(float) * 4);
949         }
950 }
951
952 static void multibuf(ImBuf *ibuf, float fmul)
953 {
954         char *rt;
955         float *rt_float;
956
957         int a, mul, icol;
958
959         mul= (int)(256.0*fmul);
960         rt= (char *)ibuf->rect;
961         rt_float = ibuf->rect_float;
962
963         if (rt) {
964                 a= ibuf->x*ibuf->y;
965                 while(a--) {
966
967                         icol= (mul*rt[0])>>8;
968                         if(icol>254) rt[0]= 255; else rt[0]= icol;
969                         icol= (mul*rt[1])>>8;
970                         if(icol>254) rt[1]= 255; else rt[1]= icol;
971                         icol= (mul*rt[2])>>8;
972                         if(icol>254) rt[2]= 255; else rt[2]= icol;
973                         icol= (mul*rt[3])>>8;
974                         if(icol>254) rt[3]= 255; else rt[3]= icol;
975                         
976                         rt+= 4;
977                 }
978         }
979         if (rt_float) {
980                 a= ibuf->x*ibuf->y;
981                 while(a--) {
982                         rt_float[0] *= fmul;
983                         rt_float[1] *= fmul;
984                         rt_float[2] *= fmul;
985                         rt_float[3] *= fmul;
986                         
987                         rt_float += 4;
988                 }
989         }
990 }
991
992 static float give_stripelem_index(Sequence *seq, float cfra)
993 {
994         float nr;
995         int sta = seq->start;
996         int end = seq->start+seq->len-1;
997
998         if(seq->len == 0) return -1;
999
1000         if(seq->flag&SEQ_REVERSE_FRAMES) {      
1001                 /*reverse frame in this sequence */
1002                 if(cfra <= sta) nr= seq->len-1;
1003                 else if(cfra >= end) nr= 0;
1004                 else nr= end - cfra;
1005         } else {
1006                 if(cfra <= sta) nr= 0;
1007                 else if(cfra >= end) nr= seq->len-1;
1008                 else nr= cfra - sta;
1009         }
1010         
1011         if (seq->strobe < 1.0) seq->strobe = 1.0;
1012         
1013         if (seq->strobe > 1.0) {
1014                 nr -= fmod((double)nr, (double)seq->strobe);
1015         }
1016
1017         return nr;
1018 }
1019
1020 StripElem *give_stripelem(Sequence *seq, int cfra)
1021 {
1022         StripElem *se= seq->strip->stripdata;
1023
1024         if(seq->type != SEQ_MOVIE) { /* movie use the first */
1025                 int nr = (int) give_stripelem_index(seq, cfra);
1026
1027                 if (nr == -1 || se == 0) return 0;
1028         
1029                 se += nr + seq->anim_startofs;
1030         }
1031         return se;
1032 }
1033
1034 static int evaluate_seq_frame_gen(Sequence ** seq_arr, ListBase *seqbase, int cfra)
1035 {
1036         Sequence *seq;
1037         int totseq=0;
1038
1039         memset(seq_arr, 0, sizeof(Sequence*) * (MAXSEQ+1));
1040
1041         seq= seqbase->first;
1042         while(seq) {
1043                 if(seq->startdisp <=cfra && seq->enddisp > cfra) {
1044                         seq_arr[seq->machine]= seq;
1045                         totseq++;
1046                 }
1047                 seq= seq->next;
1048         }
1049
1050         return totseq;
1051 }
1052
1053 int evaluate_seq_frame(Scene *scene, int cfra)
1054 {
1055         Editing *ed= seq_give_editing(scene, FALSE);
1056         Sequence *seq_arr[MAXSEQ+1];
1057
1058         if(ed==NULL) return 0;
1059         return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
1060 }
1061
1062 static int video_seq_is_rendered(Sequence * seq)
1063 {
1064         return (seq && !(seq->flag & SEQ_MUTE) && seq->type != SEQ_SOUND);
1065 }
1066
1067 static int get_shown_sequences( ListBase * seqbasep, int cfra, int chanshown, Sequence ** seq_arr_out)
1068 {
1069         Sequence *seq_arr[MAXSEQ+1];
1070         int b = chanshown;
1071         int cnt = 0;
1072
1073         if (b > MAXSEQ) {
1074                 return 0;
1075         }
1076
1077         if(evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
1078                 if (b > 0) {
1079                         if (seq_arr[b] == 0) {
1080                                 return 0;
1081                         }
1082                 } else {
1083                         for (b = MAXSEQ; b > 0; b--) {
1084                                 if (video_seq_is_rendered(seq_arr[b])) {
1085                                         break;
1086                                 }
1087                         }
1088                 }
1089         }
1090         
1091         chanshown = b;
1092
1093         for (;b > 0; b--) {
1094                 if (video_seq_is_rendered(seq_arr[b])) {
1095                         if (seq_arr[b]->blend_mode == SEQ_BLEND_REPLACE) {
1096                                 break;
1097                         }
1098                 }
1099         }
1100
1101         for (;b <= chanshown && b >= 0; b++) {
1102                 if (video_seq_is_rendered(seq_arr[b])) {
1103                         seq_arr_out[cnt++] = seq_arr[b];
1104                 }
1105         }
1106
1107         return cnt;
1108 }
1109  
1110
1111 /* **********************************************************************
1112    proxy management
1113    ********************************************************************** */
1114
1115 #define PROXY_MAXFILE (2*FILE_MAXDIR+FILE_MAXFILE)
1116
1117 static int seq_proxy_get_fname(SeqRenderData context, Sequence * seq, int cfra, char * name)
1118 {
1119         int frameno;
1120         char dir[FILE_MAXDIR];
1121
1122         if (!seq->strip->proxy) {
1123                 return FALSE;
1124         }
1125
1126         if (seq->flag & (SEQ_USE_PROXY_CUSTOM_DIR|SEQ_USE_PROXY_CUSTOM_FILE)) {
1127                 strcpy(dir, seq->strip->proxy->dir);
1128         } else {
1129                 if (ELEM(seq->type, SEQ_IMAGE, SEQ_MOVIE)) {
1130                         snprintf(dir, FILE_MAXDIR, "%s/BL_proxy", seq->strip->dir);
1131                 } else {
1132                         return FALSE;
1133                 }
1134         }
1135
1136         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1137                 BLI_join_dirfile(name, dir, seq->strip->proxy->file);
1138                 BLI_path_abs(name, G.main->name);
1139
1140                 return TRUE;
1141         }
1142
1143         /* generate a separate proxy directory for each preview size */
1144
1145         switch(seq->type) {
1146         case SEQ_IMAGE:
1147                 snprintf(name, PROXY_MAXFILE, "%s/images/%d/%s_proxy", dir,
1148                          context.preview_render_size, 
1149                          give_stripelem(seq, cfra)->name);
1150                 frameno = 1;
1151                 break;
1152         case SEQ_MOVIE:
1153                 frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1154                 snprintf(name, PROXY_MAXFILE, "%s/%s/%d/####", dir,
1155                          seq->strip->stripdata->name, context.preview_render_size);
1156                 break;
1157         default:
1158                 frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1159                 snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####", dir, 
1160                          context.preview_render_size);
1161         }
1162
1163         BLI_path_abs(name, G.main->name);
1164         BLI_path_frame(name, frameno, 0);
1165
1166         strcat(name, ".jpg");
1167
1168         return TRUE;
1169 }
1170
1171 static struct ImBuf * seq_proxy_fetch(SeqRenderData context, Sequence * seq, int cfra)
1172 {
1173         char name[PROXY_MAXFILE];
1174
1175         if (!(seq->flag & SEQ_USE_PROXY)) {
1176                 return 0;
1177         }
1178
1179         /* rendering at 100% ? No real sense in proxy-ing, right? */
1180         if (context.preview_render_size == 100) {
1181                 return 0;
1182         }
1183
1184         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1185                 int frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1186                 if (seq->strip->proxy->anim == NULL) {
1187                         if (seq_proxy_get_fname(context, seq, cfra, name)==0) {
1188                                 return 0;
1189                         }
1190  
1191                         seq->strip->proxy->anim = openanim(name, IB_rect);
1192                 }
1193                 if (seq->strip->proxy->anim==NULL) {
1194                         return 0;
1195                 }
1196  
1197                 return IMB_anim_absolute(seq->strip->proxy->anim, frameno);
1198         }
1199  
1200         if (seq_proxy_get_fname(context, seq, cfra, name) == 0) {
1201                 return 0;
1202         }
1203
1204         if (BLI_exists(name)) {
1205                 return IMB_loadiffname(name, IB_rect);
1206         } else {
1207                 return 0;
1208         }
1209 }
1210
1211 #if 0
1212 static void do_build_seq_ibuf(Scene *scene, Sequence * seq, TStripElem *se, int cfra,
1213                                   int build_proxy_run, int preview_render_size);
1214
1215 static void seq_proxy_build_frame(Scene *scene, Sequence * seq, int cfra, int preview_render_size, int seqrectx, int seqrecty)
1216 {
1217         char name[PROXY_MAXFILE];
1218         int quality;
1219         TStripElem * se;
1220         int ok;
1221         int rectx, recty;
1222         struct ImBuf * ibuf;
1223
1224         if (!(seq->flag & SEQ_USE_PROXY)) {
1225                 return;
1226         }
1227
1228         /* rendering at 100% ? No real sense in proxy-ing, right? */
1229         if (preview_render_size == 100) {
1230                 return;
1231         }
1232
1233         /* that's why it is called custom... */
1234         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1235                 return;
1236         }
1237
1238         if (!seq_proxy_get_fname(scene, seq, cfra, name, preview_render_size)) {
1239                 return;
1240         }
1241
1242         se = give_tstripelem(seq, cfra);
1243         if (!se) {
1244                 return;
1245         }
1246
1247         if(se->ibuf) {
1248                 IMB_freeImBuf(se->ibuf);
1249                 se->ibuf = 0;
1250         }
1251         
1252         do_build_seq_ibuf(scene, seq, se, cfra, TRUE, preview_render_size,
1253                           seqrectx, seqrecty);
1254
1255         if (!se->ibuf) {
1256                 return;
1257         }
1258
1259         rectx= (preview_render_size*scene->r.xsch)/100;
1260         recty= (preview_render_size*scene->r.ysch)/100;
1261
1262         ibuf = se->ibuf;
1263
1264         if (ibuf->x != rectx || ibuf->y != recty) {
1265                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1266         }
1267
1268         /* quality is fixed, otherwise one has to generate separate
1269            directories for every quality...
1270
1271            depth = 32 is intentionally left in, otherwise ALPHA channels
1272            won't work... */
1273         quality = seq->strip->proxy->quality;
1274         ibuf->ftype= JPG | quality;
1275
1276         BLI_make_existing_file(name);
1277         
1278         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1279         if (ok == 0) {
1280                 perror(name);
1281         }
1282
1283         IMB_freeImBuf(ibuf);
1284         se->ibuf = 0;
1285 }
1286
1287 static void seq_proxy_rebuild(Scene *scene, Sequence * seq, int seqrectx,
1288                               int seqrecty)
1289 {
1290         int cfra;
1291         float rsize = seq->strip->proxy->size;
1292
1293         waitcursor(1);
1294
1295         G.afbreek = 0;
1296
1297         /* flag management tries to account for strobe and 
1298            other "non-linearities", that might come in the future...
1299            better way would be to "touch" the files, so that _really_
1300            no one is rebuild twice.
1301          */
1302
1303         for (cfra = seq->startdisp; cfra < seq->enddisp; cfra++) {
1304                 TStripElem * tse = give_tstripelem(seq, cfra);
1305
1306                 tse->flag &= ~STRIPELEM_PREVIEW_DONE;
1307         }
1308
1309         
1310
1311         /* a _lot_ faster for movie files, if we read frames in
1312            sequential order */
1313         if (seq->flag & SEQ_REVERSE_FRAMES) {
1314                 for (cfra = seq->enddisp-seq->endstill-1; 
1315                          cfra >= seq->startdisp + seq->startstill; cfra--) {
1316                         TStripElem * tse = give_tstripelem(seq, cfra);
1317
1318                         if (!(tse->flag & STRIPELEM_PREVIEW_DONE)) {
1319 //XXX                           set_timecursor(cfra);
1320                                 seq_proxy_build_frame(scene, seq, cfra, rsize,
1321                                                       seqrectx, seqrecty);
1322                                 tse->flag |= STRIPELEM_PREVIEW_DONE;
1323                         }
1324                         if (blender_test_break()) {
1325                                 break;
1326                         }
1327                 }
1328         } else {
1329                 for (cfra = seq->startdisp + seq->startstill; 
1330                          cfra < seq->enddisp - seq->endstill; cfra++) {
1331                         TStripElem * tse = give_tstripelem(seq, cfra);
1332
1333                         if (!(tse->flag & STRIPELEM_PREVIEW_DONE)) {
1334 //XXX                           set_timecursor(cfra);
1335                                 seq_proxy_build_frame(scene, seq, cfra, rsize,
1336                                                       seqrectx, seqrecty);
1337                                 tse->flag |= STRIPELEM_PREVIEW_DONE;
1338                         }
1339                         if (blender_test_break()) {
1340                                 break;
1341                         }
1342                 }
1343         }
1344         waitcursor(0);
1345 }
1346 #endif
1347
1348
1349 /* **********************************************************************
1350    color balance 
1351    ********************************************************************** */
1352
1353 static StripColorBalance calc_cb(StripColorBalance * cb_)
1354 {
1355         StripColorBalance cb = *cb_;
1356         int c;
1357
1358         for (c = 0; c < 3; c++) {
1359                 cb.lift[c] = 2.0f - cb.lift[c];
1360         }
1361
1362         if(cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1363                 for (c = 0; c < 3; c++) {
1364                         /* tweak to give more subtle results
1365                          * values above 1.0 are scaled */
1366                         if(cb.lift[c] > 1.0f)
1367                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0f) + 1.0f;
1368
1369                         cb.lift[c] = 2.0f - cb.lift[c];
1370                 }
1371         }
1372
1373         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1374                 for (c = 0; c < 3; c++) {
1375                         if (cb.gain[c] != 0.0) {
1376                                 cb.gain[c] = 1.0/cb.gain[c];
1377                         } else {
1378                                 cb.gain[c] = 1000000; /* should be enough :) */
1379                         }
1380                 }
1381         }
1382
1383         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1384                 for (c = 0; c < 3; c++) {
1385                         if (cb.gamma[c] != 0.0) {
1386                                 cb.gamma[c] = 1.0/cb.gamma[c];
1387                         } else {
1388                                 cb.gamma[c] = 1000000; /* should be enough :) */
1389                         }
1390                 }
1391         }
1392
1393         return cb;
1394 }
1395
1396 /* note: lift is actually 2-lift */
1397 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1398 {
1399         float x= (((in - 1.0f) * lift) + 1.0f) * gain;
1400
1401         /* prevent NaN */
1402         if (x < 0.f) x = 0.f;
1403
1404         return powf(x, gamma) * mul;
1405 }
1406
1407 static void make_cb_table_byte(float lift, float gain, float gamma,
1408                                    unsigned char * table, float mul)
1409 {
1410         int y;
1411
1412         for (y = 0; y < 256; y++) {
1413                 float v= color_balance_fl((float)y * (1.0 / 255.0f), lift, gain, gamma, mul);
1414                 CLAMP(v, 0.0f, 1.0f);
1415                 table[y] = v * 255;
1416         }
1417 }
1418
1419 static void make_cb_table_float(float lift, float gain, float gamma,
1420                                 float * table, float mul)
1421 {
1422         int y;
1423
1424         for (y = 0; y < 256; y++) {
1425                 float v= color_balance_fl((float)y * (1.0 / 255.0f), lift, gain, gamma, mul);
1426                 table[y] = v;
1427         }
1428 }
1429
1430 static void color_balance_byte_byte(Sequence * seq, ImBuf* ibuf, float mul)
1431 {
1432         unsigned char cb_tab[3][256];
1433         int c;
1434         unsigned char * p = (unsigned char*) ibuf->rect;
1435         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1436
1437         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1438
1439         for (c = 0; c < 3; c++) {
1440                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c],
1441                                    cb_tab[c], mul);
1442         }
1443
1444         while (p < e) {
1445                 p[0] = cb_tab[0][p[0]];
1446                 p[1] = cb_tab[1][p[1]];
1447                 p[2] = cb_tab[2][p[2]];
1448                 
1449                 p += 4;
1450         }
1451 }
1452
1453 static void color_balance_byte_float(Sequence * seq, ImBuf* ibuf, float mul)
1454 {
1455         float cb_tab[4][256];
1456         int c,i;
1457         unsigned char * p = (unsigned char*) ibuf->rect;
1458         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1459         float * o;
1460         StripColorBalance cb;
1461
1462         imb_addrectfloatImBuf(ibuf);
1463
1464         o = ibuf->rect_float;
1465
1466         cb = calc_cb(seq->strip->color_balance);
1467
1468         for (c = 0; c < 3; c++) {
1469                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1470         }
1471
1472         for (i = 0; i < 256; i++) {
1473                 cb_tab[3][i] = ((float)i)*(1.0f/255.0f);
1474         }
1475
1476         while (p < e) {
1477                 o[0] = cb_tab[0][p[0]];
1478                 o[1] = cb_tab[1][p[1]];
1479                 o[2] = cb_tab[2][p[2]];
1480                 o[3] = cb_tab[3][p[3]];
1481
1482                 p += 4; o += 4;
1483         }
1484 }
1485
1486 static void color_balance_float_float(Sequence * seq, ImBuf* ibuf, float mul)
1487 {
1488         float * p = ibuf->rect_float;
1489         float * e = ibuf->rect_float + ibuf->x * 4* ibuf->y;
1490         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1491
1492         while (p < e) {
1493                 int c;
1494                 for (c = 0; c < 3; c++) {
1495                         p[c]= color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1496                 }
1497                 p += 4;
1498         }
1499 }
1500
1501 static void color_balance(Sequence * seq, ImBuf* ibuf, float mul)
1502 {
1503         if (ibuf->rect_float) {
1504                 color_balance_float_float(seq, ibuf, mul);
1505         } else if(seq->flag & SEQ_MAKE_FLOAT) {
1506                 color_balance_byte_float(seq, ibuf, mul);
1507         } else {
1508                 color_balance_byte_byte(seq, ibuf, mul);
1509         }
1510 }
1511
1512 /*
1513   input preprocessing for SEQ_IMAGE, SEQ_MOVIE and SEQ_SCENE
1514
1515   Do all the things you can't really do afterwards using sequence effects
1516   (read: before rescaling to render resolution has been done)
1517
1518   Order is important!
1519
1520   - Deinterlace
1521   - Crop and transform in image source coordinate space
1522   - Flip X + Flip Y (could be done afterwards, backward compatibility)
1523   - Promote image to float data (affects pipeline operations afterwards)
1524   - Color balance (is most efficient in the byte -> float 
1525         (future: half -> float should also work fine!)
1526         case, if done on load, since we can use lookup tables)
1527   - Premultiply
1528
1529 */
1530
1531 int input_have_to_preprocess(
1532         SeqRenderData UNUSED(context), Sequence * seq, float UNUSED(cfra))
1533 {
1534         float mul;
1535
1536         if (seq->flag & (SEQ_FILTERY|SEQ_USE_CROP|SEQ_USE_TRANSFORM|SEQ_FLIPX|
1537                          SEQ_FLIPY|SEQ_USE_COLOR_BALANCE|SEQ_MAKE_PREMUL)) {
1538                 return TRUE;
1539         }
1540
1541         mul = seq->mul;
1542
1543         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1544                 mul *= seq->blend_opacity / 100.0;
1545         }
1546
1547         if (mul != 1.0) {
1548                 return TRUE;
1549         }
1550
1551         if (seq->sat != 1.0) {
1552                 return TRUE;
1553         }
1554                 
1555         return FALSE;
1556 }
1557
1558 static ImBuf * input_preprocess(
1559         SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf * ibuf)
1560 {
1561         float mul;
1562
1563         if((seq->flag & SEQ_FILTERY) && seq->type != SEQ_MOVIE) {
1564                 IMB_filtery(ibuf);
1565         }
1566
1567         if(seq->flag & (SEQ_USE_CROP|SEQ_USE_TRANSFORM)) {
1568                 StripCrop c= {0};
1569                 StripTransform t= {0};
1570                 int sx,sy,dx,dy;
1571
1572                 if(seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1573                         c = *seq->strip->crop;
1574                 }
1575                 if(seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1576                         t = *seq->strip->transform;
1577                 }
1578
1579                 sx = ibuf->x - c.left - c.right;
1580                 sy = ibuf->y - c.top - c.bottom;
1581                 dx = sx;
1582                 dy = sy;
1583
1584                 if (seq->flag & SEQ_USE_TRANSFORM) {
1585                         dx = context.scene->r.xsch;
1586                         dy = context.scene->r.ysch;
1587                 }
1588
1589                 if (c.top + c.bottom >= ibuf->y || c.left + c.right >= ibuf->x ||
1590                                 t.xofs >= dx || t.yofs >= dy) {
1591                         make_black_ibuf(ibuf);
1592                 } else {
1593                         ImBuf * i = IMB_allocImBuf(dx, dy,32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1594
1595                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1596                         
1597                         IMB_freeImBuf(ibuf);
1598
1599                         ibuf = i;
1600                 }
1601         } 
1602
1603         if(seq->flag & SEQ_FLIPX) {
1604                 IMB_flipx(ibuf);
1605         }
1606         
1607         if(seq->flag & SEQ_FLIPY) {
1608                 IMB_flipy(ibuf);
1609         }
1610
1611         if(seq->sat != 1.0f) {
1612                 /* inline for now, could become an imbuf function */
1613                 int i;
1614                 unsigned char *rct= (unsigned char *)ibuf->rect;
1615                 float *rctf= ibuf->rect_float;
1616                 const float sat= seq->sat;
1617                 float hsv[3];
1618
1619                 if(rct) {
1620                         float rgb[3];
1621                         for (i = ibuf->x * ibuf->y; i > 0; i--, rct+=4) {
1622                                 rgb_byte_to_float(rct, rgb);
1623                                 rgb_to_hsv(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
1624                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rgb, rgb+1, rgb+2);
1625                                 rgb_float_to_byte(rgb, rct);
1626                         }
1627                 }
1628
1629                 if(rctf) {
1630                         for (i = ibuf->x * ibuf->y; i > 0; i--, rctf+=4) {
1631                                 rgb_to_hsv(rctf[0], rctf[1], rctf[2], hsv, hsv+1, hsv+2);
1632                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rctf, rctf+1, rctf+2);
1633                         }
1634                 }
1635         }
1636
1637         mul = seq->mul;
1638
1639         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1640                 mul *= seq->blend_opacity / 100.0;
1641         }
1642
1643         if(seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1644                 color_balance(seq, ibuf, mul);
1645                 mul = 1.0;
1646         }
1647
1648         if(seq->flag & SEQ_MAKE_FLOAT) {
1649                 if (!ibuf->rect_float)
1650                         IMB_float_from_rect_simple(ibuf);
1651
1652                 if (ibuf->rect) {
1653                         imb_freerectImBuf(ibuf);
1654                 }
1655         }
1656
1657         if(mul != 1.0) {
1658                 multibuf(ibuf, mul);
1659         }
1660
1661         if(seq->flag & SEQ_MAKE_PREMUL) {
1662                 if(ibuf->depth == 32 && ibuf->zbuf == 0) {
1663                         IMB_premultiply_alpha(ibuf);
1664                 }
1665         }
1666
1667
1668         if(ibuf->x != context.rectx || ibuf->y != context.recty ) {
1669                 if(context.scene->r.mode & R_OSA) {
1670                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1671                 } else {
1672                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1673                 }
1674         }
1675         return ibuf;
1676 }
1677
1678 static ImBuf * copy_from_ibuf_still(SeqRenderData context, Sequence * seq, 
1679                                     float nr)
1680 {
1681         ImBuf * rval = 0;
1682         ImBuf * ibuf = 0;
1683
1684         if (nr == 0) {
1685                 ibuf = seq_stripelem_cache_get(
1686                         context, seq, seq->start, 
1687                         SEQ_STRIPELEM_IBUF_STARTSTILL);
1688         } else if (nr == seq->len - 1) {
1689                 ibuf = seq_stripelem_cache_get(
1690                         context, seq, seq->start, 
1691                         SEQ_STRIPELEM_IBUF_ENDSTILL);
1692         }
1693
1694         if (ibuf) {
1695                 rval = IMB_dupImBuf(ibuf);
1696                 IMB_freeImBuf(ibuf);
1697         }
1698
1699         return rval;
1700 }
1701
1702 static void copy_to_ibuf_still(SeqRenderData context, Sequence * seq, float nr,
1703                                ImBuf * ibuf)
1704 {
1705         if (nr == 0) {
1706                 seq_stripelem_cache_put(
1707                         context, seq, seq->start, 
1708                         SEQ_STRIPELEM_IBUF_STARTSTILL, IMB_dupImBuf(ibuf));
1709         } 
1710
1711         if (nr == seq->len - 1) {
1712                 seq_stripelem_cache_put(
1713                         context, seq, seq->start, 
1714                         SEQ_STRIPELEM_IBUF_ENDSTILL, IMB_dupImBuf(ibuf));
1715         }
1716 }
1717
1718 /* **********************************************************************
1719    strip rendering functions
1720    ********************************************************************** */
1721
1722 static ImBuf* seq_render_strip_stack( 
1723         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown);
1724
1725 static ImBuf * seq_render_strip(
1726         SeqRenderData context, Sequence * seq, float cfra);
1727
1728
1729 static ImBuf* seq_render_effect_strip_impl(
1730         SeqRenderData context, Sequence *seq, float cfra)
1731 {
1732         float fac, facf;
1733         int early_out;
1734         int i;
1735         struct SeqEffectHandle sh = get_sequence_effect(seq);
1736         FCurve *fcu= NULL;
1737         ImBuf * ibuf[3];
1738         Sequence *input[3];
1739         ImBuf * out = NULL;
1740
1741         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1742
1743         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1744
1745         if (!sh.execute) { /* effect not supported in this version... */
1746                 out = IMB_allocImBuf((short)context.rectx, 
1747                                      (short)context.recty, 32, IB_rect);
1748                 return out;
1749         }
1750
1751         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1752                 sh.get_default_fac(seq, cfra, &fac, &facf);
1753                 
1754                 if ((context.scene->r.mode & R_FIELDS)==0)
1755                         facf= fac;
1756         }
1757         else {
1758                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0);
1759                 if (fcu) {
1760                         fac = facf = evaluate_fcurve(fcu, cfra);
1761                         if( context.scene->r.mode & R_FIELDS ) {
1762                                 facf = evaluate_fcurve(fcu, cfra + 0.5);
1763                         }
1764                 } else {
1765                         fac = facf = seq->effect_fader;
1766                 }
1767         }
1768
1769         early_out = sh.early_out(seq, fac, facf);
1770
1771         switch (early_out) {
1772         case EARLY_NO_INPUT:
1773                 out = sh.execute(context, seq, cfra, fac, facf, 
1774                                  NULL, NULL, NULL);
1775                 break;
1776         case EARLY_DO_EFFECT:
1777                 for(i=0; i<3; i++) {
1778                         if(input[i])
1779                                 ibuf[i] = seq_render_strip(
1780                                         context, input[i], cfra);
1781                 }
1782
1783                 if (ibuf[0] && ibuf[1]) {
1784                         out = sh.execute(context, seq, cfra, fac, facf,  
1785                                          ibuf[0], ibuf[1], ibuf[2]);
1786                 }
1787                 break;
1788         case EARLY_USE_INPUT_1:
1789                 if (input[0]) {
1790                         ibuf[0] = seq_render_strip(context, input[0], cfra);
1791                 }
1792                 if (ibuf[0]) {
1793                         if (input_have_to_preprocess(context, seq, cfra)) {
1794                                 out = IMB_dupImBuf(ibuf[0]);
1795                         } else {
1796                                 out = ibuf[0];
1797                                 IMB_refImBuf(out);
1798                         }
1799                 }
1800                 break;
1801         case EARLY_USE_INPUT_2:
1802                 if (input[1]) {
1803                         ibuf[1] = seq_render_strip(context, input[1], cfra);
1804                 }
1805                 if (ibuf[1]) {
1806                         if (input_have_to_preprocess(context, seq, cfra)) {
1807                                 out = IMB_dupImBuf(ibuf[1]);
1808                         } else {
1809                                 out = ibuf[1];
1810                                 IMB_refImBuf(out);
1811                         }
1812                 }
1813                 break;
1814         }
1815
1816         for (i = 0; i < 3; i++) {
1817                 IMB_freeImBuf(ibuf[i]);
1818         }
1819
1820         if (out == NULL) {
1821                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
1822         }
1823
1824         return out;
1825 }
1826
1827
1828 static ImBuf * seq_render_scene_strip_impl(
1829         SeqRenderData context, Sequence * seq, float nr)
1830 {
1831         ImBuf * ibuf = 0;
1832         float frame= seq->sfra + nr + seq->anim_startofs;
1833         float oldcfra;
1834         Object *oldcamera;
1835         ListBase oldmarkers;
1836         
1837         /* Old info:
1838            Hack! This function can be called from do_render_seq(), in that case
1839            the seq->scene can already have a Render initialized with same name,
1840            so we have to use a default name. (compositor uses scene name to
1841            find render).
1842            However, when called from within the UI (image preview in sequencer)
1843            we do want to use scene Render, that way the render result is defined
1844            for display in render/imagewindow
1845            
1846            Hmm, don't see, why we can't do that all the time,
1847            and since G.rendering is uhm, gone... (Peter)
1848         */
1849
1850         /* New info:
1851            Using the same name for the renders works just fine as the do_render_seq()
1852            render is not used while the scene strips are rendered.
1853            
1854            However rendering from UI (through sequencer_preview_area_draw) can crash in
1855            very many cases since other renders (material preview, an actual render etc.)
1856            can be started while this sequence preview render is running. The only proper
1857            solution is to make the sequencer preview render a proper job, which can be
1858            stopped when needed. This would also give a nice progress bar for the preview
1859            space so that users know there's something happening.
1860
1861            As a result the active scene now only uses OpenGL rendering for the sequencer
1862            preview. This is far from nice, but is the only way to prevent crashes at this
1863            time. 
1864
1865            -jahka
1866         */
1867
1868         int rendering = G.rendering;
1869         int doseq;
1870         int doseq_gl= G.rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
1871         int have_seq= FALSE;
1872         Scene *sce= seq->scene; /* dont refer to seq->scene above this point!, it can be NULL */
1873         int sce_valid= FALSE;
1874
1875         if(sce) {
1876                 have_seq= (sce->r.scemode & R_DOSEQ) && sce->ed && sce->ed->seqbase.first;
1877                 sce_valid= (sce->camera || have_seq);
1878         }
1879
1880         if (!sce_valid)
1881                 return NULL;
1882
1883         oldcfra= seq->scene->r.cfra;
1884         oldcamera= seq->scene->camera;
1885
1886         /* prevent eternal loop */
1887         doseq= context.scene->r.scemode & R_DOSEQ;
1888         context.scene->r.scemode &= ~R_DOSEQ;
1889         
1890         seq->scene->r.cfra= frame;
1891         if(seq->scene_camera)   
1892                 seq->scene->camera= seq->scene_camera;
1893         else    
1894                 scene_camera_switch_update(seq->scene);
1895         
1896 #ifdef DURIAN_CAMERA_SWITCH
1897         /* stooping to new low's in hackyness :( */
1898         oldmarkers= seq->scene->markers;
1899         seq->scene->markers.first= seq->scene->markers.last= NULL;
1900 #endif
1901         
1902         if(sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (seq->scene == context.scene || have_seq==0) && seq->scene->camera) {
1903                 /* for old scened this can be uninitialized, should probably be added to do_versions at some point if the functionality stays */
1904                 if(context.scene->r.seq_prev_type==0)
1905                         context.scene->r.seq_prev_type = 3 /* ==OB_SOLID */; 
1906
1907                 /* opengl offscreen render */
1908                 scene_update_for_newframe(context.bmain, seq->scene, seq->scene->lay);
1909                 ibuf= sequencer_view3d_cb(seq->scene, context.rectx, context.recty, IB_rect, context.scene->r.seq_prev_type);
1910         }
1911         else {
1912                 Render *re = RE_GetRender(sce->id.name);
1913                 RenderResult rres;
1914
1915                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
1916                 if(rendering || context.scene != sce) {
1917                         if(re==NULL)
1918                                 re= RE_NewRender(sce->id.name);
1919                         
1920                         RE_BlenderFrame(re, context.bmain, sce, NULL, sce->lay, frame, FALSE);
1921
1922                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
1923                         G.rendering = rendering;
1924                 }
1925                 
1926                 RE_AcquireResultImage(re, &rres);
1927                 
1928                 if(rres.rectf) {
1929                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
1930                         memcpy(ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
1931                         if(rres.rectz) {
1932                                 addzbuffloatImBuf(ibuf);
1933                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
1934                         }
1935
1936                         /* float buffers in the sequencer are not linear */
1937                         ibuf->profile= IB_PROFILE_LINEAR_RGB;
1938                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
1939                 }
1940                 else if (rres.rect32) {
1941                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
1942                         memcpy(ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
1943                 }
1944                 
1945                 RE_ReleaseResultImage(re);
1946                 
1947                 // BIF_end_render_callbacks();
1948         }
1949         
1950         /* restore */
1951         context.scene->r.scemode |= doseq;
1952         
1953         seq->scene->r.cfra = oldcfra;
1954         seq->scene->camera= oldcamera;
1955         if(frame != oldcfra)
1956                 scene_update_for_newframe(context.bmain, seq->scene, seq->scene->lay);
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         Editing *ed= seq_give_editing(scene, FALSE);
3299         if(ed==NULL) return;
3300
3301         ed->act_seq= seq;
3302 }
3303
3304 int seq_active_pair_get(Scene *scene, Sequence **seq_act, Sequence **seq_other)
3305 {