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