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