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