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