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