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