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