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