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