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