Merging r41176 through r41192 from trunk into soc-2011-tomato
[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         /* unsupported feature only confuses other s/w */
1331         if(ibuf->depth==32)
1332                 ibuf->depth= 24;
1333
1334         BLI_make_existing_file(name);
1335         
1336         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1337         if (ok == 0) {
1338                 perror(name);
1339         }
1340
1341         IMB_freeImBuf(ibuf);
1342 }
1343
1344 void seq_proxy_rebuild(struct Main * bmain, Scene *scene, Sequence * seq,
1345                        short *stop, short *do_update, float *progress)
1346 {
1347         SeqRenderData context;
1348         int cfra;
1349         int tc_flags;
1350         int size_flags;
1351         int quality;
1352
1353         if (!seq->strip || !seq->strip->proxy) {
1354                 return;
1355         }
1356
1357         if (!(seq->flag & SEQ_USE_PROXY)) {
1358                 return;
1359         }
1360
1361         tc_flags   = seq->strip->proxy->build_tc_flags;
1362         size_flags = seq->strip->proxy->build_size_flags;
1363         quality    = seq->strip->proxy->quality;
1364
1365         if (seq->type == SEQ_MOVIE) {
1366                 seq_open_anim_file(seq);
1367
1368                 if (seq->anim) {
1369                         IMB_anim_index_rebuild(
1370                                 seq->anim, tc_flags, size_flags, quality,
1371                                 stop, do_update, progress);
1372                 }
1373                 return;
1374         }
1375
1376         if (!(seq->flag & SEQ_USE_PROXY)) {
1377                 return;
1378         }
1379
1380         /* that's why it is called custom... */
1381         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1382                 return;
1383         }
1384
1385         /* fail safe code */
1386
1387         context = seq_new_render_data(
1388                 bmain, scene, 
1389                 (scene->r.size * (float) scene->r.xsch) / 100.0f + 0.5f, 
1390                 (scene->r.size * (float) scene->r.ysch) / 100.0f + 0.5f, 
1391                 100);
1392
1393         for (cfra = seq->startdisp + seq->startstill; 
1394              cfra < seq->enddisp - seq->endstill; cfra++) {
1395                 if (size_flags & IMB_PROXY_25) {
1396                         seq_proxy_build_frame(context, seq, cfra, 25);
1397                 }
1398                 if (size_flags & IMB_PROXY_50) {
1399                         seq_proxy_build_frame(context, seq, cfra, 50);
1400                 }
1401                 if (size_flags & IMB_PROXY_75) {
1402                         seq_proxy_build_frame(context, seq, cfra, 75);
1403                 }
1404                 if (size_flags & IMB_PROXY_100) {
1405                         seq_proxy_build_frame(context, seq, cfra, 100);
1406                 }
1407
1408                 *progress= (float)cfra/(seq->enddisp - seq->endstill 
1409                                         - seq->startdisp + seq->startstill);
1410                 *do_update= 1;
1411
1412                 if(*stop || G.afbreek)
1413                         break;
1414         }
1415 }
1416
1417
1418 /* **********************************************************************
1419    color balance 
1420    ********************************************************************** */
1421
1422 static StripColorBalance calc_cb(StripColorBalance * cb_)
1423 {
1424         StripColorBalance cb = *cb_;
1425         int c;
1426
1427         for (c = 0; c < 3; c++) {
1428                 cb.lift[c] = 2.0f - cb.lift[c];
1429         }
1430
1431         if(cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1432                 for (c = 0; c < 3; c++) {
1433                         /* tweak to give more subtle results
1434                          * values above 1.0 are scaled */
1435                         if(cb.lift[c] > 1.0f)
1436                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0;
1437
1438                         cb.lift[c] = 2.0f - cb.lift[c];
1439                 }
1440         }
1441
1442         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1443                 for (c = 0; c < 3; c++) {
1444                         if (cb.gain[c] != 0.0f) {
1445                                 cb.gain[c] = 1.0f / cb.gain[c];
1446                         } else {
1447                                 cb.gain[c] = 1000000; /* should be enough :) */
1448                         }
1449                 }
1450         }
1451
1452         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1453                 for (c = 0; c < 3; c++) {
1454                         if (cb.gamma[c] != 0.0f) {
1455                                 cb.gamma[c] = 1.0f/cb.gamma[c];
1456                         } else {
1457                                 cb.gamma[c] = 1000000; /* should be enough :) */
1458                         }
1459                 }
1460         }
1461
1462         return cb;
1463 }
1464
1465 /* note: lift is actually 2-lift */
1466 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1467 {
1468         float x= (((in - 1.0f) * lift) + 1.0f) * gain;
1469
1470         /* prevent NaN */
1471         if (x < 0.f) x = 0.f;
1472
1473         return powf(x, gamma) * mul;
1474 }
1475
1476 static void make_cb_table_byte(float lift, float gain, float gamma,
1477                                    unsigned char * table, float mul)
1478 {
1479         int y;
1480
1481         for (y = 0; y < 256; y++) {
1482                 float v= color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1483                 CLAMP(v, 0.0f, 1.0f);
1484                 table[y] = v * 255;
1485         }
1486 }
1487
1488 static void make_cb_table_float(float lift, float gain, float gamma,
1489                                 float * table, float mul)
1490 {
1491         int y;
1492
1493         for (y = 0; y < 256; y++) {
1494                 float v= color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
1495                 table[y] = v;
1496         }
1497 }
1498
1499 static void color_balance_byte_byte(Sequence * seq, ImBuf* ibuf, float mul)
1500 {
1501         unsigned char cb_tab[3][256];
1502         int c;
1503         unsigned char * p = (unsigned char*) ibuf->rect;
1504         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1505
1506         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1507
1508         for (c = 0; c < 3; c++) {
1509                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c],
1510                                    cb_tab[c], mul);
1511         }
1512
1513         while (p < e) {
1514                 p[0] = cb_tab[0][p[0]];
1515                 p[1] = cb_tab[1][p[1]];
1516                 p[2] = cb_tab[2][p[2]];
1517                 
1518                 p += 4;
1519         }
1520 }
1521
1522 static void color_balance_byte_float(Sequence * seq, ImBuf* ibuf, float mul)
1523 {
1524         float cb_tab[4][256];
1525         int c,i;
1526         unsigned char * p = (unsigned char*) ibuf->rect;
1527         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1528         float * o;
1529         StripColorBalance cb;
1530
1531         imb_addrectfloatImBuf(ibuf);
1532
1533         o = ibuf->rect_float;
1534
1535         cb = calc_cb(seq->strip->color_balance);
1536
1537         for (c = 0; c < 3; c++) {
1538                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1539         }
1540
1541         for (i = 0; i < 256; i++) {
1542                 cb_tab[3][i] = ((float)i)*(1.0f/255.0f);
1543         }
1544
1545         while (p < e) {
1546                 o[0] = cb_tab[0][p[0]];
1547                 o[1] = cb_tab[1][p[1]];
1548                 o[2] = cb_tab[2][p[2]];
1549                 o[3] = cb_tab[3][p[3]];
1550
1551                 p += 4; o += 4;
1552         }
1553 }
1554
1555 static void color_balance_float_float(Sequence * seq, ImBuf* ibuf, float mul)
1556 {
1557         float * p = ibuf->rect_float;
1558         float * e = ibuf->rect_float + ibuf->x * 4* ibuf->y;
1559         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1560
1561         while (p < e) {
1562                 int c;
1563                 for (c = 0; c < 3; c++) {
1564                         p[c]= color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1565                 }
1566                 p += 4;
1567         }
1568 }
1569
1570 static void color_balance(Sequence * seq, ImBuf* ibuf, float mul)
1571 {
1572         if (ibuf->rect_float) {
1573                 color_balance_float_float(seq, ibuf, mul);
1574         } else if(seq->flag & SEQ_MAKE_FLOAT) {
1575                 color_balance_byte_float(seq, ibuf, mul);
1576         } else {
1577                 color_balance_byte_byte(seq, ibuf, mul);
1578         }
1579 }
1580
1581 /*
1582   input preprocessing for SEQ_IMAGE, SEQ_MOVIE and SEQ_SCENE
1583
1584   Do all the things you can't really do afterwards using sequence effects
1585   (read: before rescaling to render resolution has been done)
1586
1587   Order is important!
1588
1589   - Deinterlace
1590   - Crop and transform in image source coordinate space
1591   - Flip X + Flip Y (could be done afterwards, backward compatibility)
1592   - Promote image to float data (affects pipeline operations afterwards)
1593   - Color balance (is most efficient in the byte -> float 
1594         (future: half -> float should also work fine!)
1595         case, if done on load, since we can use lookup tables)
1596   - Premultiply
1597
1598 */
1599
1600 int input_have_to_preprocess(
1601         SeqRenderData UNUSED(context), Sequence * seq, float UNUSED(cfra))
1602 {
1603         float mul;
1604
1605         if (seq->flag & (SEQ_FILTERY|SEQ_USE_CROP|SEQ_USE_TRANSFORM|SEQ_FLIPX|
1606                          SEQ_FLIPY|SEQ_USE_COLOR_BALANCE|SEQ_MAKE_PREMUL)) {
1607                 return TRUE;
1608         }
1609
1610         mul = seq->mul;
1611
1612         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1613                 mul *= seq->blend_opacity / 100.0f;
1614         }
1615
1616         if (mul != 1.0f) {
1617                 return TRUE;
1618         }
1619
1620         if (seq->sat != 1.0f) {
1621                 return TRUE;
1622         }
1623                 
1624         return FALSE;
1625 }
1626
1627 static ImBuf * input_preprocess(
1628         SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf * ibuf)
1629 {
1630         float mul;
1631
1632         ibuf = IMB_makeSingleUser(ibuf);
1633
1634         if((seq->flag & SEQ_FILTERY) && seq->type != SEQ_MOVIE) {
1635                 IMB_filtery(ibuf);
1636         }
1637
1638         if(seq->flag & (SEQ_USE_CROP|SEQ_USE_TRANSFORM)) {
1639                 StripCrop c= {0};
1640                 StripTransform t= {0};
1641                 int sx,sy,dx,dy;
1642
1643                 if(seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1644                         c = *seq->strip->crop;
1645                 }
1646                 if(seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1647                         t = *seq->strip->transform;
1648                 }
1649
1650                 sx = ibuf->x - c.left - c.right;
1651                 sy = ibuf->y - c.top - c.bottom;
1652                 dx = sx;
1653                 dy = sy;
1654
1655                 if (seq->flag & SEQ_USE_TRANSFORM) {
1656                         dx = context.scene->r.xsch;
1657                         dy = context.scene->r.ysch;
1658                 }
1659
1660                 if (c.top + c.bottom >= ibuf->y || c.left + c.right >= ibuf->x ||
1661                                 t.xofs >= dx || t.yofs >= dy) {
1662                         make_black_ibuf(ibuf);
1663                 } else {
1664                         ImBuf * i = IMB_allocImBuf(dx, dy,32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1665
1666                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1667                         
1668                         IMB_freeImBuf(ibuf);
1669
1670                         ibuf = i;
1671                 }
1672         } 
1673
1674         if(seq->flag & SEQ_FLIPX) {
1675                 IMB_flipx(ibuf);
1676         }
1677         
1678         if(seq->flag & SEQ_FLIPY) {
1679                 IMB_flipy(ibuf);
1680         }
1681
1682         if(seq->sat != 1.0f) {
1683                 /* inline for now, could become an imbuf function */
1684                 int i;
1685                 unsigned char *rct= (unsigned char *)ibuf->rect;
1686                 float *rctf= ibuf->rect_float;
1687                 const float sat= seq->sat;
1688                 float hsv[3];
1689
1690                 if(rct) {
1691                         float rgb[3];
1692                         for (i = ibuf->x * ibuf->y; i > 0; i--, rct+=4) {
1693                                 rgb_byte_to_float(rct, rgb);
1694                                 rgb_to_hsv(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
1695                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rgb, rgb+1, rgb+2);
1696                                 rgb_float_to_byte(rgb, rct);
1697                         }
1698                 }
1699
1700                 if(rctf) {
1701                         for (i = ibuf->x * ibuf->y; i > 0; i--, rctf+=4) {
1702                                 rgb_to_hsv(rctf[0], rctf[1], rctf[2], hsv, hsv+1, hsv+2);
1703                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rctf, rctf+1, rctf+2);
1704                         }
1705                 }
1706         }
1707
1708         mul = seq->mul;
1709
1710         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1711                 mul *= seq->blend_opacity / 100.0f;
1712         }
1713
1714         if(seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1715                 color_balance(seq, ibuf, mul);
1716                 mul = 1.0;
1717         }
1718
1719         if(seq->flag & SEQ_MAKE_FLOAT) {
1720                 if (!ibuf->rect_float)
1721                         IMB_float_from_rect_simple(ibuf);
1722
1723                 if (ibuf->rect) {
1724                         imb_freerectImBuf(ibuf);
1725                 }
1726         }
1727
1728         if(mul != 1.0f) {
1729                 multibuf(ibuf, mul);
1730         }
1731
1732         if(seq->flag & SEQ_MAKE_PREMUL) {
1733                 if(ibuf->depth == 32 && ibuf->zbuf == NULL) {
1734                         IMB_premultiply_alpha(ibuf);
1735                 }
1736         }
1737
1738
1739         if(ibuf->x != context.rectx || ibuf->y != context.recty ) {
1740                 if(context.scene->r.mode & R_OSA) {
1741                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1742                 } else {
1743                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1744                 }
1745         }
1746         return ibuf;
1747 }
1748
1749 static ImBuf * copy_from_ibuf_still(SeqRenderData context, Sequence * seq, 
1750                                     float nr)
1751 {
1752         ImBuf * rval = NULL;
1753         ImBuf * ibuf = NULL;
1754
1755         if (nr == 0) {
1756                 ibuf = seq_stripelem_cache_get(
1757                         context, seq, seq->start, 
1758                         SEQ_STRIPELEM_IBUF_STARTSTILL);
1759         } else if (nr == seq->len - 1) {
1760                 ibuf = seq_stripelem_cache_get(
1761                         context, seq, seq->start, 
1762                         SEQ_STRIPELEM_IBUF_ENDSTILL);
1763         }
1764
1765         if (ibuf) {
1766                 rval = IMB_dupImBuf(ibuf);
1767                 IMB_freeImBuf(ibuf);
1768         }
1769
1770         return rval;
1771 }
1772
1773 static void copy_to_ibuf_still(SeqRenderData context, Sequence * seq, float nr,
1774                                ImBuf * ibuf)
1775 {
1776         if (nr == 0 || nr == seq->len - 1) {
1777                 /* we have to store a copy, since the passed ibuf
1778                    could be preprocessed afterwards (thereby silently
1779                    changing the cached image... */
1780                 ibuf = IMB_dupImBuf(ibuf);
1781
1782                 if (nr == 0) {
1783                         seq_stripelem_cache_put(
1784                                 context, seq, seq->start, 
1785                                 SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
1786                 } 
1787
1788                 if (nr == seq->len - 1) {
1789                         seq_stripelem_cache_put(
1790                                 context, seq, seq->start, 
1791                                 SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
1792                 }
1793
1794                 IMB_freeImBuf(ibuf);
1795         }
1796 }
1797
1798 /* **********************************************************************
1799    strip rendering functions
1800    ********************************************************************** */
1801
1802 static ImBuf* seq_render_strip_stack( 
1803         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown);
1804
1805 static ImBuf * seq_render_strip(
1806         SeqRenderData context, Sequence * seq, float cfra);
1807
1808
1809 static ImBuf* seq_render_effect_strip_impl(
1810         SeqRenderData context, Sequence *seq, float cfra)
1811 {
1812         float fac, facf;
1813         int early_out;
1814         int i;
1815         struct SeqEffectHandle sh = get_sequence_effect(seq);
1816         FCurve *fcu= NULL;
1817         ImBuf * ibuf[3];
1818         Sequence *input[3];
1819         ImBuf * out = NULL;
1820
1821         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1822
1823         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1824
1825         if (!sh.execute) { /* effect not supported in this version... */
1826                 out = IMB_allocImBuf((short)context.rectx, 
1827                                      (short)context.recty, 32, IB_rect);
1828                 return out;
1829         }
1830
1831         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1832                 sh.get_default_fac(seq, cfra, &fac, &facf);
1833                 
1834                 if ((context.scene->r.mode & R_FIELDS)==0)
1835                         facf= fac;
1836         }
1837         else {
1838                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0, NULL);
1839                 if (fcu) {
1840                         fac = facf = evaluate_fcurve(fcu, cfra);
1841                         if( context.scene->r.mode & R_FIELDS ) {
1842                                 facf = evaluate_fcurve(fcu, cfra + 0.5f);
1843                         }
1844                 } else {
1845                         fac = facf = seq->effect_fader;
1846                 }
1847         }
1848
1849         early_out = sh.early_out(seq, fac, facf);
1850
1851         switch (early_out) {
1852         case EARLY_NO_INPUT:
1853                 out = sh.execute(context, seq, cfra, fac, facf, 
1854                                  NULL, NULL, NULL);
1855                 break;
1856         case EARLY_DO_EFFECT:
1857                 for(i=0; i<3; i++) {
1858                         if(input[i])
1859                                 ibuf[i] = seq_render_strip(
1860                                         context, input[i], cfra);
1861                 }
1862
1863                 if (ibuf[0] && ibuf[1]) {
1864                         out = sh.execute(context, seq, cfra, fac, facf,  
1865                                          ibuf[0], ibuf[1], ibuf[2]);
1866                 }
1867                 break;
1868         case EARLY_USE_INPUT_1:
1869                 if (input[0]) {
1870                         ibuf[0] = seq_render_strip(context, input[0], cfra);
1871                 }
1872                 if (ibuf[0]) {
1873                         if (input_have_to_preprocess(context, seq, cfra)) {
1874                                 out = IMB_dupImBuf(ibuf[0]);
1875                         } else {
1876                                 out = ibuf[0];
1877                                 IMB_refImBuf(out);
1878                         }
1879                 }
1880                 break;
1881         case EARLY_USE_INPUT_2:
1882                 if (input[1]) {
1883                         ibuf[1] = seq_render_strip(context, input[1], cfra);
1884                 }
1885                 if (ibuf[1]) {
1886                         if (input_have_to_preprocess(context, seq, cfra)) {
1887                                 out = IMB_dupImBuf(ibuf[1]);
1888                         } else {
1889                                 out = ibuf[1];
1890                                 IMB_refImBuf(out);
1891                         }
1892                 }
1893                 break;
1894         }
1895
1896         for (i = 0; i < 3; i++) {
1897                 IMB_freeImBuf(ibuf[i]);
1898         }
1899
1900         if (out == NULL) {
1901                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
1902         }
1903
1904         return out;
1905 }
1906
1907
1908 static ImBuf * seq_render_scene_strip_impl(
1909         SeqRenderData context, Sequence * seq, float nr)
1910 {
1911         ImBuf * ibuf = NULL;
1912         float frame= seq->sfra + nr + seq->anim_startofs;
1913         float oldcfra;
1914         Object *camera;
1915         ListBase oldmarkers;
1916         
1917         /* Old info:
1918            Hack! This function can be called from do_render_seq(), in that case
1919            the seq->scene can already have a Render initialized with same name,
1920            so we have to use a default name. (compositor uses scene name to
1921            find render).
1922            However, when called from within the UI (image preview in sequencer)
1923            we do want to use scene Render, that way the render result is defined
1924            for display in render/imagewindow
1925            
1926            Hmm, don't see, why we can't do that all the time,
1927            and since G.rendering is uhm, gone... (Peter)
1928         */
1929
1930         /* New info:
1931            Using the same name for the renders works just fine as the do_render_seq()
1932            render is not used while the scene strips are rendered.
1933            
1934            However rendering from UI (through sequencer_preview_area_draw) can crash in
1935            very many cases since other renders (material preview, an actual render etc.)
1936            can be started while this sequence preview render is running. The only proper
1937            solution is to make the sequencer preview render a proper job, which can be
1938            stopped when needed. This would also give a nice progress bar for the preview
1939            space so that users know there's something happening.
1940
1941            As a result the active scene now only uses OpenGL rendering for the sequencer
1942            preview. This is far from nice, but is the only way to prevent crashes at this
1943            time. 
1944
1945            -jahka
1946         */
1947
1948         int rendering = G.rendering;
1949         int doseq;
1950         int doseq_gl= G.rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
1951         int have_seq= FALSE;
1952         Scene *scene;
1953
1954         /* dont refer to seq->scene above this point!, it can be NULL */
1955         if(seq->scene == NULL) {
1956                 return NULL;
1957         }
1958
1959         scene= seq->scene;
1960
1961         have_seq= (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first;
1962
1963         oldcfra= scene->r.cfra; 
1964         scene->r.cfra= frame;
1965
1966         if(seq->scene_camera)   
1967                 camera= seq->scene_camera;
1968         else {  
1969                 scene_camera_switch_update(scene);
1970                 camera= scene->camera;
1971         }
1972
1973         if(have_seq==FALSE && camera==NULL) {
1974                 scene->r.cfra= oldcfra;
1975                 return NULL;
1976         }
1977
1978         /* prevent eternal loop */
1979         doseq= context.scene->r.scemode & R_DOSEQ;
1980         context.scene->r.scemode &= ~R_DOSEQ;
1981         
1982 #ifdef DURIAN_CAMERA_SWITCH
1983         /* stooping to new low's in hackyness :( */
1984         oldmarkers= scene->markers;
1985         scene->markers.first= scene->markers.last= NULL;
1986 #endif
1987         
1988         if(sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq==0) && camera) {
1989                 char err_out[256]= "unknown";
1990                 /* for old scened this can be uninitialized, should probably be added to do_versions at some point if the functionality stays */
1991                 if(context.scene->r.seq_prev_type==0)
1992                         context.scene->r.seq_prev_type = 3 /* ==OB_SOLID */; 
1993
1994                 /* opengl offscreen render */
1995                 scene_update_for_newframe(context.bmain, scene, scene->lay);
1996                 ibuf= sequencer_view3d_cb(scene, camera, context.rectx, context.recty, IB_rect, context.scene->r.seq_prev_type, err_out);
1997                 if(ibuf == NULL) {
1998                         fprintf(stderr, "seq_render_scene_strip_impl failed to get opengl buffer: %s\n", err_out);
1999                 }
2000         }
2001         else {
2002                 Render *re = RE_GetRender(scene->id.name);
2003                 RenderResult rres;
2004
2005                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
2006                 if(rendering || context.scene != scene) {
2007                         if(re==NULL)
2008                                 re= RE_NewRender(scene->id.name);
2009                         
2010                         RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE);
2011
2012                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
2013                         G.rendering = rendering;
2014                 }
2015                 
2016                 RE_AcquireResultImage(re, &rres);
2017                 
2018                 if(rres.rectf) {
2019                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
2020                         memcpy(ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
2021                         if(rres.rectz) {
2022                                 addzbuffloatImBuf(ibuf);
2023                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
2024                         }
2025
2026                         /* float buffers in the sequencer are not linear */
2027                         ibuf->profile= IB_PROFILE_LINEAR_RGB;
2028                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
2029                 }
2030                 else if (rres.rect32) {
2031                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
2032                         memcpy(ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
2033                 }
2034                 
2035                 RE_ReleaseResultImage(re);
2036                 
2037                 // BIF_end_render_callbacks();
2038         }
2039         
2040         /* restore */
2041         context.scene->r.scemode |= doseq;
2042         
2043         scene->r.cfra = oldcfra;
2044
2045         if(frame != oldcfra)
2046                 scene_update_for_newframe(context.bmain, scene, scene->lay);
2047         
2048 #ifdef DURIAN_CAMERA_SWITCH
2049         /* stooping to new low's in hackyness :( */
2050         scene->markers= oldmarkers;
2051 #endif
2052
2053         return ibuf;
2054 }
2055
2056 static ImBuf * seq_render_strip(SeqRenderData context, Sequence * seq, float cfra)
2057 {
2058         ImBuf * ibuf = NULL;
2059         char name[FILE_MAXDIR+FILE_MAXFILE];
2060         int use_preprocess = input_have_to_preprocess(context, seq, cfra);
2061         float nr = give_stripelem_index(seq, cfra);
2062         /* all effects are handled similarly with the exception of speed effect */
2063         int type = (seq->type & SEQ_EFFECT && seq->type != SEQ_SPEED) ? SEQ_EFFECT : seq->type;
2064
2065         ibuf = seq_stripelem_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF);
2066
2067         /* currently, we cache preprocessed images in SEQ_STRIPELEM_IBUF,
2068            but not(!) on SEQ_STRIPELEM_IBUF_ENDSTILL and ..._STARTSTILL */
2069         if (ibuf)
2070                 use_preprocess = FALSE;
2071
2072         if (ibuf == NULL)
2073                 ibuf = copy_from_ibuf_still(context, seq, nr);
2074         
2075         if (ibuf == NULL)
2076                 ibuf = seq_proxy_fetch(context, seq, cfra);
2077
2078         if(ibuf == NULL) switch(type) {
2079                 case SEQ_META:
2080                 {
2081                         ImBuf * meta_ibuf = NULL;
2082
2083                         if(seq->seqbase.first)
2084                                 meta_ibuf = seq_render_strip_stack(
2085                                         context, &seq->seqbase,
2086                                         seq->start + nr, 0);
2087
2088                         if(meta_ibuf) {
2089                                 ibuf = meta_ibuf;
2090                                 if(ibuf && use_preprocess) {
2091                                         struct ImBuf * i = IMB_dupImBuf(ibuf);
2092
2093                                         IMB_freeImBuf(ibuf);
2094
2095                                         ibuf = i;
2096                                 }
2097                         }
2098                         break;
2099                 }
2100                 case SEQ_SPEED:
2101                 {
2102                         ImBuf * child_ibuf = NULL;
2103
2104                         float f_cfra;
2105                         SpeedControlVars * s = (SpeedControlVars *)seq->effectdata;
2106
2107                         sequence_effect_speed_rebuild_map(context.scene,seq, 0);
2108
2109                         /* weeek! */
2110                         f_cfra = seq->start + s->frameMap[(int) nr];
2111
2112                         child_ibuf = seq_render_strip(context,seq->seq1,f_cfra);
2113
2114                         if (child_ibuf) {
2115                                 ibuf = child_ibuf;
2116                                 if(ibuf && use_preprocess) {
2117                                         struct ImBuf * i = IMB_dupImBuf(ibuf);
2118
2119                                         IMB_freeImBuf(ibuf);
2120
2121                                         ibuf = i;
2122                                 }
2123                         }
2124                         break;
2125                 }
2126                 case SEQ_EFFECT:
2127                 {
2128                         ibuf = seq_render_effect_strip_impl(
2129                                 context, seq, seq->start + nr);
2130                         break;
2131                 }
2132                 case SEQ_IMAGE:
2133                 {
2134                         StripElem * s_elem = give_stripelem(seq, cfra);
2135
2136                         if (s_elem) {
2137                                 BLI_join_dirfile(name, sizeof(name), seq->strip->dir, s_elem->name);
2138                                 BLI_path_abs(name, G.main->name);
2139                         }
2140
2141                         if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect))) {
2142                                 /* we don't need both (speed reasons)! */
2143                                 if (ibuf->rect_float && ibuf->rect)
2144                                         imb_freerectImBuf(ibuf);
2145
2146                                 /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2147                                 if(ibuf->profile == IB_PROFILE_LINEAR_RGB)
2148                                         IMB_convert_profile(ibuf, IB_PROFILE_NONE);
2149
2150                                 copy_to_ibuf_still(context, seq, nr, ibuf);
2151
2152                                 s_elem->orig_width  = ibuf->x;
2153                                 s_elem->orig_height = ibuf->y;
2154                         }
2155                         break;
2156                 }
2157                 case SEQ_MOVIE:
2158                 {
2159                         seq_open_anim_file(seq);
2160
2161                         if(seq->anim) {
2162                                 IMB_anim_set_preseek(seq->anim,
2163                                                      seq->anim_preseek);
2164
2165                                 ibuf = IMB_anim_absolute(
2166                                         seq->anim, nr + seq->anim_startofs, 
2167                                         seq->strip->proxy ? 
2168                                         seq->strip->proxy->tc
2169                                         : IMB_TC_RECORD_RUN, 
2170                                         seq_rendersize_to_proxysize(
2171                                                 context.preview_render_size));
2172
2173                                 /* we don't need both (speed reasons)! */
2174                                 if (ibuf && ibuf->rect_float && ibuf->rect)
2175                                         imb_freerectImBuf(ibuf);
2176                                 if (ibuf) {
2177                                         seq->strip->stripdata->orig_width = ibuf->x;
2178                                         seq->strip->stripdata->orig_height = ibuf->y;
2179                                 }
2180                         }
2181                         copy_to_ibuf_still(context, seq, nr, ibuf);
2182                         break;
2183                 }
2184                 case SEQ_SCENE:
2185                 {       // scene can be NULL after deletions
2186                         ibuf = seq_render_scene_strip_impl(context, seq, nr);
2187
2188                         /* Scene strips update all animation, so we need to restore original state.*/
2189                         BKE_animsys_evaluate_all_animation(context.bmain, context.scene, cfra);
2190
2191                         copy_to_ibuf_still(context, seq, nr, ibuf);
2192                         break;
2193                 }
2194         }
2195
2196         if (ibuf == NULL)
2197                 ibuf = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
2198
2199         if (ibuf->x != context.rectx || ibuf->y != context.recty)
2200                 use_preprocess = TRUE;
2201
2202         if (use_preprocess)
2203                 ibuf = input_preprocess(context, seq, cfra, ibuf);
2204
2205         seq_stripelem_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf);
2206
2207         return ibuf;
2208 }
2209
2210 /* **********************************************************************
2211    strip stack rendering functions
2212    ********************************************************************** */
2213
2214 static int seq_must_swap_input_in_blend_mode(Sequence * seq)
2215 {
2216         int swap_input = FALSE;
2217
2218         /* bad hack, to fix crazy input ordering of 
2219            those two effects */
2220
2221         if (ELEM3(seq->blend_mode, SEQ_ALPHAOVER, SEQ_ALPHAUNDER, SEQ_OVERDROP)) {
2222                 swap_input = TRUE;
2223         }
2224         
2225         return swap_input;
2226 }
2227
2228 static int seq_get_early_out_for_blend_mode(Sequence * seq)
2229 {
2230         struct SeqEffectHandle sh = get_sequence_blend(seq);
2231         float facf = seq->blend_opacity / 100.0f;
2232         int early_out = sh.early_out(seq, facf, facf);
2233         
2234         if (ELEM(early_out, EARLY_DO_EFFECT, EARLY_NO_INPUT)) {
2235                 return early_out;
2236         }
2237
2238         if (seq_must_swap_input_in_blend_mode(seq)) {
2239                 if (early_out == EARLY_USE_INPUT_2) {
2240                         return EARLY_USE_INPUT_1;
2241                 } else if (early_out == EARLY_USE_INPUT_1) {
2242                         return EARLY_USE_INPUT_2;
2243                 }
2244         }
2245         return early_out;
2246 }
2247
2248 static ImBuf* seq_render_strip_stack(
2249         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown)
2250 {
2251         Sequence* seq_arr[MAXSEQ+1];
2252         int count;
2253         int i;
2254         ImBuf* out = NULL;
2255
2256         count = get_shown_sequences(seqbasep, cfra, chanshown, (Sequence **)&seq_arr);
2257
2258         if (count == 0) {
2259                 return NULL;
2260         }
2261
2262 #if 0 /* commentind since this breaks keyframing, since it resets the value on draw */
2263         if(scene->r.cfra != cfra) {
2264                 // XXX for prefetch and overlay offset!..., very bad!!!
2265                 AnimData *adt= BKE_animdata_from_id(&scene->id);
2266                 BKE_animsys_evaluate_animdata(scene, &scene->id, adt, cfra, ADT_RECALC_ANIM);
2267         }
2268 #endif
2269
2270         out = seq_stripelem_cache_get(context, seq_arr[count - 1], 
2271                                       cfra, SEQ_STRIPELEM_IBUF_COMP);
2272
2273         if (out) {
2274                 return out;
2275         }
2276         
2277         if(count == 1) {
2278                 out = seq_render_strip(context, seq_arr[0], cfra);
2279                 seq_stripelem_cache_put(context, seq_arr[0], cfra, 
2280                                         SEQ_STRIPELEM_IBUF_COMP, out);
2281
2282                 return out;
2283         }
2284
2285
2286         for (i = count - 1; i >= 0; i--) {
2287                 int early_out;
2288                 Sequence *seq = seq_arr[i];
2289
2290                 out = seq_stripelem_cache_get(
2291                         context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP);
2292
2293                 if (out) {
2294                         break;
2295                 }
2296                 if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2297                         out = seq_render_strip(context, seq, cfra);
2298                         break;
2299                 }
2300
2301                 early_out = seq_get_early_out_for_blend_mode(seq);
2302
2303                 switch (early_out) {
2304                 case EARLY_NO_INPUT:
2305                 case EARLY_USE_INPUT_2:
2306                         out = seq_render_strip(context, seq, cfra);
2307                         break;
2308                 case EARLY_USE_INPUT_1:
2309                         if (i == 0) {
2310                                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
2311                         }
2312                         break;
2313                 case EARLY_DO_EFFECT:
2314                         if (i == 0) {
2315                                 out = seq_render_strip(context, seq, cfra);
2316                         }
2317
2318                         break;
2319                 }
2320                 if (out) {
2321                         break;
2322                 }
2323         }
2324
2325         seq_stripelem_cache_put(context, seq_arr[i], cfra, 
2326                                 SEQ_STRIPELEM_IBUF_COMP, out);
2327
2328
2329         i++;
2330
2331         for (; i < count; i++) {
2332                 Sequence * seq = seq_arr[i];
2333
2334                 if (seq_get_early_out_for_blend_mode(seq) == EARLY_DO_EFFECT) {
2335                         struct SeqEffectHandle sh = get_sequence_blend(seq);
2336                         ImBuf * ibuf1 = out;
2337                         ImBuf * ibuf2 = seq_render_strip(context, seq, cfra);
2338
2339                         float facf = seq->blend_opacity / 100.0f;
2340                         int swap_input = seq_must_swap_input_in_blend_mode(seq);
2341
2342                         if (swap_input) {
2343                                 out = sh.execute(context, seq, cfra, 
2344                                                  facf, facf, 
2345                                                  ibuf2, ibuf1, NULL);
2346                         } else {
2347                                 out = sh.execute(context, seq, cfra, 
2348                                                  facf, facf, 
2349                                                  ibuf1, ibuf2, NULL);
2350                         }
2351                 
2352                         IMB_freeImBuf(ibuf1);
2353                         IMB_freeImBuf(ibuf2);
2354                 }
2355
2356                 seq_stripelem_cache_put(context, seq_arr[i], cfra,
2357                                         SEQ_STRIPELEM_IBUF_COMP, out);
2358         }
2359
2360         return out;
2361 }
2362
2363 /*
2364  * returned ImBuf is refed!
2365  * you have to free after usage!
2366  */
2367
2368 ImBuf *give_ibuf_seq(SeqRenderData context, float cfra, int chanshown)
2369 {
2370         Editing *ed= seq_give_editing(context.scene, FALSE);
2371         int count;
2372         ListBase *seqbasep;
2373         
2374         if(ed==NULL) return NULL;
2375
2376         count = BLI_countlist(&ed->metastack);
2377         if((chanshown < 0) && (count > 0)) {
2378                 count = MAX2(count + chanshown, 0);
2379                 seqbasep= ((MetaStack*)BLI_findlink(&ed->metastack, count))->oldbasep;
2380         } else {
2381                 seqbasep= ed->seqbasep;
2382         }
2383
2384         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2385 }
2386
2387 ImBuf *give_ibuf_seqbase(SeqRenderData context, float cfra, int chanshown, ListBase *seqbasep)
2388 {
2389         return seq_render_strip_stack(context, seqbasep, cfra, chanshown);
2390 }
2391
2392
2393 ImBuf *give_ibuf_seq_direct(SeqRenderData context, float cfra, Sequence *seq)
2394 {
2395         return seq_render_strip(context, seq, cfra);
2396 }
2397
2398 #if 0
2399 /* check used when we need to change seq->blend_mode but not to effect or audio strips */
2400 static int seq_can_blend(Sequence *seq)
2401 {
2402         if (ELEM4(seq->type, SEQ_IMAGE, SEQ_META, SEQ_SCENE, SEQ_MOVIE)) {
2403                 return 1;
2404         } else {
2405                 return 0;
2406         }
2407 }
2408 #endif
2409
2410 /* *********************** threading api ******************* */
2411
2412 static ListBase running_threads;
2413 static ListBase prefetch_wait;
2414 static ListBase prefetch_done;
2415
2416 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
2417 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
2418 static pthread_cond_t  wakeup_cond         = PTHREAD_COND_INITIALIZER;
2419
2420 //static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
2421 //static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
2422
2423 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
2424 static pthread_cond_t  frame_done_cond     = PTHREAD_COND_INITIALIZER;
2425
2426 static volatile int seq_thread_shutdown = TRUE; 
2427 static volatile int seq_last_given_monoton_cfra = 0;
2428 static int monoton_cfra = 0;
2429
2430 typedef struct PrefetchThread {
2431         struct PrefetchThread *next, *prev;
2432         
2433         Scene *scene;
2434         struct PrefetchQueueElem *current;
2435         pthread_t pthread;
2436         int running;
2437         
2438 } PrefetchThread;
2439
2440 typedef struct PrefetchQueueElem {
2441         struct PrefetchQueueElem *next, *prev;
2442         
2443         int rectx;
2444         int recty;
2445         float cfra;
2446         int chanshown;
2447         int preview_render_size;
2448
2449         int monoton_cfra;
2450
2451         struct ImBuf * ibuf;
2452 } PrefetchQueueElem;
2453
2454 #if 0
2455 static void *seq_prefetch_thread(void * This_)
2456 {
2457         PrefetchThread * This = This_;
2458
2459         while (!seq_thread_shutdown) {
2460                 PrefetchQueueElem *e;
2461                 int s_last;
2462
2463                 pthread_mutex_lock(&queue_lock);
2464                 e = prefetch_wait.first;
2465                 if (e) {
2466                         BLI_remlink(&prefetch_wait, e);
2467                 }
2468                 s_last = seq_last_given_monoton_cfra;
2469
2470                 This->current = e;
2471
2472                 pthread_mutex_unlock(&queue_lock);
2473
2474                 if (!e) {
2475                         pthread_mutex_lock(&prefetch_ready_lock);
2476
2477                         This->running = FALSE;
2478
2479                         pthread_cond_signal(&prefetch_ready_cond);
2480                         pthread_mutex_unlock(&prefetch_ready_lock);
2481
2482                         pthread_mutex_lock(&wakeup_lock);
2483                         if (!seq_thread_shutdown) {
2484                                 pthread_cond_wait(&wakeup_cond, &wakeup_lock);
2485                         }
2486                         pthread_mutex_unlock(&wakeup_lock);
2487                         continue;
2488                 }
2489
2490                 This->running = TRUE;
2491                 
2492                 if (e->cfra >= s_last) { 
2493                         e->ibuf = give_ibuf_seq_impl(This->scene, 
2494                                 e->rectx, e->recty, e->cfra, e->chanshown,
2495                                 e->preview_render_size);
2496                 }
2497
2498                 pthread_mutex_lock(&queue_lock);
2499
2500                 BLI_addtail(&prefetch_done, e);
2501
2502                 for (e = prefetch_wait.first; e; e = e->next) {
2503                         if (s_last > e->monoton_cfra) {
2504                                 BLI_remlink(&prefetch_wait, e);
2505                                 MEM_freeN(e);
2506                         }
2507                 }
2508
2509                 for (e = prefetch_done.first; e; e = e->next) {
2510                         if (s_last > e->monoton_cfra) {
2511                                 if (e->ibuf) {
2512                                         IMB_cache_limiter_unref(e->ibuf);
2513                                 }
2514                                 BLI_remlink(&prefetch_done, e);
2515                                 MEM_freeN(e);
2516                         }
2517                 }
2518
2519                 pthread_mutex_unlock(&queue_lock);
2520
2521                 pthread_mutex_lock(&frame_done_lock);
2522                 pthread_cond_signal(&frame_done_cond);
2523                 pthread_mutex_unlock(&frame_done_lock);
2524         }
2525         return 0;
2526 }
2527
2528 static void seq_start_threads(Scene *scene)
2529 {
2530         int i;
2531
2532         running_threads.first = running_threads.last = NULL;
2533         prefetch_wait.first = prefetch_wait.last = NULL;
2534         prefetch_done.first = prefetch_done.last = NULL;
2535
2536         seq_thread_shutdown = FALSE;
2537         seq_last_given_monoton_cfra = monoton_cfra = 0;
2538
2539         /* since global structures are modified during the processing
2540            of one frame, only one render thread is currently possible... 
2541
2542            (but we code, in the hope, that we can remove this restriction
2543            soon...)
2544         */
2545
2546         fprintf(stderr, "SEQ-THREAD: seq_start_threads\n");
2547
2548         for (i = 0; i < 1; i++) {
2549                 PrefetchThread *t = MEM_callocN(sizeof(PrefetchThread), "prefetch_thread");
2550                 t->scene= scene;
2551                 t->running = TRUE;
2552                 BLI_addtail(&running_threads, t);
2553
2554                 pthread_create(&t->pthread, NULL, seq_prefetch_thread, t);
2555         }
2556
2557         /* init malloc mutex */
2558         BLI_init_threads(0, 0, 0);
2559 }
2560
2561 static void seq_stop_threads()
2562 {
2563         PrefetchThread *tslot;
2564         PrefetchQueueElem *e;
2565
2566         fprintf(stderr, "SEQ-THREAD: seq_stop_threads()\n");
2567
2568         if (seq_thread_shutdown) {
2569                 fprintf(stderr, "SEQ-THREAD: ... already stopped\n");
2570                 return;
2571         }
2572         
2573         pthread_mutex_lock(&wakeup_lock);
2574
2575         seq_thread_shutdown = TRUE;
2576
2577                 pthread_cond_broadcast(&wakeup_cond);
2578                 pthread_mutex_unlock(&wakeup_lock);
2579
2580         for(tslot = running_threads.first; tslot; tslot= tslot->next) {
2581                 pthread_join(tslot->pthread, NULL);
2582         }
2583
2584
2585         for (e = prefetch_wait.first; e; e = e->next) {
2586                 BLI_remlink(&prefetch_wait, e);
2587                 MEM_freeN(e);
2588         }
2589
2590         for (e = prefetch_done.first; e; e = e->next) {
2591                 if (e->ibuf) {
2592                         IMB_cache_limiter_unref(e->ibuf);
2593                 }
2594                 BLI_remlink(&prefetch_done, e);
2595                 MEM_freeN(e);
2596         }
2597
2598         BLI_freelistN(&running_threads);
2599
2600         /* deinit malloc mutex */
2601         BLI_end_threads(0);
2602 }
2603 #endif
2604
2605 void give_ibuf_prefetch_request(SeqRenderData context, float cfra, int chanshown)
2606 {
2607         PrefetchQueueElem *e;
2608         if (seq_thread_shutdown) {
2609                 return;
2610         }
2611
2612         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
2613         e->rectx = context.rectx;
2614         e->recty = context.recty;
2615         e->cfra = cfra;
2616         e->chanshown = chanshown;
2617         e->preview_render_size = context.preview_render_size;
2618         e->monoton_cfra = monoton_cfra++;
2619
2620         pthread_mutex_lock(&queue_lock);
2621         BLI_addtail(&prefetch_wait, e);
2622         pthread_mutex_unlock(&queue_lock);
2623         
2624         pthread_mutex_lock(&wakeup_lock);
2625         pthread_cond_signal(&wakeup_cond);
2626         pthread_mutex_unlock(&wakeup_lock);
2627 }
2628
2629 #if 0
2630 static void seq_wait_for_prefetch_ready()
2631 {
2632         PrefetchThread *tslot;
2633
2634         if (seq_thread_shutdown) {
2635                 return;
2636         }
2637
2638         fprintf(stderr, "SEQ-THREAD: rendering prefetch frames...\n");
2639
2640         pthread_mutex_lock(&prefetch_ready_lock);
2641
2642         for(;;) {
2643                 for(tslot = running_threads.first; tslot; tslot= tslot->next) {
2644                         if (tslot->running) {
2645                                 break;
2646                         }
2647                 }
2648                 if (!tslot) {
2649                         break;
2650                 }
2651                 pthread_cond_wait(&prefetch_ready_cond, &prefetch_ready_lock);
2652         }
2653
2654         pthread_mutex_unlock(&prefetch_ready_lock);
2655
2656         fprintf(stderr, "SEQ-THREAD: prefetch done\n");
2657 }
2658 #endif
2659
2660 ImBuf *give_ibuf_seq_threaded(SeqRenderData context, float cfra, int chanshown)
2661 {
2662         PrefetchQueueElem *e = NULL;
2663         int found_something = FALSE;
2664
2665         if (seq_thread_shutdown) {
2666                 return give_ibuf_seq(context, cfra, chanshown);
2667         }
2668
2669         while (!e) {
2670                 int success = FALSE;
2671                 pthread_mutex_lock(&queue_lock);
2672
2673                 for (e = prefetch_done.first; e; e = e->next) {
2674                         if (cfra == e->cfra &&
2675                                 chanshown == e->chanshown &&
2676                                 context.rectx == e->rectx && 
2677                                 context.recty == e->recty &&
2678                                 context.preview_render_size == e->preview_render_size) {
2679                                 success = TRUE;
2680                                 found_something = TRUE;
2681                                 break;
2682                         }
2683                 }
2684
2685                 if (!e) {
2686                         for (e = prefetch_wait.first; e; e = e->next) {
2687                                 if (cfra == e->cfra &&
2688                                         chanshown == e->chanshown &&
2689                                         context.rectx == e->rectx && 
2690                                         context.recty == e->recty &&
2691                                         context.preview_render_size == e->preview_render_size) {
2692                                         found_something = TRUE;
2693                                         break;
2694                                 }
2695                         }
2696                 }
2697
2698                 if (!e) {
2699                         PrefetchThread *tslot;
2700
2701                         for(tslot = running_threads.first; 
2702                                 tslot; tslot= tslot->next) {
2703                                 if (tslot->current &&
2704                                         cfra == tslot->current->cfra &&
2705                                         chanshown == tslot->current->chanshown &&
2706                                         context.rectx == tslot->current->rectx && 
2707                                         context.recty == tslot->current->recty &&
2708                                         context.preview_render_size== tslot->current->preview_render_size){
2709                                         found_something = TRUE;
2710                                         break;
2711                                 }
2712                         }
2713                 }
2714
2715                 /* e->ibuf is unrefed by render thread on next round. */
2716
2717                 if (e) {
2718                         seq_last_given_monoton_cfra = e->monoton_cfra;
2719                 }
2720
2721                 pthread_mutex_unlock(&queue_lock);
2722
2723                 if (!success) {
2724                         e = NULL;
2725
2726                         if (!found_something) {
2727                                 fprintf(stderr, 
2728                                         "SEQ-THREAD: Requested frame "
2729                                         "not in queue ???\n");
2730                                 break;
2731                         }
2732                         pthread_mutex_lock(&frame_done_lock);
2733                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
2734                         pthread_mutex_unlock(&frame_done_lock);
2735                 }
2736         }
2737         
2738         return e ? e->ibuf : NULL;
2739 }
2740
2741 /* Functions to free imbuf and anim data on changes */
2742
2743 static void free_anim_seq(Sequence *seq)
2744 {
2745         if(seq->anim) {
2746                 IMB_free_anim(seq->anim);
2747                 seq->anim = NULL;
2748         }
2749 }
2750
2751 void free_imbuf_seq(Scene *scene, ListBase * seqbase, int check_mem_usage,
2752                     int keep_file_handles)
2753 {
2754         Sequence *seq;
2755
2756         if (check_mem_usage) {
2757                 /* Let the cache limitor take care of this (schlaile) */
2758                 /* While render let's keep all memory available for render 
2759                    (ton)
2760                    At least if free memory is tight...
2761                    This can make a big difference in encoding speed
2762                    (it is around 4 times(!) faster, if we do not waste time
2763                    on freeing _all_ buffers every time on long timelines...)
2764                    (schlaile)
2765                 */
2766         
2767                 uintptr_t mem_in_use;
2768                 uintptr_t mmap_in_use;
2769                 uintptr_t max;
2770         
2771                 mem_in_use= MEM_get_memory_in_use();
2772                 mmap_in_use= MEM_get_mapped_memory_in_use();
2773                 max = MEM_CacheLimiter_get_maximum();
2774         
2775                 if (max == 0 || mem_in_use + mmap_in_use <= max) {
2776                         return;
2777                 }
2778         }
2779
2780         seq_stripelem_cache_cleanup();
2781         
2782         for(seq= seqbase->first; seq; seq= seq->next) {
2783                 if(seq->strip) {
2784                         if(seq->type==SEQ_MOVIE && !keep_file_handles)
2785                                 free_anim_seq(seq);
2786                         if(seq->type==SEQ_SPEED) {
2787                                 sequence_effect_speed_rebuild_map(scene, seq, 1);
2788                         }
2789                 }
2790                 if(seq->type==SEQ_META) {
2791                         free_imbuf_seq(scene, &seq->seqbase, FALSE, keep_file_handles);
2792                 }
2793                 if(seq->type==SEQ_SCENE) {
2794                         /* FIXME: recurs downwards, 
2795                            but do recurs protection somehow! */
2796                 }
2797         }
2798         
2799 }
2800
2801 static int update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
2802 {
2803         Sequence *subseq;
2804         int free_imbuf = 0;
2805         
2806         /* recurs downwards to see if this seq depends on the changed seq */
2807         
2808         if(seq == NULL)
2809                 return 0;
2810         
2811         if(seq == changed_seq)
2812                 free_imbuf = 1;
2813         
2814         for(subseq=seq->seqbase.first; subseq; subseq=subseq->next)
2815                 if(update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change))
2816                         free_imbuf = TRUE;
2817         
2818         if(seq->seq1)
2819                 if(update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change))
2820                         free_imbuf = TRUE;
2821         if(seq->seq2 && (seq->seq2 != seq->seq1))
2822                 if(update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change))
2823                         free_imbuf = TRUE;
2824         if(seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
2825                 if(update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change))
2826                         free_imbuf = TRUE;
2827         
2828         if(free_imbuf) {
2829                 if(ibuf_change) {
2830                         if(seq->type == SEQ_MOVIE)
2831                                 free_anim_seq(seq);
2832                         if(seq->type == SEQ_SPEED) {
2833                                 sequence_effect_speed_rebuild_map(scene, seq, 1);
2834                         }
2835                 }
2836                 
2837                 if(len_change)
2838                         calc_sequence(scene, seq);
2839         }
2840         
2841         return free_imbuf;
2842 }
2843
2844 void update_changed_seq_and_deps(Scene *scene, Sequence *changed_seq, int len_change, int ibuf_change)
2845 {
2846         Editing *ed= seq_give_editing(scene, FALSE);
2847         Sequence *seq;
2848         
2849         if (ed==NULL) return;
2850         
2851         for (seq=ed->seqbase.first; seq; seq=seq->next)
2852                 update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change);
2853 }
2854
2855 /* seq funcs's for transforming internally
2856  notice the difference between start/end and left/right.
2857
2858  left and right are the bounds at which the sequence is rendered,
2859 start and end are from the start and fixed length of the sequence.
2860 */
2861 int seq_tx_get_start(Sequence *seq)
2862 {
2863         return seq->start;
2864 }
2865 int seq_tx_get_end(Sequence *seq)
2866 {
2867         return seq->start+seq->len;
2868 }
2869
2870 int seq_tx_get_final_left(Sequence *seq, int metaclip)
2871 {
2872         if (metaclip && seq->tmp) {
2873                 /* return the range clipped by the parents range */
2874                 return MAX2( seq_tx_get_final_left(seq, 0), seq_tx_get_final_left((Sequence *)seq->tmp, 1) );
2875         } else {
2876                 return (seq->start - seq->startstill) + seq->startofs;
2877         }
2878
2879 }
2880 int seq_tx_get_final_right(Sequence *seq, int metaclip)
2881 {
2882         if (metaclip && seq->tmp) {
2883                 /* return the range clipped by the parents range */
2884                 return MIN2( seq_tx_get_final_right(seq, 0), seq_tx_get_final_right((Sequence *)seq->tmp, 1) );
2885         } else {
2886                 return ((seq->start+seq->len) + seq->endstill) - seq->endofs;
2887         }
2888 }
2889
2890 void seq_tx_set_final_left(Sequence *seq, int val)
2891 {
2892         if (val < (seq)->start) {
2893                 seq->startstill = abs(val - (seq)->start);
2894                 seq->startofs = 0;
2895         } else {
2896                 seq->startofs = abs(val - (seq)->start);
2897                 seq->startstill = 0;
2898         }
2899 }
2900
2901 void seq_tx_set_final_right(Sequence *seq, int val)
2902 {
2903         if (val > (seq)->start + (seq)->len) {
2904                 seq->endstill = abs(val - (seq->start + (seq)->len));
2905                 seq->endofs = 0;
2906         } else {
2907                 seq->endofs = abs(val - ((seq)->start + (seq)->len));
2908                 seq->endstill = 0;
2909         }
2910 }
2911
2912 /* used so we can do a quick check for single image seq
2913    since they work a bit differently to normal image seq's (during transform) */
2914 int seq_single_check(Sequence *seq)
2915 {
2916         return (seq->len==1 && (
2917                         seq->type == SEQ_IMAGE 
2918                         || ((seq->type & SEQ_EFFECT) && 
2919                             get_sequence_effect_num_inputs(seq->type) == 0)));
2920 }
2921
2922 /* check if the selected seq's reference unselected seq's */
2923 int seqbase_isolated_sel_check(ListBase *seqbase)
2924 {
2925         Sequence *seq;
2926         /* is there more than 1 select */
2927         int ok= FALSE;
2928
2929         for(seq= seqbase->first; seq; seq= seq->next) {
2930                 if(seq->flag & SELECT) {
2931                         ok= TRUE;
2932                         break;
2933                 }
2934         }
2935
2936         if(ok == FALSE)
2937                 return FALSE;
2938
2939         /* test relationships */
2940         for(seq= seqbase->first; seq; seq= seq->next) {
2941                 if((seq->type & SEQ_EFFECT)==0)
2942                         continue;
2943
2944                 if(seq->flag & SELECT) {
2945                         if( (seq->seq1 && (seq->seq1->flag & SELECT)==0) ||
2946                                 (seq->seq2 && (seq->seq2->flag & SELECT)==0) ||
2947                                 (seq->seq3 && (seq->seq3->flag & SELECT)==0) )
2948                                 return FALSE;
2949                 }
2950                 else {
2951                         if( (seq->seq1 && (seq->seq1->flag & SELECT)) ||
2952                                 (seq->seq2 && (seq->seq2->flag & SELECT)) ||
2953                                 (seq->seq3 && (seq->seq3->flag & SELECT)) )
2954                                 return FALSE;
2955                 }
2956         }
2957
2958         return TRUE;
2959 }
2960
2961 /* use to impose limits when dragging/extending - so impossible situations dont happen
2962  * Cant use the SEQ_LEFTSEL and SEQ_LEFTSEL directly because the strip may be in a metastrip */
2963 void seq_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag)
2964 {
2965         if(leftflag) {
2966                 if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_final_right(seq, 0)) {
2967                         seq_tx_set_final_left(seq, seq_tx_get_final_right(seq, 0)-1);
2968                 }
2969
2970                 if (seq_single_check(seq)==0) {
2971                         if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_end(seq)) {
2972                                 seq_tx_set_final_left(seq, seq_tx_get_end(seq)-1);
2973                         }
2974
2975                         /* dosnt work now - TODO */
2976                         /*
2977                         if (seq_tx_get_start(seq) >= seq_tx_get_final_right(seq, 0)) {
2978                                 int ofs;
2979                                 ofs = seq_tx_get_start(seq) - seq_tx_get_final_right(seq, 0);
2980                                 seq->start -= ofs;
2981                                 seq_tx_set_final_left(seq, seq_tx_get_final_left(seq, 0) + ofs );
2982                         }*/
2983
2984                 }
2985         }
2986
2987         if(rightflag) {
2988                 if (seq_tx_get_final_right(seq, 0) <=  seq_tx_get_final_left(seq, 0)) {
2989                         seq_tx_set_final_right(seq, seq_tx_get_final_left(seq, 0)+1);
2990                 }
2991
2992                 if (seq_single_check(seq)==0) {
2993                         if (seq_tx_get_final_right(seq, 0) <= seq_tx_get_start(seq)) {
2994                                 seq_tx_set_final_right(seq, seq_tx_get_start(seq)+1);
2995                         }
2996                 }
2997         }
2998
2999         /* sounds cannot be extended past their endpoints */
3000         if (seq->type == SEQ_SOUND) {
3001                 seq->startstill= 0;
3002                 seq->endstill= 0;
3003         }
3004 }
3005
3006 void seq_single_fix(Sequence *seq)
3007 {
3008         int left, start, offset;
3009         if (!seq_single_check(seq))
3010                 return;
3011
3012         /* make sure the image is always at the start since there is only one,
3013            adjusting its start should be ok */
3014         left = seq_tx_get_final_left(seq, 0);
3015         start = seq->start;
3016         if (start != left) {
3017                 offset = left - start;
3018                 seq_tx_set_final_left( seq, seq_tx_get_final_left(seq, 0) - offset );
3019                 seq_tx_set_final_right( seq, seq_tx_get_final_right(seq, 0) - offset );
3020                 seq->start += offset;
3021         }
3022 }
3023
3024 int seq_tx_test(Sequence * seq)
3025 {
3026         return (seq->type < SEQ_EFFECT) || (get_sequence_effect_num_inputs(seq->type) == 0);
3027 }
3028
3029 static int seq_overlap(Sequence *seq1, Sequence *seq2)
3030 {
3031         return (seq1 != seq2 && seq1->machine == seq2->machine &&
3032                         ((seq1->enddisp <= seq2->startdisp) || (seq1->startdisp >= seq2->enddisp))==0);
3033 }
3034
3035 int seq_test_overlap(ListBase * seqbasep, Sequence *test)
3036 {
3037         Sequence *seq;
3038
3039         seq= seqbasep->first;
3040         while(seq) {
3041                 if(seq_overlap(test, seq))
3042                         return 1;
3043
3044                 seq= seq->next;
3045         }
3046         return 0;
3047 }
3048
3049
3050 void seq_translate(Scene *evil_scene, Sequence *seq, int delta)
3051 {
3052         seq_offset_animdata(evil_scene, seq, delta);
3053         seq->start += delta;
3054
3055         if(seq->type==SEQ_META) {
3056                 Sequence *seq_child;
3057                 for(seq_child= seq->seqbase.first; seq_child; seq_child= seq_child->next) {
3058                         seq_translate(evil_scene, seq_child, delta);
3059                 }
3060         }
3061
3062         calc_sequence_disp(evil_scene, seq);
3063 }
3064
3065 void seq_sound_init(Scene *scene, Sequence *seq)
3066 {
3067         if(seq->type==SEQ_META) {
3068                 Sequence *seq_child;
3069                 for(seq_child= seq->seqbase.first; seq_child; seq_child= seq_child->next) {
3070                         seq_sound_init(scene, seq_child);
3071                 }
3072         }
3073         else {
3074                 if(seq->sound) {
3075                         seq->scene_sound = sound_add_scene_sound(scene, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3076                 }
3077                 if(seq->scene) {
3078                         sound_scene_add_scene_sound(scene, seq, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3079                 }
3080         }
3081 }
3082
3083 Sequence *seq_foreground_frame_get(Scene *scene, int frame)
3084 {
3085         Editing *ed= seq_give_editing(scene, FALSE);
3086         Sequence *seq, *best_seq=NULL;
3087         int best_machine = -1;
3088         
3089         if(!ed) return NULL;
3090         
3091         for (seq=ed->seqbasep->first; seq; seq= seq->next) {
3092                 if(seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame)
3093                         continue;
3094                 /* only use elements you can see - not */
3095                 if (ELEM5(seq->type, SEQ_IMAGE, SEQ_META, SEQ_SCENE, SEQ_MOVIE, SEQ_COLOR)) {
3096                         if (seq->machine > best_machine) {
3097                                 best_seq = seq;
3098                                 best_machine = seq->machine;
3099                         }
3100                 }
3101         }
3102         return best_seq;
3103 }
3104
3105 /* return 0 if there werent enough space */
3106 int shuffle_seq(ListBase * seqbasep, Sequence *test, Scene *evil_scene)
3107 {
3108         int orig_machine= test->machine;
3109         test->machine++;
3110         calc_sequence(evil_scene, test);
3111         while( seq_test_overlap(seqbasep, test) ) {
3112                 if(test->machine >= MAXSEQ) {
3113                         break;
3114                 }
3115                 test->machine++;
3116                 calc_sequence(evil_scene, test); // XXX - I dont think this is needed since were only moving vertically, Campbell.
3117         }
3118
3119         
3120         if(test->machine >= MAXSEQ) {
3121                 /* Blender 2.4x would remove the strip.
3122                  * nicer to move it to the end */
3123
3124                 Sequence *seq;
3125                 int new_frame= test->enddisp;
3126
3127                 for(seq= seqbasep->first; seq; seq= seq->next) {
3128                         if (seq->machine == orig_machine)
3129                                 new_frame = MAX2(new_frame, seq->enddisp);
3130                 }
3131
3132                 test->machine= orig_machine;
3133                 new_frame = new_frame + (test->start-test->startdisp); /* adjust by the startdisp */
3134                 seq_translate(evil_scene, test, new_frame - test->start);
3135
3136                 calc_sequence(evil_scene, test);
3137                 return 0;
3138         } else {
3139                 return 1;
3140         }
3141 }
3142
3143 static int shuffle_seq_time_offset_test(ListBase * seqbasep, char dir)
3144 {
3145         int offset= 0;
3146         Sequence *seq, *seq_other;
3147
3148         for(seq= seqbasep->first; seq; seq= seq->next) {
3149                 if(seq->tmp) {
3150                         for(seq_other= seqbasep->first; seq_other; seq_other= seq_other->next) {
3151                                 if(!seq_other->tmp && seq_overlap(seq, seq_other)) {
3152                                         if(dir=='L') {
3153                                                 offset= MIN2(offset, seq_other->startdisp - seq->enddisp);
3154                                         }
3155                                         else {
3156                                                 offset= MAX2(offset, seq_other->enddisp - seq->startdisp);
3157                                         }
3158                                 }
3159                         }
3160                 }
3161         }
3162         return offset;
3163 }
3164
3165 static int shuffle_seq_time_offset(Scene* scene, ListBase * seqbasep, char dir)
3166 {
3167         int ofs= 0;
3168         int tot_ofs= 0;
3169         Sequence *seq;
3170         while( (ofs= shuffle_seq_time_offset_test(seqbasep, dir)) ) {
3171                 for(seq= seqbasep->first; seq; seq= seq->next) {
3172                         if(seq->tmp) {
3173                                 /* seq_test_overlap only tests display values */
3174                                 seq->startdisp +=       ofs;
3175                                 seq->enddisp +=         ofs;
3176                         }
3177                 }
3178
3179                 tot_ofs+= ofs;
3180         }
3181
3182         for(seq= seqbasep->first; seq; seq= seq->next) {
3183                 if(seq->tmp)
3184                         calc_sequence_disp(scene, seq); /* corrects dummy startdisp/enddisp values */
3185         }
3186
3187         return tot_ofs;
3188 }
3189
3190 int shuffle_seq_time(ListBase * seqbasep, Scene *evil_scene)
3191 {
3192         /* note: seq->tmp is used to tag strips to move */
3193
3194         Sequence *seq;
3195
3196         int offset_l = shuffle_seq_time_offset(evil_scene, seqbasep, 'L');
3197         int offset_r = shuffle_seq_time_offset(evil_scene, seqbasep, 'R');
3198         int offset = (-offset_l < offset_r) ?  offset_l:offset_r;
3199
3200         if(offset) {
3201                 for(seq= seqbasep->first; seq; seq= seq->next) {
3202                         if(seq->tmp) {
3203                                 seq_translate(evil_scene, seq, offset);
3204                                 seq->flag &= ~SEQ_OVERLAP;
3205                         }
3206                 }
3207         }
3208
3209         return offset? 0:1;
3210 }
3211
3212 void seq_update_sound_bounds_all(Scene *scene)
3213 {
3214         Editing *ed = scene->ed;
3215
3216         if(ed) {
3217                 Sequence *seq;
3218
3219                 for(seq = ed->seqbase.first; seq; seq = seq->next) {
3220                         if(seq->type == SEQ_META) {
3221                                 seq_update_sound_bounds_recursive(scene, seq);
3222                         }
3223                         else if(ELEM(seq->type, SEQ_SOUND, SEQ_SCENE)) {
3224                                 seq_update_sound_bounds(scene, seq);
3225                         }
3226                 }
3227         }
3228 }
3229
3230 void seq_update_sound_bounds(Scene* scene, Sequence *seq)
3231 {
3232         if(seq->scene_sound) {
3233                 sound_move_scene_sound(scene, seq->scene_sound, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3234                 /* mute is set in seq_update_muting_recursive */
3235         }
3236 }
3237
3238 static void seq_update_muting_recursive(ListBase *seqbasep, Sequence *metaseq, int mute)
3239 {
3240         Sequence *seq;
3241         int seqmute;
3242
3243         /* for sound we go over full meta tree to update muted state,
3244            since sound is played outside of evaluating the imbufs, */
3245         for(seq=seqbasep->first; seq; seq=seq->next) {
3246                 seqmute= (mute || (seq->flag & SEQ_MUTE));
3247
3248                 if(seq->type == SEQ_META) {
3249                         /* if this is the current meta sequence, unmute because
3250                            all sequences above this were set to mute */
3251                         if(seq == metaseq)
3252                                 seqmute= 0;
3253
3254                         seq_update_muting_recursive(&seq->seqbase, metaseq, seqmute);
3255                 }
3256                 else if(ELEM(seq->type, SEQ_SOUND, SEQ_SCENE)) {
3257                         if(seq->scene_sound) {
3258                                 sound_mute_scene_sound(seq->scene_sound, seqmute);
3259                         }
3260                 }
3261         }
3262 }
3263
3264 void seq_update_muting(Editing *ed)
3265 {
3266         if(ed) {
3267                 /* mute all sounds up to current metastack list */
3268                 MetaStack *ms= ed->metastack.last;
3269
3270                 if(ms)
3271                         seq_update_muting_recursive(&ed->seqbase, ms->parseq, 1);
3272                 else
3273                         seq_update_muting_recursive(&ed->seqbase, NULL, 0);
3274         }
3275 }
3276
3277 static void seq_update_sound_recursive(Scene *scene, ListBase *seqbasep, bSound *sound)
3278 {
3279         Sequence *seq;
3280
3281         for(seq=seqbasep->first; seq; seq=seq->next) {
3282                 if(seq->type == SEQ_META) {
3283                         seq_update_sound_recursive(scene, &seq->seqbase, sound);
3284                 }
3285                 else if(seq->type == SEQ_SOUND) {
3286                         if(seq->scene_sound && sound == seq->sound) {
3287                                 sound_update_scene_sound(seq->scene_sound, sound);
3288                         }
3289                 }
3290         }
3291 }
3292
3293 void seq_update_sound(struct Scene *scene, struct bSound *sound)