== Sequencer / Imbuf ==
[blender-staging.git] / source / blender / src / sequence.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * Contributor(s): Peter Schlaile <peter [at] schlaile [dot] de> 2005/2006
27  *
28  * ***** END GPL/BL DUAL LICENSE BLOCK *****
29  */
30
31 #include <string.h>
32 #include <math.h>
33 #include <stdlib.h>
34
35 #include "MEM_guardedalloc.h"
36 #include "MEM_CacheLimiterC-Api.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_arithb.h"
40
41 #include "IMB_imbuf_types.h"
42 #include "IMB_imbuf.h"
43
44 #include "DNA_ipo_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_sequence_types.h"
47 #include "DNA_view3d_types.h"
48
49 #include "BKE_global.h"
50 #include "BKE_image.h"
51 #include "BKE_ipo.h"
52 #include "BKE_main.h"
53 #include "BKE_scene.h"
54 #include "BKE_texture.h"
55 #include "BKE_utildefines.h"
56
57 #include "BIF_editsound.h"
58 #include "BIF_editseq.h"
59 #include "BSE_filesel.h"
60 #include "BSE_headerbuttons.h"
61 #include "BIF_interface.h"
62 #include "BIF_renderwin.h"
63 #include "BIF_screen.h"
64 #include "BIF_space.h"
65 #include "BIF_toolbox.h"
66
67 #include "BSE_sequence.h"
68 #include "BSE_seqeffects.h"
69
70 #include "RE_pipeline.h"                // talks to entire render API
71
72 #include "blendef.h"
73
74 #include "BLI_threads.h"
75 #include <pthread.h>
76
77 int seqrectx, seqrecty;
78
79 void free_tstripdata(int len, TStripElem *se)
80 {
81         TStripElem *seo;
82         int a;
83
84         seo= se;
85         if (!se) {
86                 return;
87         }
88
89         for(a=0; a<len; a++, se++) {
90                 if(se->ibuf) {
91                         IMB_freeImBuf(se->ibuf);
92                         se->ibuf = 0;
93                 }
94                 if(se->ibuf_comp) {
95                         IMB_freeImBuf(se->ibuf_comp);
96                         se->ibuf_comp = 0;
97                 }
98         }
99
100         MEM_freeN(seo);
101
102 }
103
104 void seq_proxy_free(StripProxy * proxy)
105 {
106         MEM_freeN(proxy);
107 }
108
109 void free_strip(Strip *strip)
110 {
111         strip->us--;
112         if(strip->us>0) return;
113         if(strip->us<0) {
114                 printf("error: negative users in strip\n");
115                 return;
116         }
117
118         if(strip->stripdata) {
119                 MEM_freeN(strip->stripdata);
120         }
121         if (strip->crop) {
122                 MEM_freeN(strip->crop);
123         }
124         if (strip->transform) {
125                 MEM_freeN(strip->transform);
126         }
127         if (strip->proxy) {
128                 seq_proxy_free(strip->proxy);
129         }
130
131         free_tstripdata(strip->len, strip->tstripdata);
132         free_tstripdata(strip->endstill, strip->tstripdata_endstill);
133         free_tstripdata(strip->startstill, strip->tstripdata_startstill);
134
135         MEM_freeN(strip);
136 }
137
138 void new_tstripdata(Sequence *seq)
139 {
140         if(seq->strip) {
141                 free_tstripdata(seq->strip->len, seq->strip->tstripdata);
142                 free_tstripdata(seq->strip->endstill, 
143                                 seq->strip->tstripdata_endstill);
144                 free_tstripdata(seq->strip->startstill, 
145                                 seq->strip->tstripdata_startstill);
146
147                 seq->strip->tstripdata= 0;
148                 seq->strip->tstripdata_endstill= 0;
149                 seq->strip->tstripdata_startstill= 0;
150
151                 seq->strip->len= seq->len;
152         }
153 }
154
155 void free_sequence(Sequence *seq)
156 {
157         Sequence *last_seq = get_last_seq();
158
159         if(seq->strip) free_strip(seq->strip);
160
161         if(seq->anim) IMB_free_anim(seq->anim);
162         if(seq->hdaudio) sound_close_hdaudio(seq->hdaudio);
163
164         if (seq->type & SEQ_EFFECT) {
165                 struct SeqEffectHandle sh = get_sequence_effect(seq);
166
167                 sh.free(seq);
168         }
169
170         if(seq==last_seq) set_last_seq(NULL);
171
172         MEM_freeN(seq);
173 }
174
175 /*
176   **********************************************************************
177   * build_seqar
178   **********************************************************************
179   * Build a complete array of _all_ sequencies (including those
180   * in metastrips!)
181   **********************************************************************
182 */
183
184 static void do_seq_count(ListBase *seqbase, int *totseq)
185 {
186         Sequence *seq;
187
188         seq= seqbase->first;
189         while(seq) {
190                 (*totseq)++;
191                 if(seq->seqbase.first) do_seq_count(&seq->seqbase, totseq);
192                 seq= seq->next;
193         }
194 }
195
196 static void do_build_seqar(ListBase *seqbase, Sequence ***seqar, int depth)
197 {
198         Sequence *seq;
199
200         seq= seqbase->first;
201         while(seq) {
202                 seq->depth= depth;
203                 if(seq->seqbase.first) do_build_seqar(&seq->seqbase, seqar, depth+1);
204                 **seqar= seq;
205                 (*seqar)++;
206                 seq= seq->next;
207         }
208 }
209
210 void build_seqar(ListBase *seqbase, Sequence  ***seqar, int *totseq)
211 {
212         Sequence **tseqar;
213
214         *totseq= 0;
215         do_seq_count(seqbase, totseq);
216
217         if(*totseq==0) {
218                 *seqar= 0;
219                 return;
220         }
221         *seqar= MEM_mallocN(sizeof(void *)* *totseq, "seqar");
222         tseqar= *seqar;
223
224         do_build_seqar(seqbase, seqar, 0);
225         *seqar= tseqar;
226 }
227
228 static void do_seq_count_cb(ListBase *seqbase, int *totseq,
229                             int (*test_func)(Sequence * seq))
230 {
231         Sequence *seq;
232
233         seq= seqbase->first;
234         while(seq) {
235                 int test = test_func(seq);
236                 if (test & BUILD_SEQAR_COUNT_CURRENT) {
237                         (*totseq)++;
238                 }
239                 if(seq->seqbase.first && (test & BUILD_SEQAR_COUNT_CHILDREN)) {
240                         do_seq_count_cb(&seq->seqbase, totseq, test_func);
241                 }
242                 seq= seq->next;
243         }
244 }
245
246 static void do_build_seqar_cb(ListBase *seqbase, Sequence ***seqar, int depth,
247                               int (*test_func)(Sequence * seq))
248 {
249         Sequence *seq;
250
251         seq= seqbase->first;
252         while(seq) {
253                 int test = test_func(seq);
254                 seq->depth= depth;
255
256                 if(seq->seqbase.first && (test & BUILD_SEQAR_COUNT_CHILDREN)) {
257                         do_build_seqar_cb(&seq->seqbase, seqar, depth+1, 
258                                           test_func);
259                 }
260                 if (test & BUILD_SEQAR_COUNT_CURRENT) {
261                         **seqar= seq;
262                         (*seqar)++;
263                 }
264                 seq= seq->next;
265         }
266 }
267
268 void build_seqar_cb(ListBase *seqbase, Sequence  ***seqar, int *totseq,
269                     int (*test_func)(Sequence * seq))
270 {
271         Sequence **tseqar;
272
273         *totseq= 0;
274         do_seq_count_cb(seqbase, totseq, test_func);
275
276         if(*totseq==0) {
277                 *seqar= 0;
278                 return;
279         }
280         *seqar= MEM_mallocN(sizeof(void *)* *totseq, "seqar");
281         tseqar= *seqar;
282
283         do_build_seqar_cb(seqbase, seqar, 0, test_func);
284         *seqar= tseqar;
285 }
286
287
288 void free_editing(Editing *ed)
289 {
290         MetaStack *ms;
291         Sequence *seq;
292
293         if(ed==NULL) return;
294         set_last_seq(NULL);     /* clear_last_seq doesnt work, it screws up free_sequence */
295
296         WHILE_SEQ(&ed->seqbase) {
297                 free_sequence(seq);
298         }
299         END_SEQ
300
301         while( (ms= ed->metastack.first) ) {
302                 BLI_remlink(&ed->metastack, ms);
303                 MEM_freeN(ms);
304         }
305
306         MEM_freeN(ed);
307
308 }
309
310 void calc_sequence_disp(Sequence *seq)
311 {
312         if(seq->startofs && seq->startstill) seq->startstill= 0;
313         if(seq->endofs && seq->endstill) seq->endstill= 0;
314         
315         seq->startdisp= seq->start + seq->startofs - seq->startstill;
316         seq->enddisp= seq->start+seq->len - seq->endofs + seq->endstill;
317         
318         seq->handsize= 10.0;    /* 10 frames */
319         if( seq->enddisp-seq->startdisp < 10 ) {
320                 seq->handsize= (float)(0.5*(seq->enddisp-seq->startdisp));
321         }
322         else if(seq->enddisp-seq->startdisp > 250) {
323                 seq->handsize= (float)((seq->enddisp-seq->startdisp)/25);
324         }
325 }
326
327 void calc_sequence(Sequence *seq)
328 {
329         Sequence *seqm;
330         int min, max;
331
332         /* check all metas recursively */
333         seqm= seq->seqbase.first;
334         while(seqm) {
335                 if(seqm->seqbase.first) calc_sequence(seqm);
336                 seqm= seqm->next;
337         }
338
339         /* effects and meta: automatic start and end */
340
341         if(seq->type & SEQ_EFFECT) {
342                 /* pointers */
343                 if(seq->seq2==0) seq->seq2= seq->seq1;
344                 if(seq->seq3==0) seq->seq3= seq->seq1;
345
346                 /* effecten go from seq1 -> seq2: test */
347
348                 /* we take the largest start and smallest end */
349
350                 // seq->start= seq->startdisp= MAX2(seq->seq1->startdisp, seq->seq2->startdisp);
351                 // seq->enddisp= MIN2(seq->seq1->enddisp, seq->seq2->enddisp);
352
353                 if (seq->seq1) {
354                         seq->start= seq->startdisp= MAX3(seq->seq1->startdisp, seq->seq2->startdisp, seq->seq3->startdisp);
355                         seq->enddisp= MIN3(seq->seq1->enddisp, seq->seq2->enddisp, seq->seq3->enddisp);
356                         seq->len= seq->enddisp - seq->startdisp;
357                 } else {
358                         calc_sequence_disp(seq);
359                 }
360
361                 if(seq->strip && seq->len!=seq->strip->len) {
362                         new_tstripdata(seq);
363                 }
364
365         }
366         else {
367                 if(seq->type==SEQ_META) {
368                         seqm= seq->seqbase.first;
369                         if(seqm) {
370                                 min= 1000000;
371                                 max= -1000000;
372                                 while(seqm) {
373                                         if(seqm->startdisp < min) min= seqm->startdisp;
374                                         if(seqm->enddisp > max) max= seqm->enddisp;
375                                         seqm= seqm->next;
376                                 }
377                                 seq->start= min;
378                                 seq->len= max-min;
379
380                                 if(seq->strip && seq->len!=seq->strip->len) {
381                                         new_tstripdata(seq);
382                                 }
383                         }
384                 }
385                 calc_sequence_disp(seq);
386         }
387 }
388
389 void reload_sequence_new_file(Sequence * seq)
390 {
391         char str[FILE_MAXDIR+FILE_MAXFILE];
392
393         if (!(seq->type == SEQ_MOVIE || seq->type == SEQ_IMAGE ||
394               seq->type == SEQ_HD_SOUND || seq->type == SEQ_SCENE)) {
395                 return;
396         }
397
398         new_tstripdata(seq);
399
400         if (seq->type == SEQ_IMAGE) {
401                 return;
402         }
403
404         if (seq->type != SEQ_SCENE) {
405                 strncpy(str, seq->strip->dir, FILE_MAXDIR-1);
406                 strncat(str, seq->strip->stripdata->name, FILE_MAXFILE-1);
407         }
408
409         if (seq->type == SEQ_MOVIE) {
410                 if(seq->anim) IMB_free_anim(seq->anim);
411                 seq->anim = openanim(str, IB_rect);
412
413                 if (!seq->anim) {
414                         return;
415                 }
416         
417                 seq->len = IMB_anim_get_duration(seq->anim);
418                 
419                 seq->anim_preseek = IMB_anim_get_preseek(seq->anim);
420
421                 seq->len -= seq->anim_startofs;
422                 seq->len -= seq->anim_endofs;
423                 if (seq->len < 0) {
424                         seq->len = 0;
425                 }
426                 seq->strip->len = seq->len;
427         } else if (seq->type == SEQ_HD_SOUND) {
428                 if(seq->hdaudio) sound_close_hdaudio(seq->hdaudio);
429                 seq->hdaudio = sound_open_hdaudio(str);
430
431                 if (!seq->hdaudio) {
432                         return;
433                 }
434
435                 seq->strip->len = seq->len 
436                         = sound_hdaudio_get_duration(seq->hdaudio, FPS);
437         } else if (seq->type == SEQ_SCENE) {
438                 Scene * sce = G.main->scene.first;
439                 int nr = 1;
440                 while(sce) {
441                         if(nr == seq->scenenr) {
442                                 break;
443                         }
444                         nr++;
445                         sce= sce->id.next;
446                 }
447
448                 if (sce) {
449                         seq->scene = sce;
450                 }
451
452                 strncpy(seq->name + 2, sce->id.name + 2, 
453                         sizeof(seq->name) - 2);
454
455                 seq->len= seq->scene->r.efra - seq->scene->r.sfra + 1;
456                 seq->len -= seq->anim_startofs;
457                 seq->len -= seq->anim_endofs;
458                 if (seq->len < 0) {
459                         seq->len = 0;
460                 }
461                 seq->strip->len = seq->len;
462         }
463
464
465         calc_sequence(seq);
466 }
467
468 void sort_seq()
469 {
470         /* all strips together per kind, and in order of y location ("machine") */
471         ListBase seqbase, effbase;
472         Editing *ed;
473         Sequence *seq, *seqt;
474
475         ed= G.scene->ed;
476         if(ed==0) return;
477
478         seqbase.first= seqbase.last= 0;
479         effbase.first= effbase.last= 0;
480
481         while( (seq= ed->seqbasep->first) ) {
482                 BLI_remlink(ed->seqbasep, seq);
483
484                 if(seq->type & SEQ_EFFECT) {
485                         seqt= effbase.first;
486                         while(seqt) {
487                                 if(seqt->machine>=seq->machine) {
488                                         BLI_insertlinkbefore(&effbase, seqt, seq);
489                                         break;
490                                 }
491                                 seqt= seqt->next;
492                         }
493                         if(seqt==0) BLI_addtail(&effbase, seq);
494                 }
495                 else {
496                         seqt= seqbase.first;
497                         while(seqt) {
498                                 if(seqt->machine>=seq->machine) {
499                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
500                                         break;
501                                 }
502                                 seqt= seqt->next;
503                         }
504                         if(seqt==0) BLI_addtail(&seqbase, seq);
505                 }
506         }
507
508         addlisttolist(&seqbase, &effbase);
509         *(ed->seqbasep)= seqbase;
510 }
511
512
513 void clear_scene_in_allseqs(Scene *sce)
514 {
515         Scene *sce1;
516         Editing *ed;
517         Sequence *seq;
518
519         /* when a scene is deleted: test all seqs */
520
521         sce1= G.main->scene.first;
522         while(sce1) {
523                 if(sce1!=sce && sce1->ed) {
524                         ed= sce1->ed;
525
526                         WHILE_SEQ(&ed->seqbase) {
527
528                                 if(seq->scene==sce) seq->scene= 0;
529
530                         }
531                         END_SEQ
532                 }
533
534                 sce1= sce1->id.next;
535         }
536 }
537
538 char *give_seqname_by_type(int type)
539 {
540         switch(type) {
541         case SEQ_META:       return "Meta";
542         case SEQ_IMAGE:      return "Image";
543         case SEQ_SCENE:      return "Scene";
544         case SEQ_MOVIE:      return "Movie";
545         case SEQ_RAM_SOUND:  return "Audio (RAM)";
546         case SEQ_HD_SOUND:   return "Audio (HD)";
547         case SEQ_CROSS:      return "Cross";
548         case SEQ_GAMCROSS:   return "Gamma Cross";
549         case SEQ_ADD:        return "Add";
550         case SEQ_SUB:        return "Sub";
551         case SEQ_MUL:        return "Mul";
552         case SEQ_ALPHAOVER:  return "Alpha Over";
553         case SEQ_ALPHAUNDER: return "Alpha Under";
554         case SEQ_OVERDROP:   return "Over Drop";
555         case SEQ_WIPE:       return "Wipe";
556         case SEQ_GLOW:       return "Glow";
557         case SEQ_TRANSFORM:  return "Transform";
558         case SEQ_COLOR:      return "Color";
559         case SEQ_SPEED:      return "Speed";
560         default:
561                 return 0;
562         }
563 }
564
565 char *give_seqname(Sequence *seq)
566 {
567         char * name = give_seqname_by_type(seq->type);
568
569         if (!name) {
570                 if(seq->type<SEQ_EFFECT) {
571                         return seq->strip->dir;
572                 } else if(seq->type==SEQ_PLUGIN) {
573                         if(!(seq->flag & SEQ_EFFECT_NOT_LOADED) &&
574                            seq->plugin && seq->plugin->doit) {
575                                 return seq->plugin->pname;
576                         } else {
577                                 return "Plugin";
578                         }
579                 } else {
580                         return "Effect";
581                 }
582         }
583         return name;
584 }
585
586 /* ***************** DO THE SEQUENCE ***************** */
587
588 static void make_black_ibuf(ImBuf *ibuf)
589 {
590         unsigned int *rect;
591         float *rect_float;
592         int tot;
593
594         if(ibuf==0 || (ibuf->rect==0 && ibuf->rect_float==0)) return;
595
596         tot= ibuf->x*ibuf->y;
597
598         rect= ibuf->rect;
599         rect_float = ibuf->rect_float;
600
601         if (rect) {
602                 memset(rect,       0, tot * sizeof(char) * 4);
603         }
604
605         if (rect_float) {
606                 memset(rect_float, 0, tot * sizeof(float) * 4);
607         }
608 }
609
610 static void multibuf(ImBuf *ibuf, float fmul)
611 {
612         char *rt;
613         float *rt_float;
614
615         int a, mul, icol;
616
617         mul= (int)(256.0*fmul);
618
619         a= ibuf->x*ibuf->y;
620         rt= (char *)ibuf->rect;
621         rt_float = ibuf->rect_float;
622
623         if (rt) {
624                 while(a--) {
625
626                         icol= (mul*rt[0])>>8;
627                         if(icol>254) rt[0]= 255; else rt[0]= icol;
628                         icol= (mul*rt[1])>>8;
629                         if(icol>254) rt[1]= 255; else rt[1]= icol;
630                         icol= (mul*rt[2])>>8;
631                         if(icol>254) rt[2]= 255; else rt[2]= icol;
632                         icol= (mul*rt[3])>>8;
633                         if(icol>254) rt[3]= 255; else rt[3]= icol;
634                         
635                         rt+= 4;
636                 }
637         }
638         if (rt_float) {
639                 while(a--) {
640                         rt_float[0] *= fmul;
641                         rt_float[1] *= fmul;
642                         rt_float[2] *= fmul;
643                         rt_float[3] *= fmul;
644                         
645                         rt_float += 4;
646                 }
647         }
648 }
649
650 static void do_effect(int cfra, Sequence *seq, TStripElem * se)
651 {
652         TStripElem *se1, *se2, *se3;
653         float fac, facf;
654         int x, y;
655         int early_out;
656         struct SeqEffectHandle sh = get_sequence_effect(seq);
657
658         if (!sh.execute) { /* effect not supported in this version... */
659                 make_black_ibuf(se->ibuf);
660                 return;
661         }
662
663         if(seq->ipo && seq->ipo->curve.first) {
664                 do_seq_ipo(seq, cfra);
665                 fac= seq->facf0;
666                 facf= seq->facf1;
667         } else {
668                 sh.get_default_fac(seq, cfra, &fac, &facf);
669         }
670
671         if( !(G.scene->r.mode & R_FIELDS) ) facf = fac;
672
673         early_out = sh.early_out(seq, fac, facf);
674
675         if (early_out == -1) { /* no input needed */
676                 sh.execute(seq, cfra, fac, facf, 
677                            se->ibuf->x, se->ibuf->y, 
678                            0, 0, 0, se->ibuf);
679                 return;
680         }
681
682         switch (early_out) {
683         case 0:
684                 if (se->se1==0 || se->se2==0 || se->se3==0) {
685                         make_black_ibuf(se->ibuf);
686                         return;
687                 }
688
689                 if(se->se1->ok == STRIPELEM_META) se1= se->se1->se1;
690                 else se1= se->se1;
691                 
692                 if(se->se2->ok == STRIPELEM_META) se2= se->se2->se1;
693                 else se2= se->se2;
694                 
695                 if(se->se3->ok == STRIPELEM_META) se3= se->se3->se1;
696                 else se3= se->se3;
697
698                 if (   (se1==0 || se2==0 || se3==0)
699                     || (se1->ibuf==0 || se2->ibuf==0 || se3->ibuf==0)) {
700                         make_black_ibuf(se->ibuf);
701                         return;
702                 }
703
704                 break;
705         case 1:
706                 if (se->se1 == 0) {
707                         make_black_ibuf(se->ibuf);
708                         return;
709                 }
710
711                 if(se->se1->ok == STRIPELEM_META) se1= se->se1->se1;
712                 else se1= se->se1;
713
714                 if (se1 == 0 || se1->ibuf == 0) {
715                         make_black_ibuf(se->ibuf);
716                         return;
717                 }
718
719                 if (se->ibuf != se1->ibuf) {
720                         IMB_freeImBuf(se->ibuf);
721                         se->ibuf = se1->ibuf;
722                         IMB_refImBuf(se->ibuf);
723                 }
724                 return;
725         case 2:
726                 if (se->se2 == 0) {
727                         make_black_ibuf(se->ibuf);
728                         return;
729                 }
730
731                 if(se->se2->ok == STRIPELEM_META) se2= se->se2->se1;
732                 else se2= se->se2;
733
734                 if (se2 == 0 || se2->ibuf == 0) {
735                         make_black_ibuf(se->ibuf);
736                         return;
737                 }
738                 if (se->ibuf != se2->ibuf) {
739                         IMB_freeImBuf(se->ibuf);
740                         se->ibuf = se2->ibuf;
741                         IMB_refImBuf(se->ibuf);
742                 }
743                 return;
744         default:
745                 make_black_ibuf(se->ibuf);
746                 return;
747         }
748
749         x= se2->ibuf->x;
750         y= se2->ibuf->y;
751
752         if (!se1->ibuf->rect_float && se->ibuf->rect_float) {
753                 IMB_float_from_rect(se1->ibuf);
754         }
755         if (!se2->ibuf->rect_float && se->ibuf->rect_float) {
756                 IMB_float_from_rect(se2->ibuf);
757         }
758
759         if (!se1->ibuf->rect && !se->ibuf->rect_float) {
760                 IMB_rect_from_float(se1->ibuf);
761         }
762         if (!se2->ibuf->rect && !se->ibuf->rect_float) {
763                 IMB_rect_from_float(se2->ibuf);
764         }
765
766         sh.execute(seq, cfra, fac, facf, x, y, se1->ibuf, se2->ibuf, se3->ibuf,
767                    se->ibuf);
768 }
769
770 static int give_stripelem_index(Sequence *seq, int cfra)
771 {
772         int nr;
773
774         if(seq->startdisp >cfra || seq->enddisp <= cfra) return -1;
775
776         if(seq->flag&SEQ_REVERSE_FRAMES)        {       
777                 /*reverse frame in this sequence */
778                 if(cfra <= seq->start) nr= seq->len-1;
779                 else if(cfra >= seq->start+seq->len-1) nr= 0;
780                 else nr= (seq->start + seq->len) - cfra;
781         } else {
782                 if(cfra <= seq->start) nr= 0;
783                 else if(cfra >= seq->start+seq->len-1) nr= seq->len-1;
784                 else nr= cfra-seq->start;
785         }
786         if (seq->strobe < 1.0) seq->strobe = 1.0;
787         if (seq->strobe > 1.0) {
788                 nr -= (int)fmod((double)nr, (double)seq->strobe);
789         }
790
791         return nr;
792 }
793
794 static TStripElem* alloc_tstripdata(int len, const char * name)
795 {
796         int i;
797         TStripElem *se = MEM_callocN(len * sizeof(TStripElem), name);
798         for (i = 0; i < len; i++) {
799                 se[i].ok = STRIPELEM_OK;
800         }
801         return se;
802 }
803
804 TStripElem *give_tstripelem(Sequence *seq, int cfra)
805 {
806         TStripElem *se;
807         int nr;
808
809         se = seq->strip->tstripdata;
810         if (se == 0 && seq->len > 0) {
811                 se = seq->strip->tstripdata = alloc_tstripdata(seq->len,
812                                                                "tstripelems");
813         }
814         nr = give_stripelem_index(seq, cfra);
815
816         if (nr == -1) return 0;
817         if (se == 0) return 0;
818
819         se += nr; 
820
821         /* if there are IPOs with blend modes active, one has to watch out
822            for startstill + endstill area: we can't use the same tstripelem
823            here for all ibufs, since then, blending with IPOs won't work!
824            
825            Rather common case, if you use a single image and try to fade
826            it in and out...
827
828            Performance TODO: seperate give_tstripelem for ibuf from
829            give_tstripelem for ibuf_comp, so that caching works here again...
830         */
831         if (seq->ipo && seq->ipo->curve.first && !(seq->type & SEQ_EFFECT)) {
832                 Strip * s = seq->strip;
833                 if (cfra < seq->start) {
834                         se = s->tstripdata_startstill;
835                         if (seq->startstill > s->startstill) {
836                                 free_tstripdata(s->startstill, 
837                                                 s->tstripdata_startstill);
838                                 se = 0;
839                         }
840
841                         if (se == 0) {
842                                 s->startstill = seq->startstill;
843                                 se = seq->strip->tstripdata_startstill
844                                         = alloc_tstripdata(
845                                                 s->startstill,
846                                                 "tstripelems_startstill");
847                         }
848                         se += seq->start - cfra - 1;
849
850                 } else if (cfra > seq->start + seq->len-1) {
851                         se = s->tstripdata_endstill;
852                         if (seq->endstill > s->endstill) {
853                                 free_tstripdata(s->endstill, 
854                                                 s->tstripdata_endstill);
855                                 se = 0;
856                         }
857
858                         if (se == 0) {
859                                 s->endstill = seq->endstill;
860                                 se = seq->strip->tstripdata_endstill
861                                         = alloc_tstripdata(
862                                                 s->endstill,
863                                                 "tstripelems_endstill");
864                         }
865                         se += cfra - (seq->start + seq->len-1) - 1;
866                 }
867         }
868
869         
870         se->nr= nr;
871
872         return se;
873 }
874
875 StripElem *give_stripelem(Sequence *seq, int cfra)
876 {
877         StripElem *se;
878         int nr;
879
880         se = seq->strip->stripdata;
881         nr = give_stripelem_index(seq, cfra);
882
883         if (nr == -1) return 0;
884         if (se == 0) return 0;
885
886         se += nr + seq->anim_startofs; 
887         
888         return se;
889 }
890
891 static int evaluate_seq_frame_gen(
892         Sequence ** seq_arr, ListBase *seqbase, int cfra)
893 {
894         Sequence *seq;
895         int totseq=0;
896
897         memset(seq_arr, 0, sizeof(Sequence*) * (MAXSEQ+1));
898
899         seq= seqbase->first;
900         while(seq) {
901                 if(seq->startdisp <=cfra && seq->enddisp > cfra) {
902                         seq_arr[seq->machine]= seq;
903                         totseq++;
904                 }
905                 seq= seq->next;
906         }
907
908         return totseq;
909 }
910
911 int evaluate_seq_frame(int cfra)
912 {
913        Editing *ed;
914        Sequence *seq_arr[MAXSEQ+1];
915
916        ed= G.scene->ed;
917        if(ed==0) return 0;
918         
919        return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
920
921 }
922
923 static int video_seq_is_rendered(Sequence * seq)
924 {
925         return (seq 
926                 && !(seq->flag & SEQ_MUTE) 
927                 && seq->type != SEQ_RAM_SOUND 
928                 && seq->type != SEQ_HD_SOUND);
929 }
930
931 static int get_shown_sequences(
932         ListBase * seqbasep, int cfra, int chanshown, Sequence ** seq_arr_out)
933 {
934         Sequence *seq_arr[MAXSEQ+1];
935         int b = chanshown;
936         int cnt = 0;
937
938         if (b > MAXSEQ) {
939                 return 0;
940         }
941
942         if(evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
943                 if (b > 0) {
944                         if (seq_arr[b] == 0) {
945                                 return 0;
946                         }
947                 } else {
948                         for (b = MAXSEQ; b > 0; b--) {
949                                 if (video_seq_is_rendered(seq_arr[b])) {
950                                         break;
951                                 }
952                         }
953                 }
954         }
955         
956         chanshown = b;
957
958         for (;b > 0; b--) {
959                 if (video_seq_is_rendered(seq_arr[b])) {
960                         if (seq_arr[b]->blend_mode == SEQ_BLEND_REPLACE) {
961                                 break;
962                         }
963                 }
964         }
965
966         for (;b <= chanshown; b++) {
967                 if (video_seq_is_rendered(seq_arr[b])) {
968                         seq_arr_out[cnt++] = seq_arr[b];
969                 }
970         }
971
972         return cnt;
973 }
974  
975 static int get_shown_seq_from_metastrip(Sequence * seqm, int cfra,
976                                         Sequence ** seq_arr_out)
977 {
978         return get_shown_sequences(&seqm->seqbase, cfra, 0, seq_arr_out);
979 }
980
981 void set_meta_stripdata(Sequence *seqm)
982 {
983         TStripElem *se;
984         int a, cfra;
985
986         se= seqm->strip->tstripdata;
987
988         if (se == 0 && seqm->len > 0) {
989                 int i;
990                 se = seqm->strip->tstripdata = MEM_callocN(
991                         seqm->len*sizeof(TStripElem), "tstripelems");
992                 for (i = 0; i < seqm->len; i++) {
993                         se[i].ok = STRIPELEM_META;
994                 }
995         }
996
997         /* sets all ->se1 pointers in stripdata, to read the ibuf from it */
998
999         for(a=0; a<seqm->len; a++, se++) {
1000                 int cnt;
1001                 Sequence *seq_arr[MAXSEQ+1];
1002
1003                 cfra= a+seqm->start;
1004                 cnt = get_shown_seq_from_metastrip(seqm, cfra, seq_arr);
1005                 if (cnt) {
1006                         se->se1= give_tstripelem(seq_arr[cnt-1], cfra);
1007                 } else { 
1008                         se->se1= 0;
1009                 }
1010         }
1011 }
1012
1013 /*
1014   input preprocessing for SEQ_IMAGE, SEQ_MOVIE and SEQ_SCENE
1015
1016   Do all the things you can't really do afterwards using sequence effects
1017   (read: before rescaling to render resolution has been done)
1018
1019   Order is important!
1020
1021   - Deinterlace
1022   - Crop and transform in image source coordinate space
1023   - Flip X + Flip Y (could be done afterwards, backward compatibility)
1024   - Promote image to float data (affects pipeline operations afterwards)
1025   - Premultiply
1026
1027 */
1028
1029 static void input_preprocess(Sequence * seq, TStripElem* se, int cfra)
1030 {
1031         float mul;
1032
1033         seq->strip->orx= se->ibuf->x;
1034         seq->strip->ory= se->ibuf->y;
1035
1036         if(seq->flag & SEQ_FILTERY) {
1037                 IMB_filtery(se->ibuf);
1038         }
1039
1040         if(seq->flag & SEQ_USE_CROP || seq->flag & SEQ_USE_TRANSFORM) {
1041                 StripCrop c;
1042                 StripTransform t;
1043
1044                 memset(&c, 0, sizeof(StripCrop));
1045                 memset(&t, 0, sizeof(StripTransform));
1046
1047                 if(seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1048                         c = *seq->strip->crop;
1049                 }
1050                 if(seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1051                         t = *seq->strip->transform;
1052                 }
1053
1054                 if (c.top + c.bottom >= se->ibuf->y ||
1055                     c.left + c.right >= se->ibuf->x ||
1056                     t.xofs >= se->ibuf->x ||
1057                     t.yofs >= se->ibuf->y) {
1058                         make_black_ibuf(se->ibuf);
1059                 } else {
1060                         ImBuf * i;
1061                         int sx = se->ibuf->x - c.left - c.right;
1062                         int sy = se->ibuf->y - c.top - c.bottom;
1063                         int dx = sx;
1064                         int dy = sy;
1065
1066                         if (seq->flag & SEQ_USE_TRANSFORM) {
1067                                 dx = seqrectx;
1068                                 dy = seqrecty;
1069                         }
1070
1071                         if (se->ibuf->rect_float) {
1072                                 i = IMB_allocImBuf(dx, dy,32, IB_rectfloat, 0);
1073                         } else {
1074                                 i = IMB_allocImBuf(dx, dy,32, IB_rect, 0);
1075                         }
1076
1077                         IMB_rectcpy(i, se->ibuf, 
1078                                     t.xofs, t.yofs, 
1079                                     c.left, c.bottom, 
1080                                     sx, sy);
1081
1082                         IMB_freeImBuf(se->ibuf);
1083
1084                         se->ibuf = i;
1085                 }
1086         } 
1087
1088         if(seq->flag & SEQ_FLIPX) {
1089                 IMB_flipx(se->ibuf);
1090         }
1091         if(seq->flag & SEQ_FLIPY) {
1092                 IMB_flipy(se->ibuf);
1093         }
1094
1095         if(seq->flag & SEQ_MAKE_FLOAT) {
1096                 if (!se->ibuf->rect_float) {
1097                         IMB_float_from_rect(se->ibuf);
1098                         imb_freerectImBuf(se->ibuf);
1099                 }
1100         }
1101
1102         if(seq->mul == 0.0) {
1103                 seq->mul = 1.0;
1104         }
1105
1106         mul = seq->mul;
1107
1108         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1109                 if (seq->ipo && seq->ipo->curve.first) {
1110                         do_seq_ipo(seq, cfra);
1111                         mul *= seq->facf0;
1112                 }
1113                 mul *= seq->blend_opacity / 100.0;
1114         }
1115
1116         if(mul != 1.0) {
1117                 multibuf(se->ibuf, mul);
1118         }
1119
1120         if(seq->flag & SEQ_MAKE_PREMUL) {
1121                 if(se->ibuf->depth == 32 && se->ibuf->zbuf == 0) {
1122                         converttopremul(se->ibuf);
1123                 }
1124         }
1125
1126
1127         if(se->ibuf->x != seqrectx || se->ibuf->y != seqrecty ) {
1128                 if(G.scene->r.mode & R_OSA) {
1129                         IMB_scaleImBuf(se->ibuf, 
1130                                        (short)seqrectx, (short)seqrecty);
1131                 } else {
1132                         IMB_scalefastImBuf(se->ibuf, 
1133                                            (short)seqrectx, (short)seqrecty);
1134                 }
1135         }
1136 }
1137
1138 /* test if image too small or discarded from cache: reload */
1139
1140 static void test_and_auto_discard_ibuf(TStripElem * se)
1141 {
1142         if (se->ibuf) {
1143                 if(se->ibuf->x != seqrectx || se->ibuf->y != seqrecty 
1144                    || !(se->ibuf->rect || se->ibuf->rect_float)) {
1145                         IMB_freeImBuf(se->ibuf);
1146
1147                         se->ibuf= 0;
1148                         se->ok= STRIPELEM_OK;
1149                 }
1150         }
1151         if (se->ibuf_comp) {
1152                 if(se->ibuf_comp->x != seqrectx || se->ibuf_comp->y != seqrecty 
1153                    || !(se->ibuf_comp->rect || se->ibuf_comp->rect_float)) {
1154                         IMB_freeImBuf(se->ibuf_comp);
1155
1156                         se->ibuf_comp = 0;
1157                 }
1158         }
1159 }
1160
1161 static TStripElem* do_build_seq_array_recursively(
1162         ListBase *seqbasep, int cfra, int chanshown);
1163
1164 static void do_build_seq_ibuf(Sequence * seq, TStripElem *se, int cfra)
1165 {
1166         char name[FILE_MAXDIR+FILE_MAXFILE];
1167
1168
1169         if (seq->type != SEQ_META) {
1170                 test_and_auto_discard_ibuf(se);
1171         }
1172
1173         if(seq->type == SEQ_META) {
1174                 if(seq->seqbase.first) {
1175                         if(cfra < seq->start) {
1176                                 do_build_seq_array_recursively(
1177                                         &seq->seqbase, 
1178                                         seq->start, 0);
1179                         } else if(cfra > seq->start + seq->len - 1) {
1180                                 do_build_seq_array_recursively(
1181                                         &seq->seqbase, 
1182                                         seq->start + seq->len - 1, 0);
1183                         } else {
1184                                 do_build_seq_array_recursively(
1185                                         &seq->seqbase, 
1186                                         cfra, 0);
1187                         }
1188                 }
1189
1190                 se->ok = STRIPELEM_META;
1191                 if(se->se1 == 0) set_meta_stripdata(seq);
1192                 if(se->se1) {
1193                         if(se->ibuf) {
1194                                 IMB_freeImBuf(se->ibuf);
1195                         }
1196                         se->ibuf = se->se1->ibuf_comp;
1197                         if(se->ibuf) {
1198                                 IMB_refImBuf(se->ibuf);
1199                         }
1200                 }
1201         } else if(seq->type & SEQ_EFFECT) {
1202                 /* should the effect be recalculated? */
1203                 
1204                 if(se->ibuf == 0) {
1205                         /* if one of two first inputs are rectfloat, output is float too */
1206                         if((se->se1 && se->se1->ibuf && se->se1->ibuf->rect_float) ||
1207                            (se->se2 && se->se2->ibuf && se->se2->ibuf->rect_float))
1208                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
1209                         else
1210                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
1211                         
1212                         do_effect(cfra, seq, se);
1213                 }
1214
1215         } else if(seq->type < SEQ_EFFECT) {
1216                 
1217                 if(seq->type==SEQ_IMAGE) {
1218                         if(se->ok == STRIPELEM_OK && se->ibuf==0) {
1219                                 StripElem * s_elem = give_stripelem(seq, cfra);
1220
1221                                 strncpy(name, seq->strip->dir, FILE_MAXDIR-1);
1222                                 strncat(name, s_elem->name, FILE_MAXFILE);
1223                                 BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
1224                                 se->ibuf= IMB_loadiffname(name, IB_rect);
1225                                 
1226                                 if(se->ibuf == 0) {
1227                                         se->ok = STRIPELEM_FAILED;
1228                                 } else {
1229                                         input_preprocess(seq, se, cfra);
1230                                 }
1231                         }
1232                 }
1233                 else if(seq->type==SEQ_MOVIE) {
1234                         if(se->ok == STRIPELEM_OK && se->ibuf==0) {
1235                                 if(seq->anim==0) {
1236                                         strncpy(name, seq->strip->dir, FILE_MAXDIR-1);
1237                                         strncat(name, seq->strip->stripdata->name, FILE_MAXFILE-1);
1238                                         BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
1239                                         
1240                                         seq->anim = openanim(name, IB_rect);
1241                                 }
1242                                 if(seq->anim) {
1243                                         IMB_anim_set_preseek(seq->anim, seq->anim_preseek);
1244                                         se->ibuf = IMB_anim_absolute(seq->anim, se->nr + seq->anim_startofs);
1245                                 }
1246                                 
1247                                 if(se->ibuf == 0) {
1248                                         se->ok = STRIPELEM_FAILED;
1249                                 } else {
1250                                         input_preprocess(seq, se, cfra);
1251                                 }
1252                         }
1253                 } else if(seq->type==SEQ_SCENE && se->ibuf==NULL && seq->scene) {       // scene can be NULL after deletions
1254                         int oldcfra = CFRA;
1255                         Scene *sce= seq->scene, *oldsce= G.scene;
1256                         Render *re;
1257                         RenderResult rres;
1258                         int doseq, rendering= G.rendering;
1259                         char scenename[64];
1260                         
1261                         waitcursor(1);
1262                         
1263                         /* Hack! This function can be called from do_render_seq(), in that case
1264                            the seq->scene can already have a Render initialized with same name, 
1265                            so we have to use a default name. (compositor uses G.scene name to
1266                            find render).
1267                            However, when called from within the UI (image preview in sequencer)
1268                            we do want to use scene Render, that way the render result is defined
1269                            for display in render/imagewindow */
1270                         if(rendering) {
1271                                 BLI_strncpy(scenename, sce->id.name+2, 64);
1272                                 strcpy(sce->id.name+2, " do_build_seq_ibuf");
1273                         }
1274                         re= RE_NewRender(sce->id.name);
1275                         
1276                         /* prevent eternal loop */
1277                         doseq= G.scene->r.scemode & R_DOSEQ;
1278                         G.scene->r.scemode &= ~R_DOSEQ;
1279                         
1280                         BIF_init_render_callbacks(re, 0);       /* 0= no display callbacks */
1281                         
1282                         /* hrms, set_scene still needed? work on that... */
1283                         if(sce!=oldsce) set_scene_bg(sce);
1284                         RE_BlenderFrame(re, sce,
1285                                         seq->sfra+se->nr+seq->anim_startofs);
1286                         if(sce!=oldsce) set_scene_bg(oldsce);
1287                         
1288                         /* UGLY WARNING, it is set to zero in  RE_BlenderFrame */
1289                         G.rendering= rendering;
1290                         if(rendering)
1291                                 BLI_strncpy(sce->id.name+2, scenename, 64);
1292                         
1293                         RE_GetResultImage(re, &rres);
1294                         
1295                         if(rres.rectf) {
1296                                 se->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat, 0);
1297                                 memcpy(se->ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
1298                                 if(rres.rectz) {
1299                                         addzbuffloatImBuf(se->ibuf);
1300                                         memcpy(se->ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
1301                                 }
1302                         } else if (rres.rect32) {
1303                                 se->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect, 0);
1304                                 memcpy(se->ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
1305                         }
1306                         
1307                         BIF_end_render_callbacks();
1308                         
1309                         /* restore */
1310                         G.scene->r.scemode |= doseq;
1311                         
1312                         if((G.f & G_PLAYANIM)==0) /* bad, is set on do_render_seq */
1313                                 waitcursor(0);
1314                         CFRA = oldcfra;
1315
1316                         input_preprocess(seq, se, cfra);
1317                 }       
1318         }
1319         if (se->ibuf && seq->type != SEQ_META) {
1320                 IMB_cache_limiter_insert(se->ibuf);
1321                 IMB_cache_limiter_ref(se->ibuf);
1322                 IMB_cache_limiter_touch(se->ibuf);
1323         }
1324 }
1325
1326 static TStripElem* do_build_seq_recursively(Sequence * seq, int cfra);
1327
1328 static void do_effect_seq_recursively(Sequence * seq, TStripElem *se, int cfra)
1329 {
1330         float fac, facf;
1331         struct SeqEffectHandle sh = get_sequence_effect(seq);
1332         int early_out;
1333
1334         se->se1 = 0;
1335         se->se2 = 0;
1336         se->se3 = 0;
1337
1338         if(seq->ipo && seq->ipo->curve.first) {
1339                 do_seq_ipo(seq, cfra);
1340                 fac= seq->facf0;
1341                 facf= seq->facf1;
1342         } else {
1343                 sh.get_default_fac(seq, cfra, &fac, &facf);
1344         } 
1345
1346         if( G.scene->r.mode & R_FIELDS ); else facf= fac;
1347         
1348         early_out = sh.early_out(seq, fac, facf);
1349         switch (early_out) {
1350         case -1:
1351                 /* no input needed */
1352                 break;
1353         case 0:
1354                 se->se1 = do_build_seq_recursively(seq->seq1, cfra);
1355                 se->se2 = do_build_seq_recursively(seq->seq2, cfra);
1356                 if (seq->seq3) {
1357                         se->se3 = do_build_seq_recursively(seq->seq3, cfra);
1358                 }
1359                 break;
1360         case 1:
1361                 se->se1 = do_build_seq_recursively(seq->seq1, cfra);
1362                 break;
1363         case 2:
1364                 se->se2 = do_build_seq_recursively(seq->seq2, cfra);
1365                 break;
1366         }
1367
1368
1369         do_build_seq_ibuf(seq, se, cfra);
1370
1371         /* children are not needed anymore ... */
1372
1373         if (se->se1 && se->se1->ibuf) {
1374                 IMB_cache_limiter_unref(se->se1->ibuf);
1375         }
1376         if (se->se2 && se->se2->ibuf) {
1377                 IMB_cache_limiter_unref(se->se2->ibuf);
1378         }
1379         if (se->se3 && se->se3->ibuf) {
1380                 IMB_cache_limiter_unref(se->se3->ibuf);
1381         }
1382 }
1383
1384 static TStripElem* do_build_seq_recursively_impl(Sequence * seq, int cfra)
1385 {
1386         TStripElem *se;
1387
1388         se = give_tstripelem(seq, cfra);
1389
1390         if(se) {
1391                 if (seq->type & SEQ_EFFECT) {
1392                         do_effect_seq_recursively(seq, se, cfra);
1393                 } else {
1394                         do_build_seq_ibuf(seq, se, cfra);
1395                 }
1396         }
1397         return se;
1398 }
1399
1400 /* FIXME:
1401    
1402 If cfra was float throughout blender (especially in the render
1403 pipeline) one could even _render_ with subframe precision
1404 instead of faking using the blend code below...
1405
1406 */
1407
1408 static TStripElem* do_handle_speed_effect(Sequence * seq, int cfra)
1409 {
1410         SpeedControlVars * s = (SpeedControlVars *)seq->effectdata;
1411         int nr = cfra - seq->start;
1412         float f_cfra;
1413         int cfra_left;
1414         int cfra_right;
1415         TStripElem * se = 0;
1416         TStripElem * se1 = 0;
1417         TStripElem * se2 = 0;
1418         
1419         sequence_effect_speed_rebuild_map(seq, 0);
1420         
1421         f_cfra = seq->start + s->frameMap[nr];
1422         
1423         cfra_left = (int) floor(f_cfra);
1424         cfra_right = (int) ceil(f_cfra);
1425
1426         se = give_tstripelem(seq, cfra);
1427
1428         if (cfra_left == cfra_right || 
1429             (s->flags & SEQ_SPEED_BLEND) == 0) {
1430                 test_and_auto_discard_ibuf(se);
1431
1432                 if (se->ibuf == NULL) {
1433                         se1 = do_build_seq_recursively_impl(
1434                                 seq->seq1, cfra_left);
1435
1436                         if((se1 && se1->ibuf && se1->ibuf->rect_float))
1437                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
1438                         else
1439                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
1440
1441                         if (se1 == 0 || se1->ibuf == 0) {
1442                                 make_black_ibuf(se->ibuf);
1443                         } else {
1444                                 if (se->ibuf != se1->ibuf) {
1445                                         if (se->ibuf) {
1446                                                 IMB_freeImBuf(se->ibuf);
1447                                         }
1448
1449                                         se->ibuf = se1->ibuf;
1450                                         IMB_refImBuf(se->ibuf);
1451                                 }
1452                         }
1453                 }
1454         } else {
1455                 struct SeqEffectHandle sh;
1456
1457                 if(se->ibuf) {
1458                         if(se->ibuf->x < seqrectx || se->ibuf->y < seqrecty 
1459                            || !(se->ibuf->rect || se->ibuf->rect_float)) {
1460                                 IMB_freeImBuf(se->ibuf);
1461                                 se->ibuf= 0;
1462                         }
1463                 }
1464
1465                 if (se->ibuf == NULL) {
1466                         se1 = do_build_seq_recursively_impl(
1467                                 seq->seq1, cfra_left);
1468                         se2 = do_build_seq_recursively_impl(
1469                                 seq->seq1, cfra_right);
1470
1471                         if((se1 && se1->ibuf && se1->ibuf->rect_float))
1472                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
1473                         else
1474                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
1475                         
1476                         if (!se1 || !se2) {
1477                                 make_black_ibuf(se->ibuf);
1478                         } else {
1479                                 sh = get_sequence_effect(seq);
1480
1481                                 sh.execute(seq, cfra, 
1482                                            f_cfra - (float) cfra_left, 
1483                                            f_cfra - (float) cfra_left, 
1484                                            se->ibuf->x, se->ibuf->y, 
1485                                            se1->ibuf, se2->ibuf, 0, se->ibuf);
1486                         }
1487                 }
1488
1489         }
1490
1491         /* caller expects this to be referenced, so do it! */
1492         if (se->ibuf) {
1493                 IMB_cache_limiter_insert(se->ibuf);
1494                 IMB_cache_limiter_ref(se->ibuf);
1495                 IMB_cache_limiter_touch(se->ibuf);
1496         }
1497
1498         /* children are no longer needed */
1499         if (se1 && se1->ibuf)
1500                 IMB_cache_limiter_unref(se1->ibuf);
1501         if (se2 && se2->ibuf)
1502                 IMB_cache_limiter_unref(se2->ibuf);
1503
1504         return se;
1505 }
1506
1507 /* 
1508  * build all ibufs recursively
1509  * 
1510  * if successfull, the returned TStripElem contains the (referenced!) imbuf
1511  * that means: you _must_ call 
1512  *
1513  * IMB_cache_limiter_unref(rval);
1514  * 
1515  * if rval != 0
1516  * 
1517  */
1518
1519 static TStripElem* do_build_seq_recursively(Sequence * seq, int cfra)
1520 {
1521         if (seq->type == SEQ_SPEED) {
1522                 return do_handle_speed_effect(seq, cfra);
1523         } else {
1524                 return do_build_seq_recursively_impl(seq, cfra);
1525         }
1526 }
1527
1528 static TStripElem* do_build_seq_array_recursively(
1529         ListBase *seqbasep, int cfra, int chanshown)
1530 {
1531         Sequence* seq_arr[MAXSEQ+1];
1532         int count;
1533         int i;
1534         TStripElem* se = 0;
1535
1536         count = get_shown_sequences(seqbasep, cfra, chanshown, &seq_arr);
1537
1538         if (!count) {
1539                 return 0;
1540         }
1541
1542         se = give_tstripelem(seq_arr[count - 1], cfra);
1543
1544         test_and_auto_discard_ibuf(se);
1545
1546         if (se->ibuf_comp != 0) {
1547                 IMB_cache_limiter_insert(se->ibuf_comp);
1548                 IMB_cache_limiter_ref(se->ibuf_comp);
1549                 IMB_cache_limiter_touch(se->ibuf_comp);
1550                 return se;
1551         }
1552
1553         
1554         if(count == 1) {
1555                 se = do_build_seq_recursively(seq_arr[0], cfra);
1556                 if (se->ibuf) {
1557                         se->ibuf_comp = se->ibuf;
1558                         IMB_refImBuf(se->ibuf_comp);
1559                 }
1560                 return se;
1561         }
1562
1563
1564         for (i = count - 1; i >= 0; i--) {
1565                 int early_out;
1566                 Sequence * seq = seq_arr[i];
1567                 struct SeqEffectHandle sh;
1568
1569                 se = give_tstripelem(seq, cfra);
1570
1571                 test_and_auto_discard_ibuf(se);
1572
1573                 if (se->ibuf_comp != 0) {
1574                         break;
1575                 }
1576                 if (seq->blend_mode == SEQ_BLEND_REPLACE) {
1577                         do_build_seq_recursively(seq, cfra);
1578                         if (se->ibuf) {
1579                                 se->ibuf_comp = se->ibuf;
1580                                 IMB_refImBuf(se->ibuf);
1581                         } else {
1582                                 se->ibuf_comp = IMB_allocImBuf(
1583                                         (short)seqrectx, (short)seqrecty, 
1584                                         32, IB_rect, 0);
1585                         }
1586                         break;
1587                 }
1588
1589                 sh = get_sequence_blend(seq);
1590
1591                 seq->facf0 = seq->facf1 = 1.0;
1592
1593                 if(seq->ipo && seq->ipo->curve.first) {
1594                         do_seq_ipo(seq, cfra);
1595                 } 
1596
1597                 if( G.scene->r.mode & R_FIELDS ); else seq->facf0 = seq->facf1;
1598
1599                 seq->facf0 *= seq->blend_opacity / 100.0;
1600                 seq->facf1 *= seq->blend_opacity / 100.0;
1601
1602                 early_out = sh.early_out(seq, seq->facf0, seq->facf1);
1603
1604                 switch (early_out) {
1605                 case -1:
1606                 case 2:
1607                         do_build_seq_recursively(seq, cfra);
1608                         if (se->ibuf) {
1609                                 se->ibuf_comp = se->ibuf;
1610                                 IMB_refImBuf(se->ibuf_comp);
1611                         } else {
1612                                 se->ibuf_comp = IMB_allocImBuf(
1613                                         (short)seqrectx, (short)seqrecty, 
1614                                         32, IB_rect, 0);
1615                         }
1616                         break;
1617                 case 1:
1618                         if (i == 0) {
1619                                 se->ibuf_comp = IMB_allocImBuf(
1620                                         (short)seqrectx, (short)seqrecty, 
1621                                         32, IB_rect, 0);
1622                                 IMB_cache_limiter_insert(se->ibuf_comp);
1623                                 IMB_cache_limiter_ref(se->ibuf_comp);
1624                                 IMB_cache_limiter_touch(se->ibuf_comp);
1625                         }
1626                         break;
1627                 case 0:
1628                         do_build_seq_recursively(seq, cfra);
1629                         if (!se->ibuf) {
1630                                 se->ibuf = IMB_allocImBuf(
1631                                         (short)seqrectx, (short)seqrecty, 
1632                                         32, IB_rect, 0);
1633                         }
1634                         if (i == 0) {
1635                                 se->ibuf_comp = se->ibuf;
1636                                 IMB_refImBuf(se->ibuf_comp);
1637                         }
1638                         break;
1639                 }
1640         
1641                 if (se->ibuf_comp) {
1642                         break;
1643                 }
1644         }
1645
1646         i++;
1647
1648         for (; i < count; i++) {
1649                 Sequence * seq = seq_arr[i];
1650                 struct SeqEffectHandle sh = get_sequence_blend(seq);
1651                 TStripElem* se1 = give_tstripelem(seq_arr[i-1], cfra);
1652                 TStripElem* se2 = give_tstripelem(seq_arr[i], cfra);
1653         
1654                 int early_out = sh.early_out(seq, seq->facf0, seq->facf1);
1655                 switch (early_out) {
1656                 case 0: {
1657                         int x= se2->ibuf->x;
1658                         int y= se2->ibuf->y;
1659                         int swap_input = FALSE;
1660
1661                         if (se1->ibuf_comp->rect_float ||
1662                             se2->ibuf->rect_float) {
1663                                 se2->ibuf_comp = IMB_allocImBuf(
1664                                         (short)seqrectx, (short)seqrecty, 
1665                                         32, IB_rectfloat, 0);
1666                         } else {
1667                                 se2->ibuf_comp = IMB_allocImBuf(
1668                                         (short)seqrectx, (short)seqrecty, 
1669                                         32, IB_rect, 0);
1670                         }
1671
1672
1673                         if (!se1->ibuf_comp->rect_float && 
1674                             se2->ibuf_comp->rect_float) {
1675                                 IMB_float_from_rect(se1->ibuf_comp);
1676                         }
1677                         if (!se2->ibuf->rect_float && 
1678                             se2->ibuf_comp->rect_float) {
1679                                 IMB_float_from_rect(se2->ibuf);
1680                         }
1681
1682                         if (!se1->ibuf_comp->rect && 
1683                             !se2->ibuf_comp->rect_float) {
1684                                 IMB_rect_from_float(se1->ibuf_comp);
1685                         }
1686                         if (!se2->ibuf->rect && 
1687                             !se2->ibuf_comp->rect_float) {
1688                                 IMB_rect_from_float(se2->ibuf);
1689                         }
1690
1691                         /* bad hack, to fix crazy input ordering of 
1692                            those two effects */
1693
1694                         if (seq->blend_mode == SEQ_ALPHAOVER ||
1695                             seq->blend_mode == SEQ_ALPHAUNDER ||
1696                             seq->blend_mode == SEQ_OVERDROP) {
1697                                 swap_input = TRUE;
1698                         }
1699
1700                         if (swap_input) {
1701                                 sh.execute(seq, cfra, 
1702                                            seq->facf0, seq->facf1, x, y, 
1703                                            se2->ibuf, se1->ibuf_comp, 0,
1704                                            se2->ibuf_comp);
1705                         } else {
1706                                 sh.execute(seq, cfra, 
1707                                            seq->facf0, seq->facf1, x, y, 
1708                                            se1->ibuf_comp, se2->ibuf, 0,
1709                                            se2->ibuf_comp);
1710                         }
1711                         
1712                         IMB_cache_limiter_insert(se2->ibuf_comp);
1713                         IMB_cache_limiter_ref(se2->ibuf_comp);
1714                         IMB_cache_limiter_touch(se2->ibuf_comp);
1715
1716                         IMB_cache_limiter_unref(se1->ibuf_comp);
1717                         IMB_cache_limiter_unref(se2->ibuf);
1718
1719                         break;
1720                 }
1721                 case 1: {
1722                         se2->ibuf_comp = se1->ibuf;
1723                         IMB_refImBuf(se2->ibuf_comp);
1724
1725                         break;
1726                 }
1727                 }
1728                 se = se2;
1729         }
1730
1731         return se;
1732 }
1733
1734 /*
1735  * returned ImBuf is refed!
1736  * you have to unref after usage!
1737  */
1738
1739 static ImBuf *give_ibuf_seq_impl(int rectx, int recty, int cfra, int chanshown)
1740 {
1741         Editing *ed;
1742         int count;
1743         ListBase *seqbasep;
1744         TStripElem *se;
1745
1746         ed= G.scene->ed;
1747         if(ed==0) return 0;
1748
1749         count = BLI_countlist(&ed->metastack);
1750         if((chanshown < 0) && (count > 0)) {
1751                 count = MAX2(count + chanshown, 0);
1752                 seqbasep= ((MetaStack*)BLI_findlink(&ed->metastack, count))->oldbasep;
1753         } else {
1754                 seqbasep= ed->seqbasep;
1755         }
1756
1757         seqrectx= rectx;        /* bad bad global! */
1758         seqrecty= recty;
1759
1760         se = do_build_seq_array_recursively(seqbasep, cfra, chanshown);
1761
1762         if(!se) { 
1763                 return 0;
1764         }
1765
1766         return se->ibuf_comp;
1767 }
1768
1769 ImBuf *give_ibuf_seq_direct(int rectx, int recty, int cfra,
1770                             Sequence * seq)
1771 {
1772         TStripElem* se;
1773
1774         seqrectx= rectx;        /* bad bad global! */
1775         seqrecty= recty;
1776
1777         se = do_build_seq_recursively(seq, cfra);
1778
1779         if(!se) { 
1780                 return 0;
1781         }
1782
1783         if (se->ibuf) {
1784                 IMB_cache_limiter_unref(se->ibuf);
1785         }
1786
1787         return se->ibuf;
1788 }
1789
1790 ImBuf *give_ibuf_seq(int rectx, int recty, int cfra, int chanshown)
1791 {
1792         ImBuf* i = give_ibuf_seq_impl(rectx, recty, cfra, chanshown);
1793
1794         if (i) {
1795                 IMB_cache_limiter_unref(i);
1796         }
1797         return i;
1798 }
1799
1800 /* threading api */
1801
1802 static ListBase running_threads;
1803 static ListBase prefetch_wait;
1804 static ListBase prefetch_done;
1805
1806 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
1807 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
1808 static pthread_cond_t  wakeup_cond         = PTHREAD_COND_INITIALIZER;
1809
1810 static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
1811 static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
1812
1813 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
1814 static pthread_cond_t  frame_done_cond     = PTHREAD_COND_INITIALIZER;
1815
1816 static volatile int seq_thread_shutdown = FALSE;
1817 static volatile int seq_last_given_monoton_cfra = 0;
1818 static int monoton_cfra = 0;
1819
1820 typedef struct PrefetchThread {
1821         struct PrefetchThread *next, *prev;
1822         struct PrefetchQueueElem *current;
1823         pthread_t pthread;
1824         int running;
1825 } PrefetchThread;
1826
1827 typedef struct PrefetchQueueElem {
1828         struct PrefetchQueueElem *next, *prev;
1829         
1830         int rectx;
1831         int recty;
1832         int cfra;
1833         int chanshown;
1834
1835         int monoton_cfra;
1836
1837         struct ImBuf * ibuf;
1838 } PrefetchQueueElem;
1839
1840 static void * seq_prefetch_thread(void * This_)
1841 {
1842         PrefetchThread * This = This_;
1843
1844         while (!seq_thread_shutdown) {
1845                 PrefetchQueueElem * e;
1846                 int s_last;
1847
1848                 pthread_mutex_lock(&queue_lock);
1849                 e = prefetch_wait.first;
1850                 if (e) {
1851                         BLI_remlink(&prefetch_wait, e);
1852                 }
1853                 s_last = seq_last_given_monoton_cfra;
1854
1855                 This->current = e;
1856
1857                 pthread_mutex_unlock(&queue_lock);
1858
1859                 if (!e) {
1860                         pthread_mutex_lock(&prefetch_ready_lock);
1861
1862                         This->running = FALSE;
1863
1864                         pthread_cond_signal(&prefetch_ready_cond);
1865                         pthread_mutex_unlock(&prefetch_ready_lock);
1866
1867                         pthread_mutex_lock(&wakeup_lock);
1868                         if (!seq_thread_shutdown) {
1869                                 pthread_cond_wait(&wakeup_cond, &wakeup_lock);
1870                         }
1871                         pthread_mutex_unlock(&wakeup_lock);
1872                         continue;
1873                 }
1874
1875                 This->running = TRUE;
1876                 
1877                 if (e->cfra >= s_last) { 
1878                         e->ibuf = give_ibuf_seq_impl(
1879                                 e->rectx, e->recty, e->cfra, e->chanshown);
1880                 }
1881
1882                 pthread_mutex_lock(&queue_lock);
1883
1884                 BLI_addtail(&prefetch_done, e);
1885
1886                 for (e = prefetch_wait.first; e; e = e->next) {
1887                         if (s_last > e->monoton_cfra) {
1888                                 BLI_remlink(&prefetch_wait, e);
1889                                 MEM_freeN(e);
1890                         }
1891                 }
1892
1893                 for (e = prefetch_done.first; e; e = e->next) {
1894                         if (s_last > e->monoton_cfra) {
1895                                 if (e->ibuf) {
1896                                         IMB_cache_limiter_unref(e->ibuf);
1897                                 }
1898                                 BLI_remlink(&prefetch_done, e);
1899                                 MEM_freeN(e);
1900                         }
1901                 }
1902
1903                 pthread_mutex_unlock(&queue_lock);
1904
1905                 pthread_mutex_lock(&frame_done_lock);
1906                 pthread_cond_signal(&frame_done_cond);
1907                 pthread_mutex_unlock(&frame_done_lock);
1908         }
1909         return 0;
1910 }
1911
1912 void seq_start_threads()
1913 {
1914         int i;
1915
1916         running_threads.first = running_threads.last = NULL;
1917         prefetch_wait.first = prefetch_wait.last = NULL;
1918         prefetch_done.first = prefetch_done.last = NULL;
1919
1920         seq_thread_shutdown = FALSE;
1921         seq_last_given_monoton_cfra = monoton_cfra = 0;
1922
1923         /* since global structures are modified during the processing
1924            of one frame, only one render thread is currently possible... 
1925
1926            (but we code, in the hope, that we can remove this restriction
1927            soon...)
1928         */
1929
1930         fprintf(stderr, "SEQ-THREAD: seq_start_threads\n");
1931
1932         for (i = 0; i < 1; i++) {
1933                 PrefetchThread *t = MEM_callocN(sizeof(PrefetchThread), 
1934                                                 "prefetch_thread");
1935                 t->running = TRUE;
1936                 BLI_addtail(&running_threads, t);
1937
1938                 pthread_create(&t->pthread, NULL, seq_prefetch_thread, t);
1939         }
1940
1941         /* init malloc mutex */
1942         BLI_init_threads(0, 0, 0);
1943 }
1944
1945 void seq_stop_threads()
1946 {
1947         PrefetchThread *tslot;
1948         PrefetchQueueElem * e;
1949
1950         fprintf(stderr, "SEQ-THREAD: seq_stop_threads()\n");
1951
1952         if (seq_thread_shutdown) {
1953                 fprintf(stderr, "SEQ-THREAD: ... already stopped\n");
1954                 return;
1955         }
1956         
1957         pthread_mutex_lock(&wakeup_lock);
1958
1959         seq_thread_shutdown = TRUE;
1960
1961         pthread_cond_broadcast(&wakeup_cond);
1962         pthread_mutex_unlock(&wakeup_lock);
1963
1964         for(tslot = running_threads.first; tslot; tslot= tslot->next) {
1965                 pthread_join(tslot->pthread, NULL);
1966         }
1967
1968
1969         for (e = prefetch_wait.first; e; e = e->next) {
1970                 BLI_remlink(&prefetch_wait, e);
1971                 MEM_freeN(e);
1972         }
1973
1974         for (e = prefetch_done.first; e; e = e->next) {
1975                 if (e->ibuf) {
1976                         IMB_cache_limiter_unref(e->ibuf);
1977                 }
1978                 BLI_remlink(&prefetch_done, e);
1979                 MEM_freeN(e);
1980         }
1981
1982         BLI_freelistN(&running_threads);
1983
1984         /* deinit malloc mutex */
1985         BLI_end_threads(0);
1986 }
1987
1988 void give_ibuf_prefetch_request(int rectx, int recty, int cfra, int chanshown)
1989 {
1990         PrefetchQueueElem * e;
1991         if (seq_thread_shutdown) {
1992                 return;
1993         }
1994
1995         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
1996         e->rectx = rectx;
1997         e->recty = recty;
1998         e->cfra = cfra;
1999         e->chanshown = chanshown;
2000         e->monoton_cfra = monoton_cfra++;
2001
2002         pthread_mutex_lock(&queue_lock);
2003         BLI_addtail(&prefetch_wait, e);
2004         pthread_mutex_unlock(&queue_lock);
2005         
2006         pthread_mutex_lock(&wakeup_lock);
2007         pthread_cond_signal(&wakeup_cond);
2008         pthread_mutex_unlock(&wakeup_lock);
2009 }
2010
2011 void seq_wait_for_prefetch_ready()
2012 {
2013         PrefetchThread *tslot;
2014
2015         if (seq_thread_shutdown) {
2016                 return;
2017         }
2018
2019         fprintf(stderr, "SEQ-THREAD: rendering prefetch frames...\n");
2020
2021         pthread_mutex_lock(&prefetch_ready_lock);
2022
2023         for(;;) {
2024                 for(tslot = running_threads.first; tslot; tslot= tslot->next) {
2025                         if (tslot->running) {
2026                                 break;
2027                         }
2028                 }
2029                 if (!tslot) {
2030                         break;
2031                 }
2032                 pthread_cond_wait(&prefetch_ready_cond, &prefetch_ready_lock);
2033         }
2034
2035         pthread_mutex_unlock(&prefetch_ready_lock);
2036
2037         fprintf(stderr, "SEQ-THREAD: prefetch done\n");
2038 }
2039
2040 ImBuf * give_ibuf_seq_threaded(int rectx, int recty, int cfra, int chanshown)
2041 {
2042         PrefetchQueueElem * e = 0;
2043         int found_something = FALSE;
2044
2045         if (seq_thread_shutdown) {
2046                 return give_ibuf_seq(rectx, recty, cfra, chanshown);
2047         }
2048
2049         while (!e) {
2050                 int success = FALSE;
2051                 pthread_mutex_lock(&queue_lock);
2052
2053                 for (e = prefetch_done.first; e; e = e->next) {
2054                         if (cfra == e->cfra &&
2055                             chanshown == e->chanshown &&
2056                             rectx == e->rectx && 
2057                             recty == e->recty) {
2058                                 success = TRUE;
2059                                 found_something = TRUE;
2060                                 break;
2061                         }
2062                 }
2063
2064                 if (!e) {
2065                         for (e = prefetch_wait.first; e; e = e->next) {
2066                                 if (cfra == e->cfra &&
2067                                     chanshown == e->chanshown &&
2068                                     rectx == e->rectx && 
2069                                     recty == e->recty) {
2070                                         found_something = TRUE;
2071                                         break;
2072                                 }
2073                         }
2074                 }
2075
2076                 if (!e) {
2077                         PrefetchThread *tslot;
2078
2079                         for(tslot = running_threads.first; 
2080                             tslot; tslot= tslot->next) {
2081                                 if (tslot->current &&
2082                                     cfra == tslot->current->cfra &&
2083                                     chanshown == tslot->current->chanshown &&
2084                                     rectx == tslot->current->rectx && 
2085                                     recty == tslot->current->recty) {
2086                                         found_something = TRUE;
2087                                         break;
2088                                 }
2089                         }
2090                 }
2091
2092                 /* e->ibuf is unrefed by render thread on next round. */
2093
2094                 if (e) {
2095                         seq_last_given_monoton_cfra = e->monoton_cfra;
2096                 }
2097
2098                 pthread_mutex_unlock(&queue_lock);
2099
2100                 if (!success) {
2101                         e = NULL;
2102
2103                         if (!found_something) {
2104                                 fprintf(stderr, 
2105                                         "SEQ-THREAD: Requested frame "
2106                                         "not in queue ???\n");
2107                                 break;
2108                         }
2109                         pthread_mutex_lock(&frame_done_lock);
2110                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
2111                         pthread_mutex_unlock(&frame_done_lock);
2112                 }
2113         }
2114         
2115         return e ? e->ibuf : 0;
2116 }
2117
2118 /* Functions to free imbuf and anim data on changes */
2119
2120 static void free_imbuf_strip_elem(TStripElem *se)
2121 {
2122         if(se->ibuf) {
2123                 IMB_freeImBuf(se->ibuf);
2124         }
2125         if(se->ibuf_comp) {
2126                 IMB_freeImBuf(se->ibuf_comp);
2127         }
2128         se->ibuf_comp = 0;
2129         se->ibuf= 0;
2130         se->ok= STRIPELEM_OK;
2131         se->se1= se->se2= se->se3= 0;
2132 }
2133
2134 static void free_anim_seq(Sequence *seq)
2135 {
2136         if(seq->anim) {
2137                 IMB_free_anim(seq->anim);
2138                 seq->anim = 0;
2139         }
2140 }
2141
2142 void free_imbuf_seq_except(int cfra)
2143 {
2144         Editing *ed= G.scene->ed;
2145         Sequence *seq;
2146         TStripElem *se;
2147         int a;
2148
2149         if(ed==0) return;
2150
2151         WHILE_SEQ(&ed->seqbase) {
2152                 if(seq->strip) {
2153                         TStripElem * curelem = give_tstripelem(seq, cfra);
2154
2155                         for(a = 0, se = seq->strip->tstripdata; 
2156                             a < seq->strip->len && se; a++, se++) {
2157                                 if(se != curelem) {
2158                                         free_imbuf_strip_elem(se);
2159                                 }
2160                         }
2161                         for(a = 0, se = seq->strip->tstripdata_startstill;
2162                             a < seq->strip->startstill && se; a++, se++) {
2163                                 if(se != curelem) {
2164                                         free_imbuf_strip_elem(se);
2165                                 }
2166                         }
2167                         for(a = 0, se = seq->strip->tstripdata_endstill;
2168                             a < seq->strip->endstill && se; a++, se++) {
2169                                 if(se != curelem) {
2170                                         free_imbuf_strip_elem(se);
2171                                 }
2172                         }
2173
2174                         if(seq->type==SEQ_MOVIE)
2175                                 if(seq->startdisp > cfra || seq->enddisp < cfra)
2176                                         free_anim_seq(seq);
2177                 }
2178         }
2179         END_SEQ
2180 }
2181
2182 void free_imbuf_seq()
2183 {
2184         Editing *ed= G.scene->ed;
2185         Sequence *seq;
2186         TStripElem *se;
2187         int a;
2188
2189         if(ed==0) return;
2190
2191         WHILE_SEQ(&ed->seqbase) {
2192                 if(seq->strip) {
2193                         for(a = 0, se = seq->strip->tstripdata; 
2194                             a < seq->strip->len && se; a++, se++) {
2195                                 free_imbuf_strip_elem(se);
2196                         }
2197                         for(a = 0, se = seq->strip->tstripdata_startstill; 
2198                             a < seq->strip->startstill && se; a++, se++) {
2199                                 free_imbuf_strip_elem(se);
2200                         }
2201                         for(a = 0, se = seq->strip->tstripdata_endstill; 
2202                             a < seq->strip->endstill && se; a++, se++) {
2203                                 free_imbuf_strip_elem(se);
2204                         }
2205
2206                         if(seq->type==SEQ_MOVIE)
2207                                 free_anim_seq(seq);
2208                         if(seq->type==SEQ_SPEED) {
2209                                 sequence_effect_speed_rebuild_map(seq, 1);
2210                         }
2211                 }
2212         }
2213         END_SEQ
2214 }
2215
2216 void free_imbuf_seq_with_ipo(struct Ipo *ipo)
2217 {
2218         /* force update of all sequences with this ipo, on ipo changes */
2219         Editing *ed= G.scene->ed;
2220         Sequence *seq;
2221
2222         if(ed==0) return;
2223
2224         WHILE_SEQ(&ed->seqbase) {
2225                 if(seq->ipo == ipo) {
2226                         update_changed_seq_and_deps(seq, 0, 1);
2227                         if(seq->type == SEQ_SPEED) {
2228                                 sequence_effect_speed_rebuild_map(seq, 1);
2229                         }
2230                 }
2231         }
2232         END_SEQ
2233 }
2234
2235 static int update_changed_seq_recurs(Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
2236 {
2237         Sequence *subseq;
2238         int a, free_imbuf = 0;
2239         TStripElem *se;
2240
2241         /* recurs downwards to see if this seq depends on the changed seq */
2242
2243         if(seq == NULL)
2244                 return 0;
2245
2246         if(seq == changed_seq)
2247                 free_imbuf = 1;
2248         
2249         for(subseq=seq->seqbase.first; subseq; subseq=subseq->next)
2250                 if(update_changed_seq_recurs(subseq, changed_seq, len_change, ibuf_change))
2251                         free_imbuf = TRUE;
2252         
2253         if(seq->seq1)
2254                 if(update_changed_seq_recurs(seq->seq1, changed_seq, len_change, ibuf_change))
2255                         free_imbuf = TRUE;
2256         if(seq->seq2 && (seq->seq2 != seq->seq1))
2257                 if(update_changed_seq_recurs(seq->seq2, changed_seq, len_change, ibuf_change))
2258                         free_imbuf = TRUE;
2259         if(seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
2260                 if(update_changed_seq_recurs(seq->seq3, changed_seq, len_change, ibuf_change))
2261                         free_imbuf = TRUE;
2262         
2263         if(free_imbuf) {
2264                 if(ibuf_change) {
2265                         se= seq->strip->tstripdata;
2266                         if (se) {
2267                                 for(a=0; a<seq->len; a++, se++)
2268                                         free_imbuf_strip_elem(se);
2269                         }
2270                 
2271                         if(seq->type == SEQ_MOVIE)
2272                                 free_anim_seq(seq);
2273                         if(seq->type == SEQ_SPEED) {
2274                                 sequence_effect_speed_rebuild_map(seq, 1);
2275                         }
2276                 }
2277
2278                 if(len_change)
2279                         calc_sequence(seq);
2280         }
2281         
2282         return free_imbuf;
2283 }
2284
2285 void update_changed_seq_and_deps(Sequence *changed_seq, int len_change, int ibuf_change)
2286 {
2287         Editing *ed= G.scene->ed;
2288         Sequence *seq;
2289
2290         if (!ed) return;
2291
2292         for (seq=ed->seqbase.first; seq; seq=seq->next)
2293                 update_changed_seq_recurs(seq, changed_seq, len_change, ibuf_change);
2294 }
2295
2296 /* bad levell call... */
2297 void do_render_seq(RenderResult *rr, int cfra)
2298 {
2299         ImBuf *ibuf;
2300
2301         G.f |= G_PLAYANIM;      /* waitcursor patch */
2302
2303         ibuf= give_ibuf_seq(rr->rectx, rr->recty, cfra, 0);
2304         
2305         if(ibuf) {
2306                 if(ibuf->rect_float) {
2307                         if (!rr->rectf)
2308                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2309                         
2310                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2311                         
2312                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2313                            can hang around when sequence render has rendered a 32 bits one before */
2314                         if(rr->rect32) {
2315                                 MEM_freeN(rr->rect32);
2316                                 rr->rect32= NULL;
2317                         }
2318                 }
2319                 else if(ibuf->rect) {
2320                         if (!rr->rect32)
2321                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2322
2323                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2324
2325                         /* if (ibuf->zbuf) { */
2326                         /*      if (R.rectz) freeN(R.rectz); */
2327                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2328                         /* } */
2329                 }
2330                 
2331                 /* Let the cache limitor take care of this (schlaile) */
2332                 /* While render let's keep all memory available for render 
2333                    (ton)
2334                    At least if free memory is tight...
2335                    This can make a big difference in encoding speed
2336                    (it is around 4 times(!) faster, if we do not waste time
2337                    on freeing _all_ buffers every time on long timelines...)
2338                    (schlaile)
2339                 */
2340                 {
2341                         extern int mem_in_use;
2342                         extern int mmap_in_use;
2343
2344                         int max = MEM_CacheLimiter_get_maximum();
2345                         if (max != 0 && mem_in_use + mmap_in_use > max) {
2346                                 fprintf(stderr, "mem_in_use = %d, max = %d\n",
2347                                         mem_in_use + mmap_in_use, max);
2348                                 fprintf(stderr, "Cleaning up, please wait...\n"
2349                                         "If this happens very often,\n"
2350                                         "consider "
2351                                         "raising the memcache limit in the "
2352                                         "user preferences.\n");
2353                                 free_imbuf_seq();
2354                         }
2355                 }
2356         }
2357         else {
2358                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2359                 if (rr->rectf)
2360                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2361                 else if (rr->rect32)
2362                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2363                 else
2364                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2365         }
2366         
2367         G.f &= ~G_PLAYANIM;
2368
2369 }