e55cea7de592afe2907b5eedaa2e8aab388fca84
[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 <pthread.h>
75
76 int seqrectx, seqrecty;
77
78 void free_stripdata(int len, StripElem *se)
79 {
80         StripElem *seo;
81         int a;
82
83         seo= se;
84
85         for(a=0; a<len; a++, se++) {
86                 if(se->ibuf && se->ok!=2) {
87                         IMB_freeImBuf(se->ibuf);
88                         se->ibuf = 0;
89                 }
90         }
91
92         MEM_freeN(seo);
93
94 }
95
96 void free_strip(Strip *strip)
97 {
98         strip->us--;
99         if(strip->us>0) return;
100         if(strip->us<0) {
101                 printf("error: negative users in strip\n");
102                 return;
103         }
104
105         if(strip->stripdata) {
106                 free_stripdata(strip->len, strip->stripdata);
107         }
108         MEM_freeN(strip);
109 }
110
111 void new_stripdata(Sequence *seq)
112 {
113         if(seq->strip) {
114                 if(seq->strip->stripdata) free_stripdata(seq->strip->len, seq->strip->stripdata);
115                 seq->strip->stripdata= 0;
116                 seq->strip->len= seq->len;
117                 if(seq->len>0) seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelems");
118         }
119 }
120
121 void free_sequence(Sequence *seq)
122 {
123         Sequence *last_seq = get_last_seq();
124
125         if(seq->strip) free_strip(seq->strip);
126
127         if(seq->anim) IMB_free_anim(seq->anim);
128         if(seq->hdaudio) sound_close_hdaudio(seq->hdaudio);
129
130         if (seq->type & SEQ_EFFECT) {
131                 struct SeqEffectHandle sh = get_sequence_effect(seq);
132
133                 sh.free(seq);
134         }
135
136         if(seq==last_seq) set_last_seq(NULL);
137
138         MEM_freeN(seq);
139 }
140
141 /*
142   **********************************************************************
143   * build_seqar
144   **********************************************************************
145   * Build a complete array of _all_ sequencies (including those
146   * in metastrips!)
147   **********************************************************************
148 */
149
150 static void do_seq_count(ListBase *seqbase, int *totseq)
151 {
152         Sequence *seq;
153
154         seq= seqbase->first;
155         while(seq) {
156                 (*totseq)++;
157                 if(seq->seqbase.first) do_seq_count(&seq->seqbase, totseq);
158                 seq= seq->next;
159         }
160 }
161
162 static void do_build_seqar(ListBase *seqbase, Sequence ***seqar, int depth)
163 {
164         Sequence *seq;
165
166         seq= seqbase->first;
167         while(seq) {
168                 seq->depth= depth;
169                 if(seq->seqbase.first) do_build_seqar(&seq->seqbase, seqar, depth+1);
170                 **seqar= seq;
171                 (*seqar)++;
172                 seq= seq->next;
173         }
174 }
175
176 void build_seqar(ListBase *seqbase, Sequence  ***seqar, int *totseq)
177 {
178         Sequence **tseqar;
179
180         *totseq= 0;
181         do_seq_count(seqbase, totseq);
182
183         if(*totseq==0) {
184                 *seqar= 0;
185                 return;
186         }
187         *seqar= MEM_mallocN(sizeof(void *)* *totseq, "seqar");
188         tseqar= *seqar;
189
190         do_build_seqar(seqbase, seqar, 0);
191         *seqar= tseqar;
192 }
193
194 void free_editing(Editing *ed)
195 {
196         MetaStack *ms;
197         Sequence *seq;
198
199         if(ed==NULL) return;
200         set_last_seq(NULL);     /* clear_last_seq doesnt work, it screws up free_sequence */
201
202         WHILE_SEQ(&ed->seqbase) {
203                 free_sequence(seq);
204         }
205         END_SEQ
206
207         while( (ms= ed->metastack.first) ) {
208                 BLI_remlink(&ed->metastack, ms);
209                 MEM_freeN(ms);
210         }
211
212         MEM_freeN(ed);
213
214 }
215
216 void calc_sequence(Sequence *seq)
217 {
218         Sequence *seqm;
219         int min, max;
220
221         /* check all metas recursively */
222         seqm= seq->seqbase.first;
223         while(seqm) {
224                 if(seqm->seqbase.first) calc_sequence(seqm);
225                 seqm= seqm->next;
226         }
227
228         /* effects and meta: automatic start and end */
229
230         if(seq->type & SEQ_EFFECT) {
231                 /* pointers */
232                 if(seq->seq2==0) seq->seq2= seq->seq1;
233                 if(seq->seq3==0) seq->seq3= seq->seq1;
234
235                 /* effecten go from seq1 -> seq2: test */
236
237                 /* we take the largest start and smallest end */
238
239                 // seq->start= seq->startdisp= MAX2(seq->seq1->startdisp, seq->seq2->startdisp);
240                 // seq->enddisp= MIN2(seq->seq1->enddisp, seq->seq2->enddisp);
241
242                 if (seq->seq1) {
243                         seq->start= seq->startdisp= MAX3(seq->seq1->startdisp, seq->seq2->startdisp, seq->seq3->startdisp);
244                         seq->enddisp= MIN3(seq->seq1->enddisp, seq->seq2->enddisp, seq->seq3->enddisp);
245                         seq->len= seq->enddisp - seq->startdisp;
246                 } else {
247                         if(seq->startofs && seq->startstill) seq->startstill= 0;
248                         if(seq->endofs && seq->endstill) seq->endstill= 0;
249
250                         seq->startdisp= seq->start + seq->startofs - seq->startstill;
251                         seq->enddisp= seq->start+seq->len - seq->endofs + seq->endstill;
252
253                         seq->handsize= 10.0;    /* 10 frames */
254                         if( seq->enddisp-seq->startdisp < 20 ) {
255                                 seq->handsize= (float)(0.5*(seq->enddisp-seq->startdisp));
256                         }
257                         else if(seq->enddisp-seq->startdisp > 250) {
258                                 seq->handsize= (float)((seq->enddisp-seq->startdisp)/25);
259                         }
260                 }
261
262                 if(seq->strip && seq->len!=seq->strip->len) {
263                         new_stripdata(seq);
264                 }
265
266         }
267         else {
268                 if(seq->type==SEQ_META) {
269                         seqm= seq->seqbase.first;
270                         if(seqm) {
271                                 min= 1000000;
272                                 max= -1000000;
273                                 while(seqm) {
274                                         if(seqm->startdisp < min) min= seqm->startdisp;
275                                         if(seqm->enddisp > max) max= seqm->enddisp;
276                                         seqm= seqm->next;
277                                 }
278                                 seq->start= min;
279                                 seq->len= max-min;
280
281                                 if(seq->strip && seq->len!=seq->strip->len) {
282                                         new_stripdata(seq);
283                                 }
284                         }
285                 }
286
287
288                 if(seq->startofs && seq->startstill) seq->startstill= 0;
289                 if(seq->endofs && seq->endstill) seq->endstill= 0;
290
291                 seq->startdisp= seq->start + seq->startofs - seq->startstill;
292                 seq->enddisp= seq->start+seq->len - seq->endofs + seq->endstill;
293
294                 seq->handsize= 10.0;    /* 10 frames */
295                 if( seq->enddisp-seq->startdisp < 20 ) {
296                         seq->handsize= (float)(0.5*(seq->enddisp-seq->startdisp));
297                 }
298                 else if(seq->enddisp-seq->startdisp > 250) {
299                         seq->handsize= (float)((seq->enddisp-seq->startdisp)/25);
300                 }
301         }
302 }
303
304 void sort_seq()
305 {
306         /* all strips together per kind, and in order of y location ("machine") */
307         ListBase seqbase, effbase;
308         Editing *ed;
309         Sequence *seq, *seqt;
310
311         ed= G.scene->ed;
312         if(ed==0) return;
313
314         seqbase.first= seqbase.last= 0;
315         effbase.first= effbase.last= 0;
316
317         while( (seq= ed->seqbasep->first) ) {
318                 BLI_remlink(ed->seqbasep, seq);
319
320                 if(seq->type & SEQ_EFFECT) {
321                         seqt= effbase.first;
322                         while(seqt) {
323                                 if(seqt->machine>=seq->machine) {
324                                         BLI_insertlinkbefore(&effbase, seqt, seq);
325                                         break;
326                                 }
327                                 seqt= seqt->next;
328                         }
329                         if(seqt==0) BLI_addtail(&effbase, seq);
330                 }
331                 else {
332                         seqt= seqbase.first;
333                         while(seqt) {
334                                 if(seqt->machine>=seq->machine) {
335                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
336                                         break;
337                                 }
338                                 seqt= seqt->next;
339                         }
340                         if(seqt==0) BLI_addtail(&seqbase, seq);
341                 }
342         }
343
344         addlisttolist(&seqbase, &effbase);
345         *(ed->seqbasep)= seqbase;
346 }
347
348
349 void clear_scene_in_allseqs(Scene *sce)
350 {
351         Scene *sce1;
352         Editing *ed;
353         Sequence *seq;
354
355         /* when a scene is deleted: test all seqs */
356
357         sce1= G.main->scene.first;
358         while(sce1) {
359                 if(sce1!=sce && sce1->ed) {
360                         ed= sce1->ed;
361
362                         WHILE_SEQ(&ed->seqbase) {
363
364                                 if(seq->scene==sce) seq->scene= 0;
365
366                         }
367                         END_SEQ
368                 }
369
370                 sce1= sce1->id.next;
371         }
372 }
373
374 /* ***************** DO THE SEQUENCE ***************** */
375
376 static void make_black_ibuf(ImBuf *ibuf)
377 {
378         unsigned int *rect;
379         float *rect_float;
380         int tot;
381
382         if(ibuf==0 || (ibuf->rect==0 && ibuf->rect_float==0)) return;
383
384         tot= ibuf->x*ibuf->y;
385
386         rect= ibuf->rect;
387         rect_float = ibuf->rect_float;
388
389         if (rect) {
390                 memset(rect,       0, tot * sizeof(char) * 4);
391         }
392
393         if (rect_float) {
394                 memset(rect_float, 0, tot * sizeof(float) * 4);
395         }
396 }
397
398 static void multibuf(ImBuf *ibuf, float fmul)
399 {
400         char *rt;
401         float *rt_float;
402
403         int a, mul, icol;
404
405         mul= (int)(256.0*fmul);
406
407         a= ibuf->x*ibuf->y;
408         rt= (char *)ibuf->rect;
409         rt_float = ibuf->rect_float;
410
411         if (rt) {
412                 while(a--) {
413
414                         icol= (mul*rt[0])>>8;
415                         if(icol>254) rt[0]= 255; else rt[0]= icol;
416                         icol= (mul*rt[1])>>8;
417                         if(icol>254) rt[1]= 255; else rt[1]= icol;
418                         icol= (mul*rt[2])>>8;
419                         if(icol>254) rt[2]= 255; else rt[2]= icol;
420                         icol= (mul*rt[3])>>8;
421                         if(icol>254) rt[3]= 255; else rt[3]= icol;
422                         
423                         rt+= 4;
424                 }
425         }
426         if (rt_float) {
427                 while(a--) {
428                         rt_float[0] *= fmul;
429                         rt_float[1] *= fmul;
430                         rt_float[2] *= fmul;
431                         rt_float[3] *= fmul;
432                         
433                         rt_float += 4;
434                 }
435         }
436 }
437
438 static void do_effect(int cfra, Sequence *seq, StripElem *se)
439 {
440         StripElem *se1, *se2, *se3;
441         float fac, facf;
442         int x, y;
443         int early_out;
444         struct SeqEffectHandle sh = get_sequence_effect(seq);
445
446         if (!sh.execute) { /* effect not supported in this version... */
447                 make_black_ibuf(se->ibuf);
448                 return;
449         }
450
451         if(seq->ipo && seq->ipo->curve.first) {
452                 do_seq_ipo(seq);
453                 fac= seq->facf0;
454                 facf= seq->facf1;
455         } else {
456                 sh.get_default_fac(seq, cfra, &fac, &facf);
457         }
458
459         if( !(G.scene->r.mode & R_FIELDS) ) facf = fac;
460
461         early_out = sh.early_out(seq, fac, facf);
462
463         if (early_out == -1) { /* no input needed */
464                 sh.execute(seq, cfra, fac, facf, se->ibuf->x, se->ibuf->y, 
465                            0, 0, 0, se->ibuf);
466                 return;
467         }
468
469         switch (early_out) {
470         case 0:
471                 if (se->se1==0 || se->se2==0 || se->se3==0) {
472                         make_black_ibuf(se->ibuf);
473                         return;
474                 }
475
476                 /* if metastrip: other se's */
477                 if(se->se1->ok==2) se1= se->se1->se1;
478                 else se1= se->se1;
479                 
480                 if(se->se2->ok==2) se2= se->se2->se1;
481                 else se2= se->se2;
482                 
483                 if(se->se3->ok==2) se3= se->se3->se1;
484                 else se3= se->se3;
485
486                 if (   (se1==0 || se2==0 || se3==0)
487                     || (se1->ibuf==0 || se2->ibuf==0 || se3->ibuf==0)) {
488                         make_black_ibuf(se->ibuf);
489                         return;
490                 }
491
492                 break;
493         case 1:
494                 if (se->se1 == 0) {
495                         make_black_ibuf(se->ibuf);
496                         return;
497                 }
498
499                 /* if metastrip: other se's */
500                 if(se->se1->ok==2) se1= se->se1->se1;
501                 else se1= se->se1;
502
503                 if (se1 == 0 || se1->ibuf == 0) {
504                         make_black_ibuf(se->ibuf);
505                         return;
506                 }
507
508                 if (se->ibuf != se1->ibuf) {
509                         IMB_freeImBuf(se->ibuf);
510                         se->ibuf = se1->ibuf;
511                         IMB_refImBuf(se->ibuf);
512                 }
513                 return;
514         case 2:
515                 if (se->se2 == 0) {
516                         make_black_ibuf(se->ibuf);
517                         return;
518                 }
519
520                 /* if metastrip: other se's */
521                 if(se->se2->ok==2) se2= se->se2->se1;
522                 else se2= se->se2;
523
524                 if (se2 == 0 || se2->ibuf == 0) {
525                         make_black_ibuf(se->ibuf);
526                         return;
527                 }
528                 if (se->ibuf != se2->ibuf) {
529                         IMB_freeImBuf(se->ibuf);
530                         se->ibuf = se2->ibuf;
531                         IMB_refImBuf(se->ibuf);
532                 }
533                 return;
534         default:
535                 make_black_ibuf(se->ibuf);
536                 return;
537         }
538
539         x= se2->ibuf->x;
540         y= se2->ibuf->y;
541
542         if (!se1->ibuf->rect_float && se->ibuf->rect_float) {
543                 IMB_float_from_rect(se1->ibuf);
544         }
545         if (!se2->ibuf->rect_float && se->ibuf->rect_float) {
546                 IMB_float_from_rect(se2->ibuf);
547         }
548
549         if (!se1->ibuf->rect && !se->ibuf->rect_float) {
550                 IMB_rect_from_float(se1->ibuf);
551         }
552         if (!se2->ibuf->rect && !se->ibuf->rect_float) {
553                 IMB_rect_from_float(se2->ibuf);
554         }
555
556         sh.execute(seq, cfra, fac, facf, x, y, se1->ibuf, se2->ibuf, se3->ibuf,
557                    se->ibuf);
558 }
559
560 StripElem *give_stripelem(Sequence *seq, int cfra)
561 {
562         Strip *strip;
563         StripElem *se;
564         int nr;
565
566         strip= seq->strip;
567         se= strip->stripdata;
568
569         if(se==0) return 0;
570         if(seq->startdisp >cfra || seq->enddisp <= cfra) return 0;
571
572         if(seq->flag&SEQ_REVERSE_FRAMES)        {       
573                 /*reverse frame in this sequence */
574                 if(cfra <= seq->start) nr= seq->len-1;
575                 else if(cfra >= seq->start+seq->len-1) nr= 0;
576                 else nr= (seq->start + seq->len) - cfra;
577         } else {
578                 if(cfra <= seq->start) nr= 0;
579                 else if(cfra >= seq->start+seq->len-1) nr= seq->len-1;
580                 else nr= cfra-seq->start;
581         }
582         if (seq->strobe < 1.0) seq->strobe = 1.0;
583         if (seq->strobe > 1.0) {
584                 nr -= (int)fmod((double)nr, (double)seq->strobe);
585         }
586         
587         se+= nr; /* don't get confused by the increment, this is the same as strip->stripdata[nr], which works on some compilers...*/
588         se->nr= nr;
589         
590         return se;
591 }
592
593 static int evaluate_seq_frame_gen(
594         Sequence ** seq_arr, ListBase *seqbase, int cfra)
595 {
596         Sequence *seq;
597         int totseq=0;
598
599         memset(seq_arr, 0, sizeof(Sequence*) * MAXSEQ);
600
601         seq= seqbase->first;
602         while(seq) {
603                 if(seq->startdisp <=cfra && seq->enddisp > cfra) {
604                         seq_arr[seq->machine]= seq;
605                         totseq++;
606                 }
607                 seq= seq->next;
608         }
609
610         return totseq;
611 }
612
613 int evaluate_seq_frame(int cfra)
614 {
615        Editing *ed;
616        Sequence *seq_arr[MAXSEQ+1];
617
618        ed= G.scene->ed;
619        if(ed==0) return 0;
620         
621        return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
622
623 }
624
625 Sequence *get_shown_sequence(ListBase * seqbasep, int cfra, int chanshown)
626 {
627         Sequence *seq, *seqim, *seqeff;
628         Sequence *seq_arr[MAXSEQ+1];
629         int b;
630
631         seq = 0;
632
633         if (chanshown > MAXSEQ) {
634                 return 0;
635         }
636
637         if(evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
638                 if (chanshown > 0) {
639                         return seq_arr[chanshown];
640                 }
641
642                 /* we take the upper effect strip or 
643                    the lowest imagestrip/metastrip */
644                 seqim= seqeff= 0;
645
646                 for(b=1; b<MAXSEQ; b++) {
647                         if(seq_arr[b]) {
648                                 seq= seq_arr[b];
649                                 if(seq->type & SEQ_EFFECT) {
650                                         if(seqeff==0) seqeff= seq;
651                                         else if(seqeff->machine < seq->machine)
652                                                 seqeff= seq;
653                                 } else if (seq->type != SEQ_RAM_SOUND && seq->type != SEQ_HD_SOUND) {
654                                         if(seqim==0) seqim= seq;
655                                         else if(seqim->machine > seq->machine)
656                                                 seqim= seq;
657                                 }
658                         }
659                 }
660                 if(seqeff) seq= seqeff;
661                 else if(seqim) seq= seqim;
662                 else seq= 0;
663         }
664         
665         return seq;
666 }
667  
668 static Sequence * get_shown_seq_from_metastrip(Sequence * seqm, int cfra)
669 {
670         return get_shown_sequence(&seqm->seqbase, cfra, 0);
671 }
672
673 void set_meta_stripdata(Sequence *seqm)
674 {
675         Sequence *seq;
676         StripElem *se;
677         int a, cfra;
678
679         /* sets all ->se1 pointers in stripdata, to read the ibuf from it */
680
681         se= seqm->strip->stripdata;
682         for(a=0; a<seqm->len; a++, se++) {
683                 cfra= a+seqm->start;
684                 seq = get_shown_seq_from_metastrip(seqm, cfra);
685                 if (seq) {
686                         se->se1= give_stripelem(seq, cfra);
687                 } else { 
688                         se->se1= 0;
689                 }
690         }
691 }
692
693 static void do_build_seq_ibuf(Sequence * seq, int cfra)
694 {
695         StripElem *se = seq->curelem;
696         char name[FILE_MAXDIR+FILE_MAXFILE];
697
698         if(seq->type == SEQ_META) {
699                 se->ok= 2;
700                 if(se->se1==0) set_meta_stripdata(seq);
701                 if(se->se1) {
702                         se->ibuf= se->se1->ibuf;
703                 }
704         } else if(seq->type == SEQ_RAM_SOUND || seq->type == SEQ_HD_SOUND) {
705                 se->ok= 2;
706         } else if(seq->type & SEQ_EFFECT) {
707                         
708                 /* test if image is too small or discarded from cache: reload */
709                 if(se->ibuf) {
710                         if(se->ibuf->x < seqrectx || se->ibuf->y < seqrecty || !(se->ibuf->rect || se->ibuf->rect_float)) {
711                                 IMB_freeImBuf(se->ibuf);
712                                 se->ibuf= 0;
713                         }
714                 }
715                         
716                 /* should the effect be recalculated? */
717                 
718                 if(se->ibuf==0 
719                    || (seq->seq1 && se->se1 != seq->seq1->curelem) 
720                    || (seq->seq2 && se->se2 != seq->seq2->curelem) 
721                    || (seq->seq3 && se->se3 != seq->seq3->curelem)) {
722                         if (seq->seq1) se->se1= seq->seq1->curelem;
723                         if (seq->seq2) se->se2= seq->seq2->curelem;
724                         if (seq->seq3) se->se3= seq->seq3->curelem;
725                         
726                         if(se->ibuf==NULL) {
727                                 /* if one of two first inputs are rectfloat, output is float too */
728                                 if((se->se1 && se->se1->ibuf && se->se1->ibuf->rect_float) ||
729                                    (se->se2 && se->se2->ibuf && se->se2->ibuf->rect_float))
730                                         se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
731                                 else
732                                         se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
733                         }
734                         
735                         do_effect(cfra, seq, se);
736                 }
737                 
738                 /* test size */
739                 if(se->ibuf) {
740                         if(se->ibuf->x != seqrectx || se->ibuf->y != seqrecty ) {
741                                 if(G.scene->r.mode & R_OSA) {
742                                         IMB_scaleImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
743                                 } else {
744                                         IMB_scalefastImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
745                                 }
746                         }
747                 }
748         } else if(seq->type < SEQ_EFFECT) {
749                 if(se->ibuf) {
750                         /* test if image too small 
751                            or discarded from cache: reload */
752                         if(se->ibuf->x < seqrectx || se->ibuf->y < seqrecty || !(se->ibuf->rect || se->ibuf->rect_float)) {
753                                 IMB_freeImBuf(se->ibuf);
754                                 se->ibuf= 0;
755                                 se->ok= 1;
756                         }
757                 }
758                 
759                 if(seq->type==SEQ_IMAGE) {
760                         if(se->ok && se->ibuf==0) {
761                                 /* if playanim or render: 
762                                    no waitcursor */
763                                 if((G.f & G_PLAYANIM)==0) 
764                                         waitcursor(1);
765                                 
766                                 strncpy(name, seq->strip->dir, FILE_MAXDIR-1);
767                                 strncat(name, se->name, FILE_MAXFILE);
768                                 BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
769                                 se->ibuf= IMB_loadiffname(name, IB_rect);
770                                 
771                                 if((G.f & G_PLAYANIM)==0) 
772                                         waitcursor(0);
773                                 
774                                 if(se->ibuf==0) se->ok= 0;
775                                 else {
776                                         if(seq->flag & SEQ_MAKE_PREMUL) {
777                                                 if(se->ibuf->depth==32 && se->ibuf->zbuf==0) converttopremul(se->ibuf);
778                                         }
779                                         seq->strip->orx= se->ibuf->x;
780                                         seq->strip->ory= se->ibuf->y;
781                                         if(seq->flag & SEQ_FILTERY) IMB_filtery(se->ibuf);
782                                         if(seq->mul==0.0) seq->mul= 1.0;
783                                         if(seq->mul != 1.0) multibuf(se->ibuf, seq->mul);
784                                 }
785                         }
786                 }
787                 else if(seq->type==SEQ_MOVIE) {
788                         if(se->ok && se->ibuf==0) {
789                                 if(seq->anim==0) {
790                                         strncpy(name, seq->strip->dir, FILE_MAXDIR-1);
791                                         strncat(name, seq->strip->stripdata->name, FILE_MAXFILE-1);
792                                         BLI_convertstringcode(name, G.sce, G.scene->r.cfra);
793                                         
794                                         seq->anim = openanim(name, IB_rect);
795                                 }
796                                 if(seq->anim) {
797                                         IMB_anim_set_preseek(seq->anim, seq->anim_preseek);
798                                         se->ibuf = IMB_anim_absolute(seq->anim, se->nr);
799                                 }
800                                 
801                                 if(se->ibuf==0) se->ok= 0;
802                                 else {
803                                         if(seq->flag & SEQ_MAKE_PREMUL) {
804                                                 if(se->ibuf->depth==32) converttopremul(se->ibuf);
805                                         }
806                                         seq->strip->orx= se->ibuf->x;
807                                         seq->strip->ory= se->ibuf->y;
808                                         if(seq->flag & SEQ_FILTERY) IMB_filtery(se->ibuf);
809                                         if(seq->mul==0.0) seq->mul= 1.0;
810                                         if(seq->mul != 1.0) multibuf(se->ibuf, seq->mul);
811                                 }
812                         }
813                 } else if(seq->type==SEQ_SCENE && se->ibuf==NULL && seq->scene) {       // scene can be NULL after deletions
814                         int oldcfra = CFRA;
815                         Scene *sce= seq->scene, *oldsce= G.scene;
816                         Render *re;
817                         RenderResult rres;
818                         int doseq, rendering= G.rendering;
819                         char scenename[64];
820                         
821                         waitcursor(1);
822                         
823                         /* Hack! This function can be called from do_render_seq(), in that case
824                            the seq->scene can already have a Render initialized with same name, 
825                            so we have to use a default name. (compositor uses G.scene name to
826                            find render).
827                            However, when called from within the UI (image preview in sequencer)
828                            we do want to use scene Render, that way the render result is defined
829                            for display in render/imagewindow */
830                         if(rendering) {
831                                 BLI_strncpy(scenename, sce->id.name+2, 64);
832                                 strcpy(sce->id.name+2, " do_build_seq_ibuf");
833                         }
834                         re= RE_NewRender(sce->id.name);
835                         
836                         /* prevent eternal loop */
837                         doseq= G.scene->r.scemode & R_DOSEQ;
838                         G.scene->r.scemode &= ~R_DOSEQ;
839                         
840                         BIF_init_render_callbacks(re, 0);       /* 0= no display callbacks */
841                         
842                         /* hrms, set_scene still needed? work on that... */
843                         if(sce!=oldsce) set_scene_bg(sce);
844                         RE_BlenderFrame(re, sce, seq->sfra + se->nr);
845                         if(sce!=oldsce) set_scene_bg(oldsce);
846                         
847                         /* UGLY WARNING, it is set to zero in  RE_BlenderFrame */
848                         G.rendering= rendering;
849                         if(rendering)
850                                 BLI_strncpy(sce->id.name+2, scenename, 64);
851                         
852                         RE_GetResultImage(re, &rres);
853                         
854                         if(rres.rectf) {
855                                 se->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat, 0);
856                                 memcpy(se->ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
857                                 if(rres.rectz) {
858                                         addzbuffloatImBuf(se->ibuf);
859                                         memcpy(se->ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
860                                 }
861                         } else if (rres.rect32) {
862                                 se->ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect, 0);
863                                 memcpy(se->ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
864                         }
865                         
866                         BIF_end_render_callbacks();
867                         
868                         /* restore */
869                         G.scene->r.scemode |= doseq;
870                         
871                         if((G.f & G_PLAYANIM)==0) /* bad, is set on do_render_seq */
872                                 waitcursor(0);
873                         CFRA = oldcfra;
874                 }
875                 
876                 /* size test */
877                 if(se->ibuf) {
878                         if(se->ibuf->x != seqrectx || se->ibuf->y != seqrecty ) {
879                                 
880                                 if (0) { // G.scene->r.mode & R_FIELDS) {
881                                         
882                                         if (seqrecty > 288) 
883                                                 IMB_scalefieldImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
884                                         else {
885                                                 IMB_de_interlace(se->ibuf);
886                                                 
887                                                 if(G.scene->r.mode & R_OSA)
888                                                         IMB_scaleImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
889                                                 else
890                                                         IMB_scalefastImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
891                                         }
892                                 }
893                                 else {
894                                         if(G.scene->r.mode & R_OSA)
895                                                 IMB_scaleImBuf(se->ibuf,(short)seqrectx, (short)seqrecty);
896                                         else
897                                                 IMB_scalefastImBuf(se->ibuf, (short)seqrectx, (short)seqrecty);
898                                 }
899                         }
900                         
901                 }
902         }
903         if (se->ibuf) {
904                 IMB_cache_limiter_insert(se->ibuf);
905                 IMB_cache_limiter_ref(se->ibuf);
906                 IMB_cache_limiter_touch(se->ibuf);
907         }
908 }
909
910 static void do_build_seq_recursively(Sequence * seq, int cfra);
911
912 static void do_effect_seq_recursively(int cfra, Sequence * seq, StripElem *se)
913 {
914         float fac, facf;
915         struct SeqEffectHandle sh = get_sequence_effect(seq);
916         int early_out;
917
918         if(seq->ipo && seq->ipo->curve.first) {
919                 do_seq_ipo(seq);
920                 fac= seq->facf0;
921                 facf= seq->facf1;
922         } else {
923                 sh.get_default_fac(seq, cfra, &fac, &facf);
924         } 
925
926         if( G.scene->r.mode & R_FIELDS ); else facf= fac;
927         
928         early_out = sh.early_out(seq, fac, facf);
929         switch (early_out) {
930         case -1:
931                 /* no input needed */
932                 break;
933         case 0:
934                 do_build_seq_recursively(seq->seq1, cfra);
935                 do_build_seq_recursively(seq->seq2, cfra);
936                 if (seq->seq3) {
937                         do_build_seq_recursively(seq->seq3, cfra);
938                 }
939                 break;
940         case 1:
941                 do_build_seq_recursively(seq->seq1, cfra);
942                 break;
943         case 2:
944                 do_build_seq_recursively(seq->seq2, cfra);
945                 break;
946         }
947
948
949         do_build_seq_ibuf(seq, cfra);
950
951         /* children are not needed anymore ... */
952
953         switch (early_out) {
954         case 0:
955                 if (seq->seq1->curelem && seq->seq1->curelem->ibuf)
956                         IMB_cache_limiter_unref(seq->seq1->curelem->ibuf);
957                 if (seq->seq2->curelem && seq->seq2->curelem->ibuf)
958                         IMB_cache_limiter_unref(seq->seq2->curelem->ibuf);
959                 if (seq->seq3) {
960                         if (seq->seq3->curelem && seq->seq3->curelem->ibuf)
961                                 IMB_cache_limiter_unref(
962                                         seq->seq3->curelem->ibuf);
963                 }
964                 break;
965         case 1:
966                 if (seq->seq1->curelem && seq->seq1->curelem->ibuf)
967                         IMB_cache_limiter_unref(seq->seq1->curelem->ibuf);
968                 break;
969         case 2:
970                 if (seq->seq2->curelem && seq->seq2->curelem->ibuf)
971                         IMB_cache_limiter_unref(seq->seq2->curelem->ibuf);
972                 break;
973         }
974 }
975
976 static void do_build_seq_recursively_impl(Sequence * seq, int cfra)
977 {
978         StripElem *se;
979
980         se = seq->curelem = give_stripelem(seq, cfra);
981
982         if(se) {
983                 int unref_meta = FALSE;
984                 if(seq->seqbase.first) {
985                         Sequence * seqmshown= get_shown_seq_from_metastrip(seq, cfra);
986                         if (seqmshown) {
987                                 if(cfra< seq->start) 
988                                         do_build_seq_recursively(seqmshown, seq->start);
989                                 else if(cfra> seq->start+seq->len-1) 
990                                         do_build_seq_recursively(seqmshown, seq->start + seq->len-1);
991                                 else do_build_seq_recursively(seqmshown, cfra);
992
993                                 unref_meta = TRUE;
994                         }
995                 }
996
997                 if (seq->type & SEQ_EFFECT) {
998                         do_effect_seq_recursively(cfra, seq, se);
999                 } else {
1000                         do_build_seq_ibuf(seq, cfra);
1001                 }
1002
1003                 if(unref_meta && seq->curelem->ibuf) {
1004                         IMB_cache_limiter_unref(seq->curelem->ibuf);
1005                 }
1006         }
1007 }
1008
1009 /* FIXME:
1010    
1011 If cfra was float throughout blender (especially in the render
1012 pipeline) one could even _render_ with subframe precision
1013 instead of faking using the blend code below...
1014
1015 */
1016
1017 static void do_handle_speed_effect(Sequence * seq, int cfra)
1018 {
1019         SpeedControlVars * s = (SpeedControlVars *)seq->effectdata;
1020         int nr = cfra - seq->start;
1021         float f_cfra;
1022         int cfra_left;
1023         int cfra_right;
1024         StripElem * se = 0;
1025         StripElem * se1 = 0;
1026         StripElem * se2 = 0;
1027         
1028         sequence_effect_speed_rebuild_map(seq, 0);
1029         
1030         f_cfra = seq->start + s->frameMap[nr];
1031         
1032         cfra_left = (int) floor(f_cfra);
1033         cfra_right = (int) ceil(f_cfra);
1034
1035         se = seq->curelem = give_stripelem(seq, cfra);
1036
1037         if (cfra_left == cfra_right || 
1038             (s->flags & SEQ_SPEED_BLEND) == 0) {
1039                 if(se->ibuf) {
1040                         if(se->ibuf->x < seqrectx || se->ibuf->y < seqrecty 
1041                            || !(se->ibuf->rect || se->ibuf->rect_float)) {
1042                                 IMB_freeImBuf(se->ibuf);
1043                                 se->ibuf= 0;
1044                         }
1045                 }
1046
1047                 if (se->ibuf == NULL) {
1048                         do_build_seq_recursively_impl(seq->seq1, cfra_left);
1049
1050                         se1 = seq->seq1->curelem;
1051
1052                         if((se1 && se1->ibuf && se1->ibuf->rect_float))
1053                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
1054                         else
1055                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
1056
1057                         if (se1 == 0 || se1->ibuf == 0) {
1058                                 make_black_ibuf(se->ibuf);
1059                         } else {
1060                                 if (se->ibuf != se1->ibuf) {
1061                                         if (se->ibuf) {
1062                                                 IMB_freeImBuf(se->ibuf);
1063                                         }
1064
1065                                         se->ibuf = se1->ibuf;
1066                                         IMB_refImBuf(se->ibuf);
1067                                 }
1068                         }
1069                 }
1070         } else {
1071                 struct SeqEffectHandle sh;
1072
1073                 if(se->ibuf) {
1074                         if(se->ibuf->x < seqrectx || se->ibuf->y < seqrecty 
1075                            || !(se->ibuf->rect || se->ibuf->rect_float)) {
1076                                 IMB_freeImBuf(se->ibuf);
1077                                 se->ibuf= 0;
1078                         }
1079                 }
1080
1081                 if (se->ibuf == NULL) {
1082                         do_build_seq_recursively_impl(seq->seq1, cfra_left);
1083                         se1 = seq->seq1->curelem;
1084                         do_build_seq_recursively_impl(seq->seq1, cfra_right);
1085                         se2 = seq->seq1->curelem;
1086
1087
1088                         if((se1 && se1->ibuf && se1->ibuf->rect_float))
1089                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rectfloat, 0);
1090                         else
1091                                 se->ibuf= IMB_allocImBuf((short)seqrectx, (short)seqrecty, 32, IB_rect, 0);
1092                         
1093                         if (!se1 || !se2) {
1094                                 make_black_ibuf(se->ibuf);
1095                         } else {
1096                                 sh = get_sequence_effect(seq);
1097
1098                                 sh.execute(seq, cfra, 
1099                                            f_cfra - (float) cfra_left, 
1100                                            f_cfra - (float) cfra_left, 
1101                                            se->ibuf->x, se->ibuf->y, 
1102                                            se1->ibuf, se2->ibuf, 0, se->ibuf);
1103                         }
1104                 }
1105
1106         }
1107
1108         /* caller expects this to be referenced, so do it! */
1109         if (se->ibuf) {
1110                 IMB_cache_limiter_insert(se->ibuf);
1111                 IMB_cache_limiter_ref(se->ibuf);
1112                 IMB_cache_limiter_touch(se->ibuf);
1113         }
1114
1115         /* children are no longer needed */
1116         if (se1 && se1->ibuf)
1117                 IMB_cache_limiter_unref(se1->ibuf);
1118         if (se2 && se2->ibuf)
1119                 IMB_cache_limiter_unref(se2->ibuf);
1120 }
1121
1122 /* 
1123  * build all ibufs recursively
1124  * 
1125  * if successfull, seq->curelem->ibuf contains the (referenced!) imbuf
1126  * that means: you _must_ call 
1127  *
1128  * IMB_cache_limiter_unref(seq->curelem->ibuf);
1129  * 
1130  * if seq->curelem exists!
1131  * 
1132  */
1133
1134 static void do_build_seq_recursively(Sequence * seq, int cfra)
1135 {
1136         if (seq->type == SEQ_SPEED) {
1137                 do_handle_speed_effect(seq, cfra);
1138         } else {
1139                 do_build_seq_recursively_impl(seq, cfra);
1140         }
1141 }
1142
1143 ImBuf *give_ibuf_seq(int rectx, int recty, int cfra, int chanshown)
1144 {
1145         Sequence *seqfirst=0;
1146         Editing *ed;
1147         int count;
1148         ListBase *seqbasep;
1149
1150         ed= G.scene->ed;
1151         if(ed==0) return 0;
1152
1153         count = BLI_countlist(&ed->metastack);
1154         if((chanshown < 0) && (count > 0)) {
1155                 count = MAX2(count + chanshown, 0);
1156                 seqbasep= ((MetaStack*)BLI_findlink(&ed->metastack, count))->oldbasep;
1157         } else {
1158                 seqbasep= ed->seqbasep;
1159         }
1160
1161         seqrectx= rectx;        /* bad bad global! */
1162         seqrecty= recty;
1163
1164         seqfirst = get_shown_sequence(seqbasep, cfra, chanshown);
1165
1166         if (!seqfirst) {
1167                 return 0;
1168         }
1169
1170         do_build_seq_recursively(seqfirst, cfra);
1171
1172         if(!seqfirst->curelem) { 
1173                 return 0;
1174         }
1175
1176         if (seqfirst->curelem->ibuf) {
1177                 IMB_cache_limiter_unref(seqfirst->curelem->ibuf);
1178         }
1179
1180         return seqfirst->curelem->ibuf;
1181
1182 }
1183
1184 /* threading api */
1185
1186 static ListBase running_threads;
1187 static ListBase prefetch_wait;
1188 static ListBase prefetch_done;
1189
1190 static pthread_mutex_t queue_lock          = PTHREAD_MUTEX_INITIALIZER;
1191 static pthread_mutex_t wakeup_lock         = PTHREAD_MUTEX_INITIALIZER;
1192 static pthread_cond_t  wakeup_cond         = PTHREAD_COND_INITIALIZER;
1193
1194 static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER;
1195 static pthread_cond_t  prefetch_ready_cond = PTHREAD_COND_INITIALIZER;
1196
1197 static pthread_mutex_t frame_done_lock     = PTHREAD_MUTEX_INITIALIZER;
1198 static pthread_cond_t  frame_done_cond     = PTHREAD_COND_INITIALIZER;
1199
1200 static volatile int seq_thread_shutdown = FALSE;
1201 static volatile int seq_last_given_monoton_cfra = 0;
1202 static int monoton_cfra = 0;
1203
1204 typedef struct PrefetchThread {
1205         struct PrefetchThread *next, *prev;
1206         struct PrefetchQueueElem *current;
1207         pthread_t pthread;
1208         int running;
1209 } PrefetchThread;
1210
1211 typedef struct PrefetchQueueElem {
1212         struct PrefetchQueueElem *next, *prev;
1213         
1214         int rectx;
1215         int recty;
1216         int cfra;
1217         int chanshown;
1218
1219         int monoton_cfra;
1220
1221         struct ImBuf * ibuf;
1222 } PrefetchQueueElem;
1223
1224
1225 static void * seq_prefetch_thread(void * This_)
1226 {
1227         PrefetchThread * This = This_;
1228
1229         while (!seq_thread_shutdown) {
1230                 PrefetchQueueElem * e;
1231                 int s_last;
1232
1233                 pthread_mutex_lock(&queue_lock);
1234                 e = prefetch_wait.first;
1235                 if (e) {
1236                         BLI_remlink(&prefetch_wait, e);
1237                 }
1238                 s_last = seq_last_given_monoton_cfra;
1239
1240                 This->current = e;
1241
1242                 pthread_mutex_unlock(&queue_lock);
1243
1244                 if (!e) {
1245                         pthread_mutex_lock(&prefetch_ready_lock);
1246
1247                         This->running = FALSE;
1248
1249                         pthread_cond_signal(&prefetch_ready_cond);
1250                         pthread_mutex_unlock(&prefetch_ready_lock);
1251
1252                         pthread_mutex_lock(&wakeup_lock);
1253                         if (!seq_thread_shutdown) {
1254                                 pthread_cond_wait(&wakeup_cond, &wakeup_lock);
1255                         }
1256                         pthread_mutex_unlock(&wakeup_lock);
1257                         continue;
1258                 }
1259
1260                 This->running = TRUE;
1261                 
1262                 if (e->cfra >= s_last) { 
1263                         e->ibuf = give_ibuf_seq(e->rectx, e->recty, e->cfra, 
1264                                                 e->chanshown);
1265                 }
1266
1267                 if (e->ibuf) {
1268                         IMB_cache_limiter_ref(e->ibuf);
1269                 }
1270
1271                 pthread_mutex_lock(&queue_lock);
1272
1273                 BLI_addtail(&prefetch_done, e);
1274
1275                 for (e = prefetch_wait.first; e; e = e->next) {
1276                         if (s_last > e->monoton_cfra) {
1277                                 BLI_remlink(&prefetch_wait, e);
1278                                 MEM_freeN(e);
1279                         }
1280                 }
1281
1282                 for (e = prefetch_done.first; e; e = e->next) {
1283                         if (s_last > e->monoton_cfra) {
1284                                 if (e->ibuf) {
1285                                         IMB_cache_limiter_unref(e->ibuf);
1286                                 }
1287                                 BLI_remlink(&prefetch_done, e);
1288                                 MEM_freeN(e);
1289                         }
1290                 }
1291
1292                 pthread_mutex_unlock(&queue_lock);
1293
1294                 pthread_mutex_lock(&frame_done_lock);
1295                 pthread_cond_signal(&frame_done_cond);
1296                 pthread_mutex_unlock(&frame_done_lock);
1297         }
1298         return 0;
1299 }
1300
1301 void seq_start_threads()
1302 {
1303         int i;
1304
1305         running_threads.first = running_threads.last = NULL;
1306         prefetch_wait.first = prefetch_wait.last = NULL;
1307         prefetch_done.first = prefetch_done.last = NULL;
1308
1309         seq_thread_shutdown = FALSE;
1310         seq_last_given_monoton_cfra = monoton_cfra = 0;
1311
1312         /* since global structures are modified during the processing
1313            of one frame, only one render thread is currently possible... 
1314
1315            (but we code, in the hope, that we can remove this restriction
1316            soon...)
1317         */
1318
1319         fprintf(stderr, "SEQ-THREAD: seq_start_threads\n");
1320
1321         for (i = 0; i < 1; i++) {
1322                 PrefetchThread *t = MEM_callocN(sizeof(PrefetchThread), 
1323                                                 "prefetch_thread");
1324                 t->running = TRUE;
1325                 BLI_addtail(&running_threads, t);
1326
1327                 pthread_create(&t->pthread, NULL, seq_prefetch_thread, t);
1328         }
1329 }
1330
1331 void seq_stop_threads()
1332 {
1333         PrefetchThread *tslot;
1334         PrefetchQueueElem * e;
1335
1336         fprintf(stderr, "SEQ-THREAD: seq_stop_threads()\n");
1337
1338         if (seq_thread_shutdown) {
1339                 fprintf(stderr, "SEQ-THREAD: ... already stopped\n");
1340                 return;
1341         }
1342         
1343         pthread_mutex_lock(&wakeup_lock);
1344
1345         seq_thread_shutdown = TRUE;
1346
1347         pthread_cond_broadcast(&wakeup_cond);
1348         pthread_mutex_unlock(&wakeup_lock);
1349
1350         for(tslot = running_threads.first; tslot; tslot= tslot->next) {
1351                 pthread_join(tslot->pthread, NULL);
1352         }
1353
1354
1355         for (e = prefetch_wait.first; e; e = e->next) {
1356                 BLI_remlink(&prefetch_wait, e);
1357                 MEM_freeN(e);
1358         }
1359
1360         for (e = prefetch_done.first; e; e = e->next) {
1361                 if (e->ibuf) {
1362                         IMB_cache_limiter_unref(e->ibuf);
1363                 }
1364                 BLI_remlink(&prefetch_done, e);
1365                 MEM_freeN(e);
1366         }
1367
1368         BLI_freelistN(&running_threads);
1369 }
1370
1371 void give_ibuf_prefetch_request(int rectx, int recty, int cfra, int chanshown)
1372 {
1373         PrefetchQueueElem * e;
1374         if (seq_thread_shutdown) {
1375                 return;
1376         }
1377
1378         e = MEM_callocN(sizeof(PrefetchQueueElem), "prefetch_queue_elem");
1379         e->rectx = rectx;
1380         e->recty = recty;
1381         e->cfra = cfra;
1382         e->chanshown = chanshown;
1383         e->monoton_cfra = monoton_cfra++;
1384
1385         pthread_mutex_lock(&queue_lock);
1386         BLI_addtail(&prefetch_wait, e);
1387         pthread_mutex_unlock(&queue_lock);
1388         
1389         pthread_mutex_lock(&wakeup_lock);
1390         pthread_cond_signal(&wakeup_cond);
1391         pthread_mutex_unlock(&wakeup_lock);
1392 }
1393
1394 void seq_wait_for_prefetch_ready()
1395 {
1396         PrefetchThread *tslot;
1397
1398         if (seq_thread_shutdown) {
1399                 return;
1400         }
1401
1402         fprintf(stderr, "SEQ-THREAD: rendering prefetch frames...\n");
1403
1404         pthread_mutex_lock(&prefetch_ready_lock);
1405
1406         for(;;) {
1407                 for(tslot = running_threads.first; tslot; tslot= tslot->next) {
1408                         if (tslot->running) {
1409                                 break;
1410                         }
1411                 }
1412                 if (!tslot) {
1413                         break;
1414                 }
1415                 pthread_cond_wait(&prefetch_ready_cond, &prefetch_ready_lock);
1416         }
1417
1418         pthread_mutex_unlock(&prefetch_ready_lock);
1419
1420         fprintf(stderr, "SEQ-THREAD: prefetch done\n");
1421 }
1422
1423 ImBuf * give_ibuf_threaded(int rectx, int recty, int cfra, int chanshown)
1424 {
1425         PrefetchQueueElem * e = 0;
1426         int found_something = FALSE;
1427
1428         if (seq_thread_shutdown) {
1429                 return give_ibuf_seq(rectx, recty, cfra, chanshown);
1430         }
1431
1432         while (!e) {
1433                 int success = FALSE;
1434                 pthread_mutex_lock(&queue_lock);
1435
1436                 for (e = prefetch_done.first; e; e = e->next) {
1437                         if (cfra == e->cfra &&
1438                             chanshown == e->chanshown &&
1439                             rectx == e->rectx && 
1440                             recty == e->recty) {
1441                                 success = TRUE;
1442                                 found_something = TRUE;
1443                                 break;
1444                         }
1445                 }
1446
1447                 if (!e) {
1448                         for (e = prefetch_wait.first; e; e = e->next) {
1449                                 if (cfra == e->cfra &&
1450                                     chanshown == e->chanshown &&
1451                                     rectx == e->rectx && 
1452                                     recty == e->recty) {
1453                                         found_something = TRUE;
1454                                         break;
1455                                 }
1456                         }
1457                 }
1458
1459                 if (!e) {
1460                         PrefetchThread *tslot;
1461
1462                         for(tslot = running_threads.first; 
1463                             tslot; tslot= tslot->next) {
1464                                 if (tslot->current &&
1465                                     cfra == tslot->current->cfra &&
1466                                     chanshown == tslot->current->chanshown &&
1467                                     rectx == tslot->current->rectx && 
1468                                     recty == tslot->current->recty) {
1469                                         found_something = TRUE;
1470                                         break;
1471                                 }
1472                         }
1473                 }
1474
1475                 /* e->ibuf is unrefed by render thread on next round. */
1476
1477                 if (e) {
1478                         seq_last_given_monoton_cfra = e->monoton_cfra;
1479                 }
1480
1481                 pthread_mutex_unlock(&queue_lock);
1482
1483                 if (!success) {
1484                         e = NULL;
1485
1486                         if (!found_something) {
1487                                 fprintf(stderr, 
1488                                         "SEQ-THREAD: Requested frame "
1489                                         "not in queue ???\n");
1490                                 break;
1491                         }
1492                         pthread_mutex_lock(&frame_done_lock);
1493                         pthread_cond_wait(&frame_done_cond, &frame_done_lock);
1494                         pthread_mutex_unlock(&frame_done_lock);
1495                 }
1496         }
1497         
1498         return e ? e->ibuf : 0;
1499 }
1500
1501 /* Functions to free imbuf and anim data on changes */
1502
1503 static void free_imbuf_strip_elem(StripElem *se)
1504 {
1505         if (se->ibuf) {
1506                 if (se->ok != 2)
1507                         IMB_freeImBuf(se->ibuf);
1508                 se->ibuf= 0;
1509                 se->ok= 1;
1510                 se->se1= se->se2= se->se3= 0;
1511         }
1512 }
1513
1514 static void free_anim_seq(Sequence *seq)
1515 {
1516         if(seq->anim) {
1517                 IMB_free_anim(seq->anim);
1518                 seq->anim = 0;
1519         }
1520 }
1521
1522 void free_imbuf_seq_except(int cfra)
1523 {
1524         Editing *ed= G.scene->ed;
1525         Sequence *seq;
1526         StripElem *se;
1527         int a;
1528
1529         if(ed==0) return;
1530
1531         WHILE_SEQ(&ed->seqbase) {
1532                 if(seq->strip) {
1533                         for(a=0, se= seq->strip->stripdata; a<seq->len; a++, se++)
1534                                 if(se!=seq->curelem)
1535                                         free_imbuf_strip_elem(se);
1536
1537                         if(seq->type==SEQ_MOVIE)
1538                                 if(seq->startdisp > cfra || seq->enddisp < cfra)
1539                                         free_anim_seq(seq);
1540                 }
1541         }
1542         END_SEQ
1543 }
1544
1545 void free_imbuf_seq()
1546 {
1547         Editing *ed= G.scene->ed;
1548         Sequence *seq;
1549         StripElem *se;
1550         int a;
1551
1552         if(ed==0) return;
1553
1554         WHILE_SEQ(&ed->seqbase) {
1555                 if(seq->strip) {
1556                         for(a=0, se= seq->strip->stripdata; a<seq->len; a++, se++)
1557                                 free_imbuf_strip_elem(se);
1558
1559                         if(seq->type==SEQ_MOVIE)
1560                                 free_anim_seq(seq);
1561                         if(seq->type==SEQ_SPEED) {
1562                                 sequence_effect_speed_rebuild_map(seq, 1);
1563                         }
1564                 }
1565         }
1566         END_SEQ
1567 }
1568
1569 void free_imbuf_seq_with_ipo(struct Ipo *ipo)
1570 {
1571         /* force update of all sequences with this ipo, on ipo changes */
1572         Editing *ed= G.scene->ed;
1573         Sequence *seq;
1574
1575         if(ed==0) return;
1576
1577         WHILE_SEQ(&ed->seqbase) {
1578                 if(seq->ipo == ipo) {
1579                         update_changed_seq_and_deps(seq, 0, 1);
1580                         if(seq->type == SEQ_SPEED) {
1581                                 sequence_effect_speed_rebuild_map(seq, 1);
1582                         }
1583                 }
1584         }
1585         END_SEQ
1586 }
1587
1588 static int update_changed_seq_recurs(Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change)
1589 {
1590         Sequence *subseq;
1591         int a, free_imbuf = 0;
1592         StripElem *se;
1593
1594         /* recurs downwards to see if this seq depends on the changed seq */
1595
1596         if(seq == NULL)
1597                 return 0;
1598
1599         if(seq == changed_seq)
1600                 free_imbuf = 1;
1601         
1602         for(subseq=seq->seqbase.first; subseq; subseq=subseq->next)
1603                 if(update_changed_seq_recurs(subseq, changed_seq, len_change, ibuf_change))
1604                         free_imbuf = 1;
1605         
1606         if(seq->seq1)
1607                 if(update_changed_seq_recurs(seq->seq1, changed_seq, len_change, ibuf_change))
1608                         free_imbuf = 1;
1609         if(seq->seq2 && (seq->seq2 != seq->seq1))
1610                 if(update_changed_seq_recurs(seq->seq2, changed_seq, len_change, ibuf_change))
1611                         free_imbuf = 1;
1612         if(seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2))
1613                 if(update_changed_seq_recurs(seq->seq3, changed_seq, len_change, ibuf_change))
1614                         free_imbuf = 1;
1615         
1616         if(free_imbuf) {
1617                 if(ibuf_change) {
1618                         for(a=0, se= seq->strip->stripdata; a<seq->len; a++, se++)
1619                                 free_imbuf_strip_elem(se);
1620                 
1621                         if(seq->type==SEQ_MOVIE)
1622                                 free_anim_seq(seq);
1623                         if(seq->type == SEQ_SPEED) {
1624                                 sequence_effect_speed_rebuild_map(seq, 1);
1625                         }
1626                 }
1627
1628                 if(len_change)
1629                         calc_sequence(seq);
1630         }
1631         
1632         return free_imbuf;
1633 }
1634
1635 void update_changed_seq_and_deps(Sequence *changed_seq, int len_change, int ibuf_change)
1636 {
1637         Editing *ed= G.scene->ed;
1638         Sequence *seq;
1639
1640         if (!ed) return;
1641
1642         for (seq=ed->seqbase.first; seq; seq=seq->next)
1643                 update_changed_seq_recurs(seq, changed_seq, len_change, ibuf_change);
1644 }
1645
1646 /* bad levell call... */
1647 void do_render_seq(RenderResult *rr, int cfra)
1648 {
1649         ImBuf *ibuf;
1650
1651         G.f |= G_PLAYANIM;      /* waitcursor patch */
1652
1653         ibuf= give_ibuf_seq(rr->rectx, rr->recty, cfra, 0);
1654         
1655         if(ibuf) {
1656                 
1657                 if(ibuf->rect_float) {
1658                         if (!rr->rectf)
1659                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
1660                         
1661                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
1662                         
1663                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
1664                            can hang around when sequence render has rendered a 32 bits one before */
1665                         if(rr->rect32) {
1666                                 MEM_freeN(rr->rect32);
1667                                 rr->rect32= NULL;
1668                         }
1669                 }
1670                 else if(ibuf->rect) {
1671                         if (!rr->rect32)
1672                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
1673
1674                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
1675
1676                         /* if (ibuf->zbuf) { */
1677                         /*      if (R.rectz) freeN(R.rectz); */
1678                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
1679                         /* } */
1680                 }
1681                 
1682                 /* Let the cache limitor take care of this (schlaile) */
1683                 /* While render let's keep all memory available for render 
1684                    (ton)
1685                    At least if free memory is tight...
1686                    This can make a big difference in encoding speed
1687                    (it is around 4 times(!) faster, if we do not waste time
1688                    on freeing _all_ buffers every time on long timelines...)
1689                    (schlaile)
1690                 */
1691                 {
1692                         extern int mem_in_use;
1693                         extern int mmap_in_use;
1694
1695                         int max = MEM_CacheLimiter_get_maximum();
1696                         if (max != 0 && mem_in_use + mmap_in_use > max) {
1697                                 fprintf(stderr, "mem_in_use = %d, max = %d\n",
1698                                         mem_in_use + mmap_in_use, max);
1699                                 fprintf(stderr, "Cleaning up, please wait...\n"
1700                                         "If this happens very often,\n"
1701                                         "consider "
1702                                         "raising the memcache limit in the "
1703                                         "user preferences.\n");
1704                                 free_imbuf_seq();
1705                         }
1706                 }
1707         }
1708         else {
1709                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
1710                 if (rr->rectf)
1711                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
1712                 else if (rr->rect32)
1713                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
1714                 else
1715                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
1716         }
1717         
1718         G.f &= ~G_PLAYANIM;
1719
1720 }