remove misc unused vars and correct theme name for face angles.
[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 #include <stddef.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36 #include "MEM_CacheLimiterC-Api.h"
37
38 #include "DNA_sequence_types.h"
39 #include "DNA_scene_types.h"
40 #include "DNA_anim_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_sound_types.h"
43
44 #include "BLI_math.h"
45 #include "BLI_fileops.h"
46 #include "BLI_listbase.h"
47 #include "BLI_path_util.h"
48 #include "BLI_string.h"
49 #include "BLI_threads.h"
50 #include "BLI_utildefines.h"
51
52 #include "BKE_animsys.h"
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_main.h"
56 #include "BKE_sequencer.h"
57 #include "BKE_fcurve.h"
58 #include "BKE_scene.h"
59 #include "RNA_access.h"
60 #include "BKE_utildefines.h"
61
62 #include "RE_pipeline.h"
63
64 #include <pthread.h>
65
66 #include "IMB_imbuf.h"
67 #include "IMB_imbuf_types.h"
68
69 #include "BKE_context.h"
70 #include "BKE_sound.h"
71 #include "AUD_C-API.h"
72
73 #ifdef WIN32
74 #define snprintf _snprintf
75 #endif
76
77 /* **** XXX ******** */
78 //static void waitcursor(int val) {}
79 //static int blender_test_break() {return 0;}
80
81 /* **** XXX ******** */
82 #define SELECT 1
83 ListBase seqbase_clipboard;
84 int seqbase_clipboard_frame;
85 SequencerDrawView sequencer_view3d_cb= NULL; /* NULL in background mode */
86
87
88 void printf_strip(Sequence *seq)
89 {
90         fprintf(stderr, "name: '%s', len:%d, start:%d, (startofs:%d, endofs:%d), (startstill:%d, endstill:%d), machine:%d, (startdisp:%d, enddisp:%d)\n",
91                         seq->name, seq->len, seq->start, seq->startofs, seq->endofs, seq->startstill, seq->endstill, seq->machine, seq->startdisp, seq->enddisp);
92         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));
93 }
94
95 int seqbase_recursive_apply(ListBase *seqbase, int (*apply_func)(Sequence *seq, void *), void *arg)
96 {
97         Sequence *iseq;
98         for(iseq= seqbase->first; iseq; iseq= iseq->next) {
99                 if(seq_recursive_apply(iseq, apply_func, arg) == -1)
100                         return -1; /* bail out */
101         }
102         return 1;
103 }
104
105 int seq_recursive_apply(Sequence *seq, int (*apply_func)(Sequence *, void *), void *arg)
106 {
107         int ret= apply_func(seq, arg);
108
109         if(ret == -1)
110                 return -1;  /* bail out */
111
112         if(ret && seq->seqbase.first)
113                 ret = seqbase_recursive_apply(&seq->seqbase, apply_func, arg);
114
115         return ret;
116 }
117
118 /* **********************************************************************
119    alloc / free functions
120    ********************************************************************** */
121
122
123
124 void new_tstripdata(Sequence *seq)
125 {
126         if(seq->strip) {
127                 seq->strip->len= seq->len;
128         }
129 }
130
131
132 /* free */
133
134 static void free_proxy_seq(Sequence *seq)
135 {
136         if (seq->strip && seq->strip->proxy && seq->strip->proxy->anim) {
137                 IMB_free_anim(seq->strip->proxy->anim);
138                 seq->strip->proxy->anim = 0;
139         }
140 }
141
142 void seq_free_strip(Strip *strip)
143 {
144         strip->us--;
145         if(strip->us>0) return;
146         if(strip->us<0) {
147                 printf("error: negative users in strip\n");
148                 return;
149         }
150
151         if (strip->stripdata) {
152                 MEM_freeN(strip->stripdata);
153         }
154
155         if (strip->proxy) {
156                 if (strip->proxy->anim) {
157                         IMB_free_anim(strip->proxy->anim);
158                 }
159
160                 MEM_freeN(strip->proxy);
161         }
162         if (strip->crop) {
163                 MEM_freeN(strip->crop);
164         }
165         if (strip->transform) {
166                 MEM_freeN(strip->transform);
167         }
168         if (strip->color_balance) {
169                 MEM_freeN(strip->color_balance);
170         }
171
172         MEM_freeN(strip);
173 }
174
175 static void seq_free_animdata(Scene *scene, Sequence *seq);
176
177 void seq_free_sequence(Scene *scene, Sequence *seq)
178 {
179         if(seq->strip) seq_free_strip(seq->strip);
180
181         if(seq->anim) IMB_free_anim(seq->anim);
182
183         if (seq->type & SEQ_EFFECT) {
184                 struct SeqEffectHandle sh = get_sequence_effect(seq);
185
186                 sh.free(seq);
187         }
188
189         /* clipboard has no scene and will never have a sound handle or be active */
190         if(scene) {
191                 Editing *ed = scene->ed;
192
193                 if (ed->act_seq==seq)
194                         ed->act_seq= NULL;
195
196                 if(seq->scene_sound)
197                         sound_remove_scene_sound(scene, seq->scene_sound);
198
199                 seq_free_animdata(scene, seq);
200         }
201
202         MEM_freeN(seq);
203 }
204
205 Editing *seq_give_editing(Scene *scene, int alloc)
206 {
207         if (scene->ed == NULL && alloc) {
208                 Editing *ed;
209
210                 ed= scene->ed= MEM_callocN( sizeof(Editing), "addseq");
211                 ed->seqbasep= &ed->seqbase;
212         }
213         return scene->ed;
214 }
215
216 void seq_free_clipboard(void)
217 {
218         Sequence *seq, *nseq;
219
220         for(seq= seqbase_clipboard.first; seq; seq= nseq) {
221                 nseq= seq->next;
222                 seq_free_sequence(NULL, seq);
223         }
224         seqbase_clipboard.first= seqbase_clipboard.last= NULL;
225 }
226
227 void seq_free_editing(Scene *scene)
228 {
229         Editing *ed = scene->ed;
230         MetaStack *ms;
231         Sequence *seq;
232
233         if(ed==NULL)
234                 return;
235
236         SEQ_BEGIN(ed, seq) {
237                 seq_free_sequence(scene, seq);
238         }
239         SEQ_END
240
241         while((ms= ed->metastack.first)) {
242                 BLI_remlink(&ed->metastack, ms);
243                 MEM_freeN(ms);
244         }
245
246         MEM_freeN(ed);
247 }
248
249 /* **********************************************************************
250    * sequencer pipeline functions
251    ********************************************************************** */
252
253 SeqRenderData seq_new_render_data(
254         struct Main * bmain, struct Scene * scene,
255         int rectx, int recty, int preview_render_size)
256 {
257         SeqRenderData rval;
258
259         rval.bmain = bmain;
260         rval.scene = scene;
261         rval.rectx = rectx;
262         rval.recty = recty;
263         rval.preview_render_size = preview_render_size;
264         rval.motion_blur_samples = 0;
265         rval.motion_blur_shutter = 0;
266
267         return rval;
268 }
269
270 int seq_cmp_render_data(const SeqRenderData * a, const SeqRenderData * b)
271 {
272         if (a->preview_render_size < b->preview_render_size) {
273                 return -1;
274         }
275         if (a->preview_render_size > b->preview_render_size) {
276                 return 1;
277         }
278         
279         if (a->rectx < b->rectx) {
280                 return -1;
281         }
282         if (a->rectx > b->rectx) {
283                 return 1;
284         }
285
286         if (a->recty < b->recty) {
287                 return -1;
288         }
289         if (a->recty > b->recty) {
290                 return 1;
291         }
292
293         if (a->bmain < b->bmain) {
294                 return -1;
295         }
296         if (a->bmain > b->bmain) {
297                 return 1;
298         }
299
300         if (a->scene < b->scene) {
301                 return -1;
302         }
303         if (a->scene > b->scene) {
304                 return 1;
305         }
306
307         if (a->motion_blur_shutter < b->motion_blur_shutter) {
308                 return -1;
309         }
310         if (a->motion_blur_shutter > b->motion_blur_shutter) {
311                 return 1;
312         }
313
314         if (a->motion_blur_samples < b->motion_blur_samples) {
315                 return -1;
316         }
317         if (a->motion_blur_samples > b->motion_blur_samples) {
318                 return 1;
319         }
320
321         return 0;
322 }
323
324 unsigned int seq_hash_render_data(const SeqRenderData * a)
325 {
326         unsigned int rval = a->rectx + a->recty;
327
328         rval ^= a->preview_render_size;
329         rval ^= ((intptr_t) a->bmain) << 6;
330         rval ^= ((intptr_t) a->scene) << 6;
331         rval ^= (int) (a->motion_blur_shutter * 100.0) << 10;
332         rval ^= a->motion_blur_samples << 24;
333         
334         return rval;
335 }
336
337 /* ************************* iterator ************************** */
338 /* *************** (replaces old WHILE_SEQ) ********************* */
339 /* **************** use now SEQ_BEGIN() SEQ_END ***************** */
340
341 /* sequence strip iterator:
342  * - builds a full array, recursively into meta strips */
343
344 static void seq_count(ListBase *seqbase, int *tot)
345 {
346         Sequence *seq;
347
348         for(seq=seqbase->first; seq; seq=seq->next) {
349                 (*tot)++;
350
351                 if(seq->seqbase.first)
352                         seq_count(&seq->seqbase, tot);
353         }
354 }
355
356 static void seq_build_array(ListBase *seqbase, Sequence ***array, int depth)
357 {
358         Sequence *seq;
359
360         for(seq=seqbase->first; seq; seq=seq->next) {
361                 seq->depth= depth;
362
363                 if(seq->seqbase.first)
364                         seq_build_array(&seq->seqbase, array, depth+1);
365
366                 **array= seq;
367                 (*array)++;
368         }
369 }
370
371 void seq_array(Editing *ed, Sequence ***seqarray, int *tot, int use_pointer)
372 {
373         Sequence **array;
374
375         *seqarray= NULL;
376         *tot= 0;
377
378         if(ed == NULL)
379                 return;
380
381         if(use_pointer)
382                 seq_count(ed->seqbasep, tot);
383         else
384                 seq_count(&ed->seqbase, tot);
385
386         if(*tot == 0)
387                 return;
388
389         *seqarray= array= MEM_mallocN(sizeof(Sequence *)*(*tot), "SeqArray");
390         if(use_pointer)
391                 seq_build_array(ed->seqbasep, &array, 0);
392         else
393                 seq_build_array(&ed->seqbase, &array, 0);
394 }
395
396 void seq_begin(Editing *ed, SeqIterator *iter, int use_pointer)
397 {
398         memset(iter, 0, sizeof(*iter));
399         seq_array(ed, &iter->array, &iter->tot, use_pointer);
400
401         if(iter->tot) {
402                 iter->cur= 0;
403                 iter->seq= iter->array[iter->cur];
404                 iter->valid= 1;
405         }
406 }
407
408 void seq_next(SeqIterator *iter)
409 {
410         if(++iter->cur < iter->tot)
411                 iter->seq= iter->array[iter->cur];
412         else
413                 iter->valid= 0;
414 }
415
416 void seq_end(SeqIterator *iter)
417 {
418         if(iter->array)
419                 MEM_freeN(iter->array);
420
421         iter->valid= 0;
422 }
423
424 /*
425   **********************************************************************
426   * build_seqar
427   **********************************************************************
428   * Build a complete array of _all_ sequencies (including those
429   * in metastrips!)
430   **********************************************************************
431 */
432
433 static void do_seq_count(ListBase *seqbase, int *totseq)
434 {
435         Sequence *seq;
436
437         seq= seqbase->first;
438         while(seq) {
439                 (*totseq)++;
440                 if(seq->seqbase.first) do_seq_count(&seq->seqbase, totseq);
441                 seq= seq->next;
442         }
443 }
444
445 static void do_build_seqar(ListBase *seqbase, Sequence ***seqar, int depth)
446 {
447         Sequence *seq;
448
449         seq= seqbase->first;
450         while(seq) {
451                 seq->depth= depth;
452                 if(seq->seqbase.first) do_build_seqar(&seq->seqbase, seqar, depth+1);
453                 **seqar= seq;
454                 (*seqar)++;
455                 seq= seq->next;
456         }
457 }
458
459 void build_seqar(ListBase *seqbase, Sequence  ***seqar, int *totseq)
460 {
461         Sequence **tseqar;
462
463         *totseq= 0;
464         do_seq_count(seqbase, totseq);
465
466         if(*totseq==0) {
467                 *seqar= NULL;
468                 return;
469         }
470         *seqar= MEM_mallocN(sizeof(void *)* *totseq, "seqar");
471         tseqar= *seqar;
472
473         do_build_seqar(seqbase, seqar, 0);
474         *seqar= tseqar;
475 }
476
477 static void do_seq_count_cb(ListBase *seqbase, int *totseq,
478                                 int (*test_func)(Sequence * seq))
479 {
480         Sequence *seq;
481
482         seq= seqbase->first;
483         while(seq) {
484                 int test = test_func(seq);
485                 if (test & BUILD_SEQAR_COUNT_CURRENT) {
486                         (*totseq)++;
487                 }
488                 if(seq->seqbase.first && (test & BUILD_SEQAR_COUNT_CHILDREN)) {
489                         do_seq_count_cb(&seq->seqbase, totseq, test_func);
490                 }
491                 seq= seq->next;
492         }
493 }
494
495 static void do_build_seqar_cb(ListBase *seqbase, Sequence ***seqar, int depth,
496                                   int (*test_func)(Sequence * seq))
497 {
498         Sequence *seq;
499
500         seq= seqbase->first;
501         while(seq) {
502                 int test = test_func(seq);
503                 seq->depth= depth;
504
505                 if(seq->seqbase.first && (test & BUILD_SEQAR_COUNT_CHILDREN)) {
506                         do_build_seqar_cb(&seq->seqbase, seqar, depth+1, test_func);
507                 }
508                 if (test & BUILD_SEQAR_COUNT_CURRENT) {
509                         **seqar= seq;
510                         (*seqar)++;
511                 }
512                 seq= seq->next;
513         }
514 }
515
516 void build_seqar_cb(ListBase *seqbase, Sequence  ***seqar, int *totseq,
517                         int (*test_func)(Sequence * seq))
518 {
519         Sequence **tseqar;
520
521         *totseq= 0;
522         do_seq_count_cb(seqbase, totseq, test_func);
523
524         if(*totseq==0) {
525                 *seqar= NULL;
526                 return;
527         }
528         *seqar= MEM_mallocN(sizeof(void *)* *totseq, "seqar");
529         tseqar= *seqar;
530
531         do_build_seqar_cb(seqbase, seqar, 0, test_func);
532         *seqar= tseqar;
533 }
534
535
536 void calc_sequence_disp(Scene *scene, Sequence *seq)
537 {
538         if(seq->startofs && seq->startstill) seq->startstill= 0;
539         if(seq->endofs && seq->endstill) seq->endstill= 0;
540         
541         seq->startdisp= seq->start + seq->startofs - seq->startstill;
542         seq->enddisp= seq->start+seq->len - seq->endofs + seq->endstill;
543         
544         seq->handsize= 10.0;    /* 10 frames */
545         if( seq->enddisp-seq->startdisp < 10 ) {
546                 seq->handsize= (float)(0.5*(seq->enddisp-seq->startdisp));
547         }
548         else if(seq->enddisp-seq->startdisp > 250) {
549                 seq->handsize= (float)((seq->enddisp-seq->startdisp)/25);
550         }
551
552         seq_update_sound(scene, seq);
553 }
554
555 static void seq_update_sound_bounds_recursive(Scene *scene, Sequence *metaseq)
556 {
557         Sequence *seq;
558
559         /* for sound we go over full meta tree to update bounds of the sound strips,
560            since sound is played outside of evaluating the imbufs, */
561         for(seq=metaseq->seqbase.first; seq; seq=seq->next) {
562                 if(seq->type == SEQ_META) {
563                         seq_update_sound_bounds_recursive(scene, seq);
564                 }
565                 else if(ELEM(seq->type, SEQ_SOUND, SEQ_SCENE)) {
566                         if(seq->scene_sound) {
567                                 int startofs = seq->startofs;
568                                 int endofs = seq->endofs;
569                                 if(seq->startofs + seq->start < metaseq->start + metaseq->startofs)
570                                         startofs = metaseq->start + metaseq->startofs - seq->start;
571
572                                 if(seq->start + seq->len - seq->endofs > metaseq->start + metaseq->len - metaseq->endofs)
573                                         endofs = seq->start + seq->len - metaseq->start - metaseq->len + metaseq->endofs;
574                                 sound_move_scene_sound(scene, seq->scene_sound, seq->start + startofs, seq->start+seq->len - endofs, startofs);
575                         }
576                 }
577         }
578 }
579
580 void calc_sequence(Scene *scene, Sequence *seq)
581 {
582         Sequence *seqm;
583         int min, max;
584
585         /* check all metas recursively */
586         seqm= seq->seqbase.first;
587         while(seqm) {
588                 if(seqm->seqbase.first) calc_sequence(scene, seqm);
589                 seqm= seqm->next;
590         }
591
592         /* effects and meta: automatic start and end */
593
594         if(seq->type & SEQ_EFFECT) {
595                 /* pointers */
596                 if(seq->seq2==NULL) seq->seq2= seq->seq1;
597                 if(seq->seq3==NULL) seq->seq3= seq->seq1;
598
599                 /* effecten go from seq1 -> seq2: test */
600
601                 /* we take the largest start and smallest end */
602
603                 // seq->start= seq->startdisp= MAX2(seq->seq1->startdisp, seq->seq2->startdisp);
604                 // seq->enddisp= MIN2(seq->seq1->enddisp, seq->seq2->enddisp);
605
606                 if (seq->seq1) {
607                         seq->start= seq->startdisp= MAX3(seq->seq1->startdisp, seq->seq2->startdisp, seq->seq3->startdisp);
608                         seq->enddisp= MIN3(seq->seq1->enddisp, seq->seq2->enddisp, seq->seq3->enddisp);
609                         seq->len= seq->enddisp - seq->startdisp;
610                 } else {
611                         calc_sequence_disp(scene, seq);
612                 }
613
614                 if(seq->strip && seq->len!=seq->strip->len) {
615                         new_tstripdata(seq);
616                 }
617
618         }
619         else {
620                 if(seq->type==SEQ_META) {
621                         seqm= seq->seqbase.first;
622                         if(seqm) {
623                                 min=  MAXFRAME * 2;
624                                 max= -MAXFRAME * 2;
625                                 while(seqm) {
626                                         if(seqm->startdisp < min) min= seqm->startdisp;
627                                         if(seqm->enddisp > max) max= seqm->enddisp;
628                                         seqm= seqm->next;
629                                 }
630                                 seq->start= min + seq->anim_startofs;
631                                 seq->len = max-min;
632                                 seq->len -= seq->anim_startofs;
633                                 seq->len -= seq->anim_endofs;
634
635                                 if(seq->strip && seq->len!=seq->strip->len) {
636                                         new_tstripdata(seq);
637                                 }
638                         }
639                         seq_update_sound_bounds_recursive(scene, seq);
640                 }
641                 calc_sequence_disp(scene, seq);
642         }
643 }
644
645 /* note: caller should run calc_sequence(scene, seq) after */
646 void reload_sequence_new_file(Scene *scene, Sequence * seq, int lock_range)
647 {
648         char str[FILE_MAXDIR+FILE_MAXFILE];
649         int prev_startdisp=0, prev_enddisp=0;
650         /* note: dont rename the strip, will break animation curves */
651
652         if (ELEM5(seq->type, SEQ_MOVIE, SEQ_IMAGE, SEQ_SOUND, SEQ_SCENE, SEQ_META)==0) {
653                 return;
654         }
655
656         if(lock_range) {
657                 /* keep so we dont have to move the actual start and end points (only the data) */
658                 calc_sequence_disp(scene, seq);
659                 prev_startdisp= seq->startdisp;
660                 prev_enddisp= seq->enddisp;
661         }
662
663
664         new_tstripdata(seq);
665
666         if (ELEM3(seq->type, SEQ_SCENE, SEQ_META, SEQ_IMAGE)==0) {
667                 BLI_join_dirfile(str, seq->strip->dir, seq->strip->stripdata->name);
668                 BLI_path_abs(str, G.main->name);
669         }
670
671         switch(seq->type) {
672         case SEQ_IMAGE:
673         {
674                 /* Hack? */
675                 size_t olen = MEM_allocN_len(seq->strip->stripdata)/sizeof(struct StripElem);
676
677                 seq->len = olen;
678                 seq->len -= seq->anim_startofs;
679                 seq->len -= seq->anim_endofs;
680                 if (seq->len < 0) {
681                         seq->len = 0;
682                 }
683                 seq->strip->len = seq->len;
684                 break;
685         }
686         case SEQ_MOVIE:
687                 if(seq->anim) IMB_free_anim(seq->anim);
688                 seq->anim = openanim(str, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0));
689
690                 if (!seq->anim) {
691                         return;
692                 }
693         
694                 seq->len = IMB_anim_get_duration(seq->anim);
695                 
696                 seq->anim_preseek = IMB_anim_get_preseek(seq->anim);
697
698                 seq->len -= seq->anim_startofs;
699                 seq->len -= seq->anim_endofs;
700                 if (seq->len < 0) {
701                         seq->len = 0;
702                 }
703                 seq->strip->len = seq->len;
704         case SEQ_SOUND:
705                 if(!seq->sound)
706                         return;
707                 seq->len = ceil(AUD_getInfo(seq->sound->playback_handle).length * FPS);
708                 seq->len -= seq->anim_startofs;
709                 seq->len -= seq->anim_endofs;
710                 if (seq->len < 0) {
711                         seq->len = 0;
712                 }
713                 seq->strip->len = seq->len;
714                 break;
715         case SEQ_SCENE:
716         {
717                 /* 'seq->scenenr' should be replaced with something more reliable */
718                 Scene * sce = G.main->scene.first;
719                 int nr = 1;
720                 
721                 while(sce) {
722                         if(nr == seq->scenenr) {
723                                 break;
724                         }
725                         nr++;
726                         sce= sce->id.next;
727                 }
728
729                 if (sce) {
730                         seq->scene = sce;
731                 }
732
733                 seq->len= seq->scene->r.efra - seq->scene->r.sfra + 1;
734                 seq->len -= seq->anim_startofs;
735                 seq->len -= seq->anim_endofs;
736                 if (seq->len < 0) {
737                         seq->len = 0;
738                 }
739                 seq->strip->len = seq->len;
740                 break;
741         }
742         }
743
744         free_proxy_seq(seq);
745
746         if(lock_range) {
747                 seq_tx_set_final_left(seq, prev_startdisp);
748                 seq_tx_set_final_right(seq, prev_enddisp);
749                 seq_single_fix(seq);
750         }
751         
752         calc_sequence(scene, seq);
753 }
754
755 void sort_seq(Scene *scene)
756 {
757         /* all strips together per kind, and in order of y location ("machine") */
758         ListBase seqbase, effbase;
759         Editing *ed= seq_give_editing(scene, FALSE);
760         Sequence *seq, *seqt;
761
762         
763         if(ed==NULL) return;
764
765         seqbase.first= seqbase.last= 0;
766         effbase.first= effbase.last= 0;
767
768         while( (seq= ed->seqbasep->first) ) {
769                 BLI_remlink(ed->seqbasep, seq);
770
771                 if(seq->type & SEQ_EFFECT) {
772                         seqt= effbase.first;
773                         while(seqt) {
774                                 if(seqt->machine>=seq->machine) {
775                                         BLI_insertlinkbefore(&effbase, seqt, seq);
776                                         break;
777                                 }
778                                 seqt= seqt->next;
779                         }
780                         if(seqt==0) BLI_addtail(&effbase, seq);
781                 }
782                 else {
783                         seqt= seqbase.first;
784                         while(seqt) {
785                                 if(seqt->machine>=seq->machine) {
786                                         BLI_insertlinkbefore(&seqbase, seqt, seq);
787                                         break;
788                                 }
789                                 seqt= seqt->next;
790                         }
791                         if(seqt==0) BLI_addtail(&seqbase, seq);
792                 }
793         }
794
795         BLI_movelisttolist(&seqbase, &effbase);
796         *(ed->seqbasep)= seqbase;
797 }
798
799
800 static int clear_scene_in_allseqs_cb(Sequence *seq, void *arg_pt)
801 {
802         if(seq->scene==(Scene *)arg_pt)
803                 seq->scene= NULL;
804         return 1;
805 }
806
807 void clear_scene_in_allseqs(Main *bmain, Scene *scene)
808 {
809         Scene *scene_iter;
810
811         /* when a scene is deleted: test all seqs */
812         for(scene_iter= bmain->scene.first; scene_iter; scene_iter= scene_iter->id.next) {
813                 if(scene_iter != scene && scene_iter->ed) {
814                         seqbase_recursive_apply(&scene_iter->ed->seqbase, clear_scene_in_allseqs_cb, scene);
815                 }
816         }
817 }
818
819 typedef struct SeqUniqueInfo {
820         Sequence *seq;
821         char name_src[32];
822         char name_dest[32];
823         int count;
824         int match;
825 } SeqUniqueInfo;
826
827 /*
828 static void seqbase_unique_name(ListBase *seqbasep, Sequence *seq)
829 {
830          BLI_uniquename(seqbasep, seq, "Sequence", '.', offsetof(Sequence, name), SEQ_NAME_MAXSTR);
831 }*/
832
833 static void seqbase_unique_name(ListBase *seqbasep, SeqUniqueInfo *sui)
834 {
835         Sequence *seq;
836         for(seq=seqbasep->first; seq; seq= seq->next) {
837                 if (sui->seq != seq && strcmp(sui->name_dest, seq->name+2)==0) {
838                         sprintf(sui->name_dest, "%.17s.%03d",  sui->name_src, sui->count++); /*24 - 2 for prefix, -1 for \0 */
839                         sui->match= 1; /* be sure to re-scan */
840                 }
841         }
842 }
843
844 static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt)
845 {
846         if(seq->seqbase.first)
847                 seqbase_unique_name(&seq->seqbase, (SeqUniqueInfo *)arg_pt);
848         return 1;
849 }
850
851 void seqbase_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq)
852 {
853         SeqUniqueInfo sui;
854         char *dot;
855         sui.seq= seq;
856         strcpy(sui.name_src, seq->name+2);
857         strcpy(sui.name_dest, seq->name+2);
858
859         sui.count= 1;
860         sui.match= 1; /* assume the worst to start the loop */
861
862         /* Strip off the suffix */
863         if ((dot=strrchr(sui.name_src, '.'))) {
864                 *dot= '\0';
865                 dot++;
866
867                 if(*dot)
868                         sui.count= atoi(dot) + 1;
869         }
870
871         while(sui.match) {
872                 sui.match= 0;
873                 seqbase_unique_name(seqbasep, &sui);
874                 seqbase_recursive_apply(seqbasep, seqbase_unique_name_recursive_cb, &sui);
875         }
876
877         strcpy(seq->name+2, sui.name_dest);
878 }
879
880 static const char *give_seqname_by_type(int type)
881 {
882         switch(type) {
883         case SEQ_META:       return "Meta";
884         case SEQ_IMAGE:      return "Image";
885         case SEQ_SCENE:      return "Scene";
886         case SEQ_MOVIE:      return "Movie";
887         case SEQ_SOUND:      return "Audio";
888         case SEQ_CROSS:      return "Cross";
889         case SEQ_GAMCROSS:   return "Gamma Cross";
890         case SEQ_ADD:        return "Add";
891         case SEQ_SUB:        return "Sub";
892         case SEQ_MUL:        return "Mul";
893         case SEQ_ALPHAOVER:  return "Alpha Over";
894         case SEQ_ALPHAUNDER: return "Alpha Under";
895         case SEQ_OVERDROP:   return "Over Drop";
896         case SEQ_WIPE:       return "Wipe";
897         case SEQ_GLOW:       return "Glow";
898         case SEQ_TRANSFORM:  return "Transform";
899         case SEQ_COLOR:      return "Color";
900         case SEQ_MULTICAM:   return "Multicam";
901         case SEQ_SPEED:      return "Speed";
902         default:
903                 return NULL;
904         }
905 }
906
907 const char *give_seqname(Sequence *seq)
908 {
909         const char *name = give_seqname_by_type(seq->type);
910
911         if (!name) {
912                 if(seq->type<SEQ_EFFECT) {
913                         return seq->strip->dir;
914                 } else if(seq->type==SEQ_PLUGIN) {
915                         if(!(seq->flag & SEQ_EFFECT_NOT_LOADED) &&
916                            seq->plugin && seq->plugin->doit) {
917                                 return seq->plugin->pname;
918                         } else {
919                                 return "Plugin";
920                         }
921                 } else {
922                         return "Effect";
923                 }
924         }
925         return name;
926 }
927
928 /* ***************** DO THE SEQUENCE ***************** */
929
930 static void make_black_ibuf(ImBuf *ibuf)
931 {
932         unsigned int *rect;
933         float *rect_float;
934         int tot;
935
936         if(ibuf==0 || (ibuf->rect==0 && ibuf->rect_float==0)) return;
937
938         tot= ibuf->x*ibuf->y;
939
940         rect= ibuf->rect;
941         rect_float = ibuf->rect_float;
942
943         if (rect) {
944                 memset(rect,       0, tot * sizeof(char) * 4);
945         }
946
947         if (rect_float) {
948                 memset(rect_float, 0, tot * sizeof(float) * 4);
949         }
950 }
951
952 static void multibuf(ImBuf *ibuf, float fmul)
953 {
954         char *rt;
955         float *rt_float;
956
957         int a, mul, icol;
958
959         mul= (int)(256.0*fmul);
960         rt= (char *)ibuf->rect;
961         rt_float = ibuf->rect_float;
962
963         if (rt) {
964                 a= ibuf->x*ibuf->y;
965                 while(a--) {
966
967                         icol= (mul*rt[0])>>8;
968                         if(icol>254) rt[0]= 255; else rt[0]= icol;
969                         icol= (mul*rt[1])>>8;
970                         if(icol>254) rt[1]= 255; else rt[1]= icol;
971                         icol= (mul*rt[2])>>8;
972                         if(icol>254) rt[2]= 255; else rt[2]= icol;
973                         icol= (mul*rt[3])>>8;
974                         if(icol>254) rt[3]= 255; else rt[3]= icol;
975                         
976                         rt+= 4;
977                 }
978         }
979         if (rt_float) {
980                 a= ibuf->x*ibuf->y;
981                 while(a--) {
982                         rt_float[0] *= fmul;
983                         rt_float[1] *= fmul;
984                         rt_float[2] *= fmul;
985                         rt_float[3] *= fmul;
986                         
987                         rt_float += 4;
988                 }
989         }
990 }
991
992 static float give_stripelem_index(Sequence *seq, float cfra)
993 {
994         float nr;
995         int sta = seq->start;
996         int end = seq->start+seq->len-1;
997
998         if(seq->len == 0) return -1;
999
1000         if(seq->flag&SEQ_REVERSE_FRAMES) {      
1001                 /*reverse frame in this sequence */
1002                 if(cfra <= sta) nr= seq->len-1;
1003                 else if(cfra >= end) nr= 0;
1004                 else nr= end - cfra;
1005         } else {
1006                 if(cfra <= sta) nr= 0;
1007                 else if(cfra >= end) nr= seq->len-1;
1008                 else nr= cfra - sta;
1009         }
1010         
1011         if (seq->strobe < 1.0) seq->strobe = 1.0;
1012         
1013         if (seq->strobe > 1.0) {
1014                 nr -= fmod((double)nr, (double)seq->strobe);
1015         }
1016
1017         return nr;
1018 }
1019
1020 StripElem *give_stripelem(Sequence *seq, int cfra)
1021 {
1022         StripElem *se= seq->strip->stripdata;
1023
1024         if(seq->type != SEQ_MOVIE) { /* movie use the first */
1025                 int nr = (int) give_stripelem_index(seq, cfra);
1026
1027                 if (nr == -1 || se == 0) return 0;
1028         
1029                 se += nr + seq->anim_startofs;
1030         }
1031         return se;
1032 }
1033
1034 static int evaluate_seq_frame_gen(Sequence ** seq_arr, ListBase *seqbase, int cfra)
1035 {
1036         Sequence *seq;
1037         int totseq=0;
1038
1039         memset(seq_arr, 0, sizeof(Sequence*) * (MAXSEQ+1));
1040
1041         seq= seqbase->first;
1042         while(seq) {
1043                 if(seq->startdisp <=cfra && seq->enddisp > cfra) {
1044                         seq_arr[seq->machine]= seq;
1045                         totseq++;
1046                 }
1047                 seq= seq->next;
1048         }
1049
1050         return totseq;
1051 }
1052
1053 int evaluate_seq_frame(Scene *scene, int cfra)
1054 {
1055         Editing *ed= seq_give_editing(scene, FALSE);
1056         Sequence *seq_arr[MAXSEQ+1];
1057
1058         if(ed==NULL) return 0;
1059         return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra);
1060 }
1061
1062 static int video_seq_is_rendered(Sequence * seq)
1063 {
1064         return (seq && !(seq->flag & SEQ_MUTE) && seq->type != SEQ_SOUND);
1065 }
1066
1067 static int get_shown_sequences( ListBase * seqbasep, int cfra, int chanshown, Sequence ** seq_arr_out)
1068 {
1069         Sequence *seq_arr[MAXSEQ+1];
1070         int b = chanshown;
1071         int cnt = 0;
1072
1073         if (b > MAXSEQ) {
1074                 return 0;
1075         }
1076
1077         if(evaluate_seq_frame_gen(seq_arr, seqbasep, cfra)) {
1078                 if (b > 0) {
1079                         if (seq_arr[b] == 0) {
1080                                 return 0;
1081                         }
1082                 } else {
1083                         for (b = MAXSEQ; b > 0; b--) {
1084                                 if (video_seq_is_rendered(seq_arr[b])) {
1085                                         break;
1086                                 }
1087                         }
1088                 }
1089         }
1090         
1091         chanshown = b;
1092
1093         for (;b > 0; b--) {
1094                 if (video_seq_is_rendered(seq_arr[b])) {
1095                         if (seq_arr[b]->blend_mode == SEQ_BLEND_REPLACE) {
1096                                 break;
1097                         }
1098                 }
1099         }
1100
1101         for (;b <= chanshown && b >= 0; b++) {
1102                 if (video_seq_is_rendered(seq_arr[b])) {
1103                         seq_arr_out[cnt++] = seq_arr[b];
1104                 }
1105         }
1106
1107         return cnt;
1108 }
1109  
1110
1111 /* **********************************************************************
1112    proxy management
1113    ********************************************************************** */
1114
1115 #define PROXY_MAXFILE (2*FILE_MAXDIR+FILE_MAXFILE)
1116
1117 static int seq_proxy_get_fname(SeqRenderData context, Sequence * seq, int cfra, char * name)
1118 {
1119         int frameno;
1120         char dir[FILE_MAXDIR];
1121
1122         if (!seq->strip->proxy) {
1123                 return FALSE;
1124         }
1125
1126         if (seq->flag & (SEQ_USE_PROXY_CUSTOM_DIR|SEQ_USE_PROXY_CUSTOM_FILE)) {
1127                 strcpy(dir, seq->strip->proxy->dir);
1128         } else {
1129                 if (ELEM(seq->type, SEQ_IMAGE, SEQ_MOVIE)) {
1130                         snprintf(dir, FILE_MAXDIR, "%s/BL_proxy", seq->strip->dir);
1131                 } else {
1132                         return FALSE;
1133                 }
1134         }
1135
1136         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1137                 BLI_join_dirfile(name, dir, seq->strip->proxy->file);
1138                 BLI_path_abs(name, G.main->name);
1139
1140                 return TRUE;
1141         }
1142
1143         /* generate a separate proxy directory for each preview size */
1144
1145         switch(seq->type) {
1146         case SEQ_IMAGE:
1147                 snprintf(name, PROXY_MAXFILE, "%s/images/%d/%s_proxy", dir,
1148                          context.preview_render_size, 
1149                          give_stripelem(seq, cfra)->name);
1150                 frameno = 1;
1151                 break;
1152         case SEQ_MOVIE:
1153                 frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1154                 snprintf(name, PROXY_MAXFILE, "%s/%s/%d/####", dir,
1155                          seq->strip->stripdata->name, context.preview_render_size);
1156                 break;
1157         default:
1158                 frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1159                 snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####", dir, 
1160                          context.preview_render_size);
1161         }
1162
1163         BLI_path_abs(name, G.main->name);
1164         BLI_path_frame(name, frameno, 0);
1165
1166         strcat(name, ".jpg");
1167
1168         return TRUE;
1169 }
1170
1171 static struct ImBuf * seq_proxy_fetch(SeqRenderData context, Sequence * seq, int cfra)
1172 {
1173         char name[PROXY_MAXFILE];
1174
1175         if (!(seq->flag & SEQ_USE_PROXY)) {
1176                 return 0;
1177         }
1178
1179         /* rendering at 100% ? No real sense in proxy-ing, right? */
1180         if (context.preview_render_size == 100) {
1181                 return 0;
1182         }
1183
1184         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1185                 int frameno = (int) give_stripelem_index(seq, cfra) + seq->anim_startofs;
1186                 if (seq->strip->proxy->anim == NULL) {
1187                         if (seq_proxy_get_fname(context, seq, cfra, name)==0) {
1188                                 return 0;
1189                         }
1190  
1191                         seq->strip->proxy->anim = openanim(name, IB_rect);
1192                 }
1193                 if (seq->strip->proxy->anim==NULL) {
1194                         return 0;
1195                 }
1196  
1197                 return IMB_anim_absolute(seq->strip->proxy->anim, frameno);
1198         }
1199  
1200         if (seq_proxy_get_fname(context, seq, cfra, name) == 0) {
1201                 return 0;
1202         }
1203
1204         if (BLI_exists(name)) {
1205                 return IMB_loadiffname(name, IB_rect);
1206         } else {
1207                 return 0;
1208         }
1209 }
1210
1211 #if 0
1212 static void do_build_seq_ibuf(Scene *scene, Sequence * seq, TStripElem *se, int cfra,
1213                                   int build_proxy_run, int preview_render_size);
1214
1215 static void seq_proxy_build_frame(Scene *scene, Sequence * seq, int cfra, int preview_render_size, int seqrectx, int seqrecty)
1216 {
1217         char name[PROXY_MAXFILE];
1218         int quality;
1219         TStripElem * se;
1220         int ok;
1221         int rectx, recty;
1222         struct ImBuf * ibuf;
1223
1224         if (!(seq->flag & SEQ_USE_PROXY)) {
1225                 return;
1226         }
1227
1228         /* rendering at 100% ? No real sense in proxy-ing, right? */
1229         if (preview_render_size == 100) {
1230                 return;
1231         }
1232
1233         /* that's why it is called custom... */
1234         if (seq->flag & SEQ_USE_PROXY_CUSTOM_FILE) {
1235                 return;
1236         }
1237
1238         if (!seq_proxy_get_fname(scene, seq, cfra, name, preview_render_size)) {
1239                 return;
1240         }
1241
1242         se = give_tstripelem(seq, cfra);
1243         if (!se) {
1244                 return;
1245         }
1246
1247         if(se->ibuf) {
1248                 IMB_freeImBuf(se->ibuf);
1249                 se->ibuf = 0;
1250         }
1251         
1252         do_build_seq_ibuf(scene, seq, se, cfra, TRUE, preview_render_size,
1253                           seqrectx, seqrecty);
1254
1255         if (!se->ibuf) {
1256                 return;
1257         }
1258
1259         rectx= (preview_render_size*scene->r.xsch)/100;
1260         recty= (preview_render_size*scene->r.ysch)/100;
1261
1262         ibuf = se->ibuf;
1263
1264         if (ibuf->x != rectx || ibuf->y != recty) {
1265                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1266         }
1267
1268         /* quality is fixed, otherwise one has to generate separate
1269            directories for every quality...
1270
1271            depth = 32 is intentionally left in, otherwise ALPHA channels
1272            won't work... */
1273         quality = seq->strip->proxy->quality;
1274         ibuf->ftype= JPG | quality;
1275
1276         BLI_make_existing_file(name);
1277         
1278         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1279         if (ok == 0) {
1280                 perror(name);
1281         }
1282
1283         IMB_freeImBuf(ibuf);
1284         se->ibuf = 0;
1285 }
1286
1287 static void seq_proxy_rebuild(Scene *scene, Sequence * seq, int seqrectx,
1288                               int seqrecty)
1289 {
1290         int cfra;
1291         float rsize = seq->strip->proxy->size;
1292
1293         waitcursor(1);
1294
1295         G.afbreek = 0;
1296
1297         /* flag management tries to account for strobe and 
1298            other "non-linearities", that might come in the future...
1299            better way would be to "touch" the files, so that _really_
1300            no one is rebuild twice.
1301          */
1302
1303         for (cfra = seq->startdisp; cfra < seq->enddisp; cfra++) {
1304                 TStripElem * tse = give_tstripelem(seq, cfra);
1305
1306                 tse->flag &= ~STRIPELEM_PREVIEW_DONE;
1307         }
1308
1309         
1310
1311         /* a _lot_ faster for movie files, if we read frames in
1312            sequential order */
1313         if (seq->flag & SEQ_REVERSE_FRAMES) {
1314                 for (cfra = seq->enddisp-seq->endstill-1; 
1315                          cfra >= seq->startdisp + seq->startstill; cfra--) {
1316                         TStripElem * tse = give_tstripelem(seq, cfra);
1317
1318                         if (!(tse->flag & STRIPELEM_PREVIEW_DONE)) {
1319 //XXX                           set_timecursor(cfra);
1320                                 seq_proxy_build_frame(scene, seq, cfra, rsize,
1321                                                       seqrectx, seqrecty);
1322                                 tse->flag |= STRIPELEM_PREVIEW_DONE;
1323                         }
1324                         if (blender_test_break()) {
1325                                 break;
1326                         }
1327                 }
1328         } else {
1329                 for (cfra = seq->startdisp + seq->startstill; 
1330                          cfra < seq->enddisp - seq->endstill; cfra++) {
1331                         TStripElem * tse = give_tstripelem(seq, cfra);
1332
1333                         if (!(tse->flag & STRIPELEM_PREVIEW_DONE)) {
1334 //XXX                           set_timecursor(cfra);
1335                                 seq_proxy_build_frame(scene, seq, cfra, rsize,
1336                                                       seqrectx, seqrecty);
1337                                 tse->flag |= STRIPELEM_PREVIEW_DONE;
1338                         }
1339                         if (blender_test_break()) {
1340                                 break;
1341                         }
1342                 }
1343         }
1344         waitcursor(0);
1345 }
1346 #endif
1347
1348
1349 /* **********************************************************************
1350    color balance 
1351    ********************************************************************** */
1352
1353 static StripColorBalance calc_cb(StripColorBalance * cb_)
1354 {
1355         StripColorBalance cb = *cb_;
1356         int c;
1357
1358         for (c = 0; c < 3; c++) {
1359                 cb.lift[c] = 2.0f - cb.lift[c];
1360         }
1361
1362         if(cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
1363                 for (c = 0; c < 3; c++) {
1364                         /* tweak to give more subtle results
1365                          * values above 1.0 are scaled */
1366                         if(cb.lift[c] > 1.0f)
1367                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0f) + 1.0f;
1368
1369                         cb.lift[c] = 2.0f - cb.lift[c];
1370                 }
1371         }
1372
1373         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
1374                 for (c = 0; c < 3; c++) {
1375                         if (cb.gain[c] != 0.0) {
1376                                 cb.gain[c] = 1.0/cb.gain[c];
1377                         } else {
1378                                 cb.gain[c] = 1000000; /* should be enough :) */
1379                         }
1380                 }
1381         }
1382
1383         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
1384                 for (c = 0; c < 3; c++) {
1385                         if (cb.gamma[c] != 0.0) {
1386                                 cb.gamma[c] = 1.0/cb.gamma[c];
1387                         } else {
1388                                 cb.gamma[c] = 1000000; /* should be enough :) */
1389                         }
1390                 }
1391         }
1392
1393         return cb;
1394 }
1395
1396 /* note: lift is actually 2-lift */
1397 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
1398 {
1399         float x= (((in - 1.0f) * lift) + 1.0f) * gain;
1400
1401         /* prevent NaN */
1402         if (x < 0.f) x = 0.f;
1403
1404         return powf(x, gamma) * mul;
1405 }
1406
1407 static void make_cb_table_byte(float lift, float gain, float gamma,
1408                                    unsigned char * table, float mul)
1409 {
1410         int y;
1411
1412         for (y = 0; y < 256; y++) {
1413                 float v= color_balance_fl((float)y * (1.0 / 255.0f), lift, gain, gamma, mul);
1414                 CLAMP(v, 0.0f, 1.0f);
1415                 table[y] = v * 255;
1416         }
1417 }
1418
1419 static void make_cb_table_float(float lift, float gain, float gamma,
1420                                 float * table, float mul)
1421 {
1422         int y;
1423
1424         for (y = 0; y < 256; y++) {
1425                 float v= color_balance_fl((float)y * (1.0 / 255.0f), lift, gain, gamma, mul);
1426                 table[y] = v;
1427         }
1428 }
1429
1430 static void color_balance_byte_byte(Sequence * seq, ImBuf* ibuf, float mul)
1431 {
1432         unsigned char cb_tab[3][256];
1433         int c;
1434         unsigned char * p = (unsigned char*) ibuf->rect;
1435         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1436
1437         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1438
1439         for (c = 0; c < 3; c++) {
1440                 make_cb_table_byte(cb.lift[c], cb.gain[c], cb.gamma[c],
1441                                    cb_tab[c], mul);
1442         }
1443
1444         while (p < e) {
1445                 p[0] = cb_tab[0][p[0]];
1446                 p[1] = cb_tab[1][p[1]];
1447                 p[2] = cb_tab[2][p[2]];
1448                 
1449                 p += 4;
1450         }
1451 }
1452
1453 static void color_balance_byte_float(Sequence * seq, ImBuf* ibuf, float mul)
1454 {
1455         float cb_tab[4][256];
1456         int c,i;
1457         unsigned char * p = (unsigned char*) ibuf->rect;
1458         unsigned char * e = p + ibuf->x * 4 * ibuf->y;
1459         float * o;
1460         StripColorBalance cb;
1461
1462         imb_addrectfloatImBuf(ibuf);
1463
1464         o = ibuf->rect_float;
1465
1466         cb = calc_cb(seq->strip->color_balance);
1467
1468         for (c = 0; c < 3; c++) {
1469                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
1470         }
1471
1472         for (i = 0; i < 256; i++) {
1473                 cb_tab[3][i] = ((float)i)*(1.0f/255.0f);
1474         }
1475
1476         while (p < e) {
1477                 o[0] = cb_tab[0][p[0]];
1478                 o[1] = cb_tab[1][p[1]];
1479                 o[2] = cb_tab[2][p[2]];
1480                 o[3] = cb_tab[3][p[3]];
1481
1482                 p += 4; o += 4;
1483         }
1484 }
1485
1486 static void color_balance_float_float(Sequence * seq, ImBuf* ibuf, float mul)
1487 {
1488         float * p = ibuf->rect_float;
1489         float * e = ibuf->rect_float + ibuf->x * 4* ibuf->y;
1490         StripColorBalance cb = calc_cb(seq->strip->color_balance);
1491
1492         while (p < e) {
1493                 int c;
1494                 for (c = 0; c < 3; c++) {
1495                         p[c]= color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
1496                 }
1497                 p += 4;
1498         }
1499 }
1500
1501 static void color_balance(Sequence * seq, ImBuf* ibuf, float mul)
1502 {
1503         if (ibuf->rect_float) {
1504                 color_balance_float_float(seq, ibuf, mul);
1505         } else if(seq->flag & SEQ_MAKE_FLOAT) {
1506                 color_balance_byte_float(seq, ibuf, mul);
1507         } else {
1508                 color_balance_byte_byte(seq, ibuf, mul);
1509         }
1510 }
1511
1512 /*
1513   input preprocessing for SEQ_IMAGE, SEQ_MOVIE and SEQ_SCENE
1514
1515   Do all the things you can't really do afterwards using sequence effects
1516   (read: before rescaling to render resolution has been done)
1517
1518   Order is important!
1519
1520   - Deinterlace
1521   - Crop and transform in image source coordinate space
1522   - Flip X + Flip Y (could be done afterwards, backward compatibility)
1523   - Promote image to float data (affects pipeline operations afterwards)
1524   - Color balance (is most efficient in the byte -> float 
1525         (future: half -> float should also work fine!)
1526         case, if done on load, since we can use lookup tables)
1527   - Premultiply
1528
1529 */
1530
1531 int input_have_to_preprocess(
1532         SeqRenderData UNUSED(context), Sequence * seq, float UNUSED(cfra))
1533 {
1534         float mul;
1535
1536         if (seq->flag & (SEQ_FILTERY|SEQ_USE_CROP|SEQ_USE_TRANSFORM|SEQ_FLIPX|
1537                          SEQ_FLIPY|SEQ_USE_COLOR_BALANCE|SEQ_MAKE_PREMUL)) {
1538                 return TRUE;
1539         }
1540
1541         mul = seq->mul;
1542
1543         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1544                 mul *= seq->blend_opacity / 100.0;
1545         }
1546
1547         if (mul != 1.0) {
1548                 return TRUE;
1549         }
1550
1551         if (seq->sat != 1.0) {
1552                 return TRUE;
1553         }
1554                 
1555         return FALSE;
1556 }
1557
1558 static ImBuf * input_preprocess(
1559         SeqRenderData context, Sequence *seq, float UNUSED(cfra), ImBuf * ibuf)
1560 {
1561         float mul;
1562
1563         if((seq->flag & SEQ_FILTERY) && seq->type != SEQ_MOVIE) {
1564                 IMB_filtery(ibuf);
1565         }
1566
1567         if(seq->flag & (SEQ_USE_CROP|SEQ_USE_TRANSFORM)) {
1568                 StripCrop c= {0};
1569                 StripTransform t= {0};
1570                 int sx,sy,dx,dy;
1571
1572                 if(seq->flag & SEQ_USE_CROP && seq->strip->crop) {
1573                         c = *seq->strip->crop;
1574                 }
1575                 if(seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
1576                         t = *seq->strip->transform;
1577                 }
1578
1579                 sx = ibuf->x - c.left - c.right;
1580                 sy = ibuf->y - c.top - c.bottom;
1581                 dx = sx;
1582                 dy = sy;
1583
1584                 if (seq->flag & SEQ_USE_TRANSFORM) {
1585                         dx = context.scene->r.xsch;
1586                         dy = context.scene->r.ysch;
1587                 }
1588
1589                 if (c.top + c.bottom >= ibuf->y || c.left + c.right >= ibuf->x ||
1590                                 t.xofs >= dx || t.yofs >= dy) {
1591                         make_black_ibuf(ibuf);
1592                 } else {
1593                         ImBuf * i = IMB_allocImBuf(dx, dy,32, ibuf->rect_float ? IB_rectfloat : IB_rect);
1594
1595                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
1596                         
1597                         IMB_freeImBuf(ibuf);
1598
1599                         ibuf = i;
1600                 }
1601         } 
1602
1603         if(seq->flag & SEQ_FLIPX) {
1604                 IMB_flipx(ibuf);
1605         }
1606         
1607         if(seq->flag & SEQ_FLIPY) {
1608                 IMB_flipy(ibuf);
1609         }
1610
1611         if(seq->sat != 1.0f) {
1612                 /* inline for now, could become an imbuf function */
1613                 int i;
1614                 unsigned char *rct= (unsigned char *)ibuf->rect;
1615                 float *rctf= ibuf->rect_float;
1616                 const float sat= seq->sat;
1617                 float hsv[3];
1618
1619                 if(rct) {
1620                         float rgb[3];
1621                         for (i = ibuf->x * ibuf->y; i > 0; i--, rct+=4) {
1622                                 rgb_byte_to_float(rct, rgb);
1623                                 rgb_to_hsv(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2);
1624                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rgb, rgb+1, rgb+2);
1625                                 rgb_float_to_byte(rgb, rct);
1626                         }
1627                 }
1628
1629                 if(rctf) {
1630                         for (i = ibuf->x * ibuf->y; i > 0; i--, rctf+=4) {
1631                                 rgb_to_hsv(rctf[0], rctf[1], rctf[2], hsv, hsv+1, hsv+2);
1632                                 hsv_to_rgb(hsv[0], hsv[1] * sat, hsv[2], rctf, rctf+1, rctf+2);
1633                         }
1634                 }
1635         }
1636
1637         mul = seq->mul;
1638
1639         if(seq->blend_mode == SEQ_BLEND_REPLACE) {
1640                 mul *= seq->blend_opacity / 100.0;
1641         }
1642
1643         if(seq->flag & SEQ_USE_COLOR_BALANCE && seq->strip->color_balance) {
1644                 color_balance(seq, ibuf, mul);
1645                 mul = 1.0;
1646         }
1647
1648         if(seq->flag & SEQ_MAKE_FLOAT) {
1649                 if (!ibuf->rect_float)
1650                         IMB_float_from_rect_simple(ibuf);
1651
1652                 if (ibuf->rect) {
1653                         imb_freerectImBuf(ibuf);
1654                 }
1655         }
1656
1657         if(mul != 1.0) {
1658                 multibuf(ibuf, mul);
1659         }
1660
1661         if(seq->flag & SEQ_MAKE_PREMUL) {
1662                 if(ibuf->depth == 32 && ibuf->zbuf == 0) {
1663                         IMB_premultiply_alpha(ibuf);
1664                 }
1665         }
1666
1667
1668         if(ibuf->x != context.rectx || ibuf->y != context.recty ) {
1669                 if(context.scene->r.mode & R_OSA) {
1670                         IMB_scaleImBuf(ibuf, (short)context.rectx, (short)context.recty);
1671                 } else {
1672                         IMB_scalefastImBuf(ibuf, (short)context.rectx, (short)context.recty);
1673                 }
1674         }
1675         return ibuf;
1676 }
1677
1678 static ImBuf * copy_from_ibuf_still(SeqRenderData context, Sequence * seq, 
1679                                     float nr)
1680 {
1681         ImBuf * rval = 0;
1682         ImBuf * ibuf = 0;
1683
1684         if (nr == 0) {
1685                 ibuf = seq_stripelem_cache_get(
1686                         context, seq, seq->start, 
1687                         SEQ_STRIPELEM_IBUF_STARTSTILL);
1688         } else if (nr == seq->len - 1) {
1689                 ibuf = seq_stripelem_cache_get(
1690                         context, seq, seq->start, 
1691                         SEQ_STRIPELEM_IBUF_ENDSTILL);
1692         }
1693
1694         if (ibuf) {
1695                 rval = IMB_dupImBuf(ibuf);
1696                 IMB_freeImBuf(ibuf);
1697         }
1698
1699         return rval;
1700 }
1701
1702 static void copy_to_ibuf_still(SeqRenderData context, Sequence * seq, float nr,
1703                                ImBuf * ibuf)
1704 {
1705         if (nr == 0) {
1706                 seq_stripelem_cache_put(
1707                         context, seq, seq->start, 
1708                         SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
1709         } 
1710
1711         if (nr == seq->len - 1) {
1712                 seq_stripelem_cache_put(
1713                         context, seq, seq->start, 
1714                         SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
1715         }
1716 }
1717
1718 /* **********************************************************************
1719    strip rendering functions
1720    ********************************************************************** */
1721
1722 static ImBuf* seq_render_strip_stack( 
1723         SeqRenderData context, ListBase *seqbasep, float cfra, int chanshown);
1724
1725 static ImBuf * seq_render_strip(
1726         SeqRenderData context, Sequence * seq, float cfra);
1727
1728
1729 static ImBuf* seq_render_effect_strip_impl(
1730         SeqRenderData context, Sequence *seq, float cfra)
1731 {
1732         float fac, facf;
1733         int early_out;
1734         int i;
1735         struct SeqEffectHandle sh = get_sequence_effect(seq);
1736         FCurve *fcu= NULL;
1737         ImBuf * ibuf[3];
1738         Sequence *input[3];
1739         ImBuf * out = NULL;
1740
1741         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
1742
1743         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
1744
1745         if (!sh.execute) { /* effect not supported in this version... */
1746                 out = IMB_allocImBuf((short)context.rectx, 
1747                                      (short)context.recty, 32, IB_rect);
1748                 return out;
1749         }
1750
1751         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
1752                 sh.get_default_fac(seq, cfra, &fac, &facf);
1753                 
1754                 if ((context.scene->r.mode & R_FIELDS)==0)
1755                         facf= fac;
1756         }
1757         else {
1758                 fcu = id_data_find_fcurve(&context.scene->id, seq, &RNA_Sequence, "effect_fader", 0);
1759                 if (fcu) {
1760                         fac = facf = evaluate_fcurve(fcu, cfra);
1761                         if( context.scene->r.mode & R_FIELDS ) {
1762                                 facf = evaluate_fcurve(fcu, cfra + 0.5);
1763                         }
1764                 } else {
1765                         fac = facf = seq->effect_fader;
1766                 }
1767         }
1768
1769         early_out = sh.early_out(seq, fac, facf);
1770
1771         switch (early_out) {
1772         case EARLY_NO_INPUT:
1773                 out = sh.execute(context, seq, cfra, fac, facf, 
1774                                  NULL, NULL, NULL);
1775                 break;
1776         case EARLY_DO_EFFECT:
1777                 for(i=0; i<3; i++) {
1778                         if(input[i])
1779                                 ibuf[i] = seq_render_strip(
1780                                         context, input[i], cfra);
1781                 }
1782
1783                 if (ibuf[0] && ibuf[1]) {
1784                         out = sh.execute(context, seq, cfra, fac, facf,  
1785                                          ibuf[0], ibuf[1], ibuf[2]);
1786                 }
1787                 break;
1788         case EARLY_USE_INPUT_1:
1789                 if (input[0]) {
1790                         ibuf[0] = seq_render_strip(context, input[0], cfra);
1791                 }
1792                 if (ibuf[0]) {
1793                         if (input_have_to_preprocess(context, seq, cfra)) {
1794                                 out = IMB_dupImBuf(ibuf[0]);
1795                         } else {
1796                                 out = ibuf[0];
1797                                 IMB_refImBuf(out);
1798                         }
1799                 }
1800                 break;
1801         case EARLY_USE_INPUT_2:
1802                 if (input[1]) {
1803                         ibuf[1] = seq_render_strip(context, input[1], cfra);
1804                 }
1805                 if (ibuf[1]) {
1806                         if (input_have_to_preprocess(context, seq, cfra)) {
1807                                 out = IMB_dupImBuf(ibuf[1]);
1808                         } else {
1809                                 out = ibuf[1];
1810                                 IMB_refImBuf(out);
1811                         }
1812                 }
1813                 break;
1814         }
1815
1816         for (i = 0; i < 3; i++) {
1817                 IMB_freeImBuf(ibuf[i]);
1818         }
1819
1820         if (out == NULL) {
1821                 out = IMB_allocImBuf((short)context.rectx, (short)context.recty, 32, IB_rect);
1822         }
1823
1824         return out;
1825 }
1826
1827
1828 static ImBuf * seq_render_scene_strip_impl(
1829         SeqRenderData context, Sequence * seq, float nr)
1830 {
1831         ImBuf * ibuf = 0;
1832         float frame= seq->sfra + nr + seq->anim_startofs;
1833         float oldcfra;
1834         Object *oldcamera;
1835         ListBase oldmarkers;
1836         
1837         /* Old info:
1838            Hack! This function can be called from do_render_seq(), in that case
1839            the seq->scene can already have a Render initialized with same name,
1840            so we have to use a default name. (compositor uses scene name to
1841            find render).
1842            However, when called from within the UI (image preview in sequencer)
1843            we do want to use scene Render, that way the render result is defined
1844            for display in render/imagewindow
1845            
1846            Hmm, don't see, why we can't do that all the time,
1847            and since G.rendering is uhm, gone... (Peter)
1848         */
1849
1850         /* New info:
1851            Using the same name for the renders works just fine as the do_render_seq()
1852            render is not used while the scene strips are rendered.
1853            
1854            However rendering from UI (through sequencer_preview_area_draw) can crash in
1855            very many cases since other renders (material preview, an actual render etc.)
1856            can be started while this sequence preview render is running. The only proper
1857            solution is to make the sequencer preview render a proper job, which can be
1858            stopped when needed. This would also give a nice progress bar for the preview
1859            space so that users know there's something happening.
1860
1861            As a result the active scene now only uses OpenGL rendering for the sequencer
1862            preview. This is far from nice, but is the only way to prevent crashes at this
1863            time. 
1864
1865            -jahka
1866         */
1867
1868         int rendering = G.rendering;
1869         int doseq;
1870         int doseq_gl= G.rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1;
1871         int have_seq= FALSE;
1872         Scene *sce= seq->scene; /* dont refer to seq->scene above this point!, it can be NULL */
1873         int sce_valid= FALSE;
1874
1875         if(sce) {
1876                 have_seq= (sce->r.scemode & R_DOSEQ) && sce->ed && sce->ed->seqbase.first;
1877                 sce_valid= (sce->camera || have_seq);
1878         }
1879
1880         if (!sce_valid)
1881                 return NULL;
1882
1883         oldcfra= seq->scene->r.cfra;
1884         oldcamera= seq->scene->camera;
1885
1886         /* prevent eternal loop */
1887         doseq= context.scene->r.scemode & R_DOSEQ;
1888         context.scene->r.scemode &= ~R_DOSEQ;
1889         
1890         seq->scene->r.cfra= frame;
1891         if(seq->scene_camera)   
1892                 seq->scene->camera= seq->scene_camera;
1893         else    
1894                 scene_camera_switch_update(seq->scene);
1895         
1896 #ifdef DURIAN_CAMERA_SWITCH
1897         /* stooping to new low's in hackyness :( */
1898         oldmarkers= seq->scene->markers;
1899         seq->scene->markers.first= seq->scene->markers.last= NULL;
1900 #endif
1901         
1902         if(sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (seq->scene == context.scene || have_seq==0) && seq->scene->camera) {
1903                 /* for old scened this can be uninitialized, should probably be added to do_versions at some point if the functionality stays */
1904                 if(context.scene->r.seq_prev_type==0)
1905                         context.scene->r.seq_prev_type = 3 /* ==OB_SOLID */; 
1906
1907                 /* opengl offscreen render */
1908                 scene_update_for_newframe(context.bmain, seq->scene, seq->scene->lay);
1909                 ibuf= sequencer_view3d_cb(seq->scene, context.rectx, context.recty, IB_rect, context.scene->r.seq_prev_type);
1910         }
1911         else {
1912                 Render *re = RE_GetRender(sce->id.name);
1913                 RenderResult rres;
1914
1915                 /* XXX: this if can be removed when sequence preview rendering uses the job system */
1916                 if(rendering || context.scene != sce) {
1917                         if(re==NULL)
1918                                 re= RE_NewRender(sce->id.name);
1919                         
1920                         RE_BlenderFrame(re, context.bmain, sce, NULL, sce->lay, frame, FALSE);
1921
1922                         /* restore previous state after it was toggled on & off by RE_BlenderFrame */
1923                         G.rendering = rendering;
1924                 }
1925                 
1926                 RE_AcquireResultImage(re, &rres);
1927                 
1928                 if(rres.rectf) {
1929                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rectfloat);
1930                         memcpy(ibuf->rect_float, rres.rectf, 4*sizeof(float)*rres.rectx*rres.recty);
1931                         if(rres.rectz) {
1932                                 addzbuffloatImBuf(ibuf);
1933                                 memcpy(ibuf->zbuf_float, rres.rectz, sizeof(float)*rres.rectx*rres.recty);
1934                         }
1935
1936                         /* float buffers in the sequencer are not linear */
1937                         ibuf->profile= IB_PROFILE_LINEAR_RGB;
1938                         IMB_convert_profile(ibuf, IB_PROFILE_SRGB);                     
1939                 }
1940                 else if (rres.rect32) {
1941                         ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, IB_rect);
1942                         memcpy(ibuf->rect, rres.rect32, 4*rres.rectx*rres.recty);
1943                 }
1944                 
1945                 RE_ReleaseResultImage(re);
1946                 
1947                 // BIF_end_render_callbacks();
1948         }
1949         
1950         /* restore */
1951         context.scene->r.scemode |= doseq;
1952         
1953         seq->scene->r.cfra = oldcfra;
1954         seq->scene->camera= oldcamera;
1955         
1956 #ifdef DURIAN_CAMERA_SWITCH
1957         /* stooping to new low's in hackyness :( */
1958         seq->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, 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==0) {
2067                                 BLI_join_dirfile(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.0;
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.0;
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, 0);
2250                         } else {
2251                                 out = sh.execute(context, seq, cfra, 
2252                                                  facf, facf, 
2253                                                  ibuf1, ibuf2, 0);
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 : 0;
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 = 0;
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 && ELEM3(seq->type, SEQ_IMAGE, SEQ_COLOR, SEQ_MULTICAM));
2820 }
2821
2822 /* check if the selected seq's reference unselected seq's */
2823 int seqbase_isolated_sel_check(ListBase *seqbase)
2824 {
2825         Sequence *seq;
2826         /* is there more than 1 select */
2827         int ok= FALSE;
2828
2829         for(seq= seqbase->first; seq; seq= seq->next) {
2830                 if(seq->flag & SELECT) {
2831                         ok= TRUE;
2832                         break;
2833                 }
2834         }
2835
2836         if(ok == FALSE)
2837                 return FALSE;
2838
2839         /* test relationships */
2840         for(seq= seqbase->first; seq; seq= seq->next) {
2841                 if((seq->type & SEQ_EFFECT)==0)
2842                         continue;
2843
2844                 if(seq->flag & SELECT) {
2845                         if( (seq->seq1 && (seq->seq1->flag & SELECT)==0) ||
2846                                 (seq->seq2 && (seq->seq2->flag & SELECT)==0) ||
2847                                 (seq->seq3 && (seq->seq3->flag & SELECT)==0) )
2848                                 return FALSE;
2849                 }
2850                 else {
2851                         if( (seq->seq1 && (seq->seq1->flag & SELECT)) ||
2852                                 (seq->seq2 && (seq->seq2->flag & SELECT)) ||
2853                                 (seq->seq3 && (seq->seq3->flag & SELECT)) )
2854                                 return FALSE;
2855                 }
2856         }
2857
2858         return TRUE;
2859 }
2860
2861 /* use to impose limits when dragging/extending - so impossible situations dont happen
2862  * Cant use the SEQ_LEFTSEL and SEQ_LEFTSEL directly because the strip may be in a metastrip */
2863 void seq_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag)
2864 {
2865         if(leftflag) {
2866                 if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_final_right(seq, 0)) {
2867                         seq_tx_set_final_left(seq, seq_tx_get_final_right(seq, 0)-1);
2868                 }
2869
2870                 if (seq_single_check(seq)==0) {
2871                         if (seq_tx_get_final_left(seq, 0) >= seq_tx_get_end(seq)) {
2872                                 seq_tx_set_final_left(seq, seq_tx_get_end(seq)-1);
2873                         }
2874
2875                         /* dosnt work now - TODO */
2876                         /*
2877                         if (seq_tx_get_start(seq) >= seq_tx_get_final_right(seq, 0)) {
2878                                 int ofs;
2879                                 ofs = seq_tx_get_start(seq) - seq_tx_get_final_right(seq, 0);
2880                                 seq->start -= ofs;
2881                                 seq_tx_set_final_left(seq, seq_tx_get_final_left(seq, 0) + ofs );
2882                         }*/
2883
2884                 }
2885         }
2886
2887         if(rightflag) {
2888                 if (seq_tx_get_final_right(seq, 0) <=  seq_tx_get_final_left(seq, 0)) {
2889                         seq_tx_set_final_right(seq, seq_tx_get_final_left(seq, 0)+1);
2890                 }
2891
2892                 if (seq_single_check(seq)==0) {
2893                         if (seq_tx_get_final_right(seq, 0) <= seq_tx_get_start(seq)) {
2894                                 seq_tx_set_final_right(seq, seq_tx_get_start(seq)+1);
2895                         }
2896                 }
2897         }
2898
2899         /* sounds cannot be extended past their endpoints */
2900         if (seq->type == SEQ_SOUND) {
2901                 seq->startstill= 0;
2902                 seq->endstill= 0;
2903         }
2904 }
2905
2906 void seq_single_fix(Sequence *seq)
2907 {
2908         int left, start, offset;
2909         if (!seq_single_check(seq))
2910                 return;
2911
2912         /* make sure the image is always at the start since there is only one,
2913            adjusting its start should be ok */
2914         left = seq_tx_get_final_left(seq, 0);
2915         start = seq->start;
2916         if (start != left) {
2917                 offset = left - start;
2918                 seq_tx_set_final_left( seq, seq_tx_get_final_left(seq, 0) - offset );
2919                 seq_tx_set_final_right( seq, seq_tx_get_final_right(seq, 0) - offset );
2920                 seq->start += offset;
2921         }
2922 }
2923
2924 int seq_tx_test(Sequence * seq)
2925 {
2926         return (seq->type < SEQ_EFFECT) || (get_sequence_effect_num_inputs(seq->type) == 0);
2927 }
2928
2929 static int seq_overlap(Sequence *seq1, Sequence *seq2)
2930 {
2931         return (seq1 != seq2 && seq1->machine == seq2->machine &&
2932                         ((seq1->enddisp <= seq2->startdisp) || (seq1->startdisp >= seq2->enddisp))==0);
2933 }
2934
2935 int seq_test_overlap(ListBase * seqbasep, Sequence *test)
2936 {
2937         Sequence *seq;
2938
2939         seq= seqbasep->first;
2940         while(seq) {
2941                 if(seq_overlap(test, seq))
2942                         return 1;
2943
2944                 seq= seq->next;
2945         }
2946         return 0;
2947 }
2948
2949
2950 void seq_translate(Scene *evil_scene, Sequence *seq, int delta)
2951 {
2952         seq_offset_animdata(evil_scene, seq, delta);
2953         seq->start += delta;
2954
2955         if(seq->type==SEQ_META) {
2956                 Sequence *seq_child;
2957                 for(seq_child= seq->seqbase.first; seq_child; seq_child= seq_child->next) {
2958                         seq_translate(evil_scene, seq_child, delta);
2959                 }
2960         }
2961
2962         calc_sequence_disp(evil_scene, seq);
2963 }
2964
2965 /* return 0 if there werent enough space */
2966 int shuffle_seq(ListBase * seqbasep, Sequence *test, Scene *evil_scene)
2967 {
2968         int orig_machine= test->machine;
2969         test->machine++;
2970         calc_sequence(evil_scene, test);
2971         while( seq_test_overlap(seqbasep, test) ) {
2972                 if(test->machine >= MAXSEQ) {
2973                         break;
2974                 }
2975                 test->machine++;
2976                 calc_sequence(evil_scene, test); // XXX - I dont think this is needed since were only moving vertically, Campbell.
2977         }
2978
2979         
2980         if(test->machine >= MAXSEQ) {
2981                 /* Blender 2.4x would remove the strip.
2982                  * nicer to move it to the end */
2983
2984                 Sequence *seq;
2985                 int new_frame= test->enddisp;
2986
2987                 for(seq= seqbasep->first; seq; seq= seq->next) {
2988                         if (seq->machine == orig_machine)
2989                                 new_frame = MAX2(new_frame, seq->enddisp);
2990                 }
2991
2992                 test->machine= orig_machine;
2993                 new_frame = new_frame + (test->start-test->startdisp); /* adjust by the startdisp */
2994                 seq_translate(evil_scene, test, new_frame - test->start);
2995
2996                 calc_sequence(evil_scene, test);
2997                 return 0;
2998         } else {
2999                 return 1;
3000         }
3001 }
3002
3003 static int shuffle_seq_time_offset_test(ListBase * seqbasep, char dir)
3004 {
3005         int offset= 0;
3006         Sequence *seq, *seq_other;
3007
3008         for(seq= seqbasep->first; seq; seq= seq->next) {
3009                 if(seq->tmp) {
3010                         for(seq_other= seqbasep->first; seq_other; seq_other= seq_other->next) {
3011                                 if(!seq_other->tmp && seq_overlap(seq, seq_other)) {
3012                                         if(dir=='L') {
3013                                                 offset= MIN2(offset, seq_other->startdisp - seq->enddisp);
3014                                         }
3015                                         else {
3016                                                 offset= MAX2(offset, seq_other->enddisp - seq->startdisp);
3017                                         }
3018                                 }
3019                         }
3020                 }
3021         }
3022         return offset;
3023 }
3024
3025 static int shuffle_seq_time_offset(Scene* scene, ListBase * seqbasep, char dir)
3026 {
3027         int ofs= 0;
3028         int tot_ofs= 0;
3029         Sequence *seq;
3030         while( (ofs= shuffle_seq_time_offset_test(seqbasep, dir)) ) {
3031                 for(seq= seqbasep->first; seq; seq= seq->next) {
3032                         if(seq->tmp) {
3033                                 /* seq_test_overlap only tests display values */
3034                                 seq->startdisp +=       ofs;
3035                                 seq->enddisp +=         ofs;
3036                         }
3037                 }
3038
3039                 tot_ofs+= ofs;
3040         }
3041
3042         for(seq= seqbasep->first; seq; seq= seq->next) {
3043                 if(seq->tmp)
3044                         calc_sequence_disp(scene, seq); /* corrects dummy startdisp/enddisp values */
3045         }
3046
3047         return tot_ofs;
3048 }
3049
3050 int shuffle_seq_time(ListBase * seqbasep, Scene *evil_scene)
3051 {
3052         /* note: seq->tmp is used to tag strips to move */
3053
3054         Sequence *seq;
3055
3056         int offset_l = shuffle_seq_time_offset(evil_scene, seqbasep, 'L');
3057         int offset_r = shuffle_seq_time_offset(evil_scene, seqbasep, 'R');
3058         int offset = (-offset_l < offset_r) ?  offset_l:offset_r;
3059
3060         if(offset) {
3061                 for(seq= seqbasep->first; seq; seq= seq->next) {
3062                         if(seq->tmp) {
3063                                 seq_translate(evil_scene, seq, offset);
3064                                 seq->flag &= ~SEQ_OVERLAP;
3065                         }
3066                 }
3067         }
3068
3069         return offset? 0:1;
3070 }
3071
3072 void seq_update_sound(Scene* scene, Sequence *seq)
3073 {
3074         if(seq->scene_sound)
3075         {
3076                 sound_move_scene_sound(scene, seq->scene_sound, seq->startdisp, seq->enddisp, seq->startofs + seq->anim_startofs);
3077                 /* mute is set in seq_update_muting_recursive */
3078         }
3079 }
3080
3081 static void seq_update_muting_recursive(Scene *scene, ListBase *seqbasep, Sequence *metaseq, int mute)
3082 {
3083         Sequence *seq;
3084         int seqmute;
3085
3086         /* for sound we go over full meta tree to update muted state,
3087            since sound is played outside of evaluating the imbufs, */
3088         for(seq=seqbasep->first; seq; seq=seq->next) {
3089                 seqmute= (mute || (seq->flag & SEQ_MUTE));
3090
3091                 if(seq->type == SEQ_META) {
3092                         /* if this is the current meta sequence, unmute because
3093                            all sequences above this were set to mute */
3094                         if(seq == metaseq)
3095                                 seqmute= 0;
3096
3097                         seq_update_muting_recursive(scene, &seq->seqbase, metaseq, seqmute);
3098                 }
3099                 else if(ELEM(seq->type, SEQ_SOUND, SEQ_SCENE)) {
3100                         if(seq->scene_sound) {
3101                                 sound_mute_scene_sound(scene, seq->scene_sound, seqmute);
3102                         }
3103                 }
3104         }
3105 }
3106
3107 void seq_update_muting(Scene *scene, Editing *ed)
3108 {
3109         if(ed) {
3110                 /* mute all sounds up to current metastack list */
3111                 MetaStack *ms= ed->metastack.last;
3112
3113                 if(ms)
3114                         seq_update_muting_recursive(scene, &ed->seqbase, ms->parseq, 1);
3115                 else
3116                         seq_update_muting_recursive(scene, &ed->seqbase, NULL, 0);
3117         }
3118 }
3119
3120 /* in cases where we done know the sequence's listbase */
3121 ListBase *seq_seqbase(ListBase *seqbase, Sequence *seq)
3122 {
3123         Sequence *iseq;
3124         ListBase *lb= NULL;
3125
3126         for(iseq= seqbase->first; iseq; iseq= iseq->next) {
3127                 if(seq==iseq) {
3128                         return seqbase;
3129                 }
3130                 else if(iseq->seqbase.first && (lb= seq_seqbase(&iseq->seqbase, seq))) {
3131                         return lb;
3132                 }
3133         }
3134
3135         return NULL;
3136 }
3137
3138 int seq_swap(Sequence *seq_a, Sequence *seq_b)
3139 {
3140         char name[sizeof(seq_a->name)];
3141
3142         if(seq_a->len != seq_b->len)
3143                 return 0;
3144
3145         /* type checking, could be more advanced but disalow sound vs non-sound copy */
3146         if(seq_a->type != seq_b->type) {
3147                 if(seq_a->type == SEQ_SOUND || seq_b->type == SEQ_SOUND) {
3148                         return 0;
3149                 }
3150
3151                 /* disallow effects to swap with non-effects strips */
3152                 if((seq_a->type & SEQ_EFFECT) != (seq_b->type & SEQ_EFFECT)) {
3153                         return 0;
3154                 }
3155
3156                 if((seq_a->type & SEQ_EFFECT) && (seq_b->type & SEQ_EFFECT)) {
3157                         if(get_sequence_effect_num_inputs(seq_a->type) != get_sequence_effect_num_inputs(seq_b->type)) {
3158                                 return 0;
3159                         }
3160                 }
3161         }
3162
3163         SWAP(Sequence, *seq_a, *seq_b);
3164
3165         /* swap back names so animation fcurves dont get swapped */
3166         strcpy(name, seq_a->name+2);
3167         strcpy(seq_a->name+2, seq_b->name+2);
3168         strcpy(seq_b->name+2, name);
3169
3170         /* swap back opacity, and overlay mode */
3171         SWAP(int, seq_a->blend_mode, seq_b->blend_mode);
3172         SWAP(float, seq_a->blend_opacity, seq_b->blend_opacity);
3173
3174
3175         SWAP(void *, seq_a->prev, seq_b->prev);
3176         SWAP(void *, seq_a->next, seq_b->next);
3177         SWAP(int, seq_a->start, seq_b->start);
3178         SWAP(int, seq_a->startofs, seq_b->startofs);
3179         SWAP(int, seq_a->endofs, seq_b->endofs);
3180         SWAP(int, seq_a->startstill, seq_b->startstill);
3181         SWAP(int, seq_a->endstill, seq_b->endstill);
3182         SWAP(int, seq_a->machine, seq_b->machine);
3183         SWAP(int, seq_a->startdisp, seq_b->startdisp);
3184         SWAP(int, seq_a->enddisp, seq_b->enddisp);
3185
3186         return 1;
3187 }
3188
3189 /* XXX - hackish function needed for transforming strips! TODO - have some better solution */
3190 void seq_offset_animdata(Scene *scene, Sequence *seq, int ofs)
3191 {
3192         char str[32];
3193         FCurve *fcu;
3194
3195         if(scene->adt==NULL || ofs==0 || scene->adt->action==NULL)
3196                 return;
3197
3198         sprintf(str, "[\"%s\"]", seq->name+2);
3199
3200         for (fcu= scene->adt->action->curves.first; fcu; fcu= fcu->next) {
3201                 if(strstr(fcu->rna_path, "sequence_editor.sequences_all[") && strstr(fcu->rna_path, str)) {
3202                         unsigned int i;
3203                         for (i = 0; i < fcu->totvert; i++) {
3204                                 BezTriple *bezt= &fcu->bezt[i];
3205                                 bezt->vec[0][0] += ofs;
3206                                 bezt->vec[1][0] += ofs;
3207                                 bezt->vec[2][0] += ofs;
3208                         }
3209                 }
3210         }
3211 }
3212
3213 void seq_dupe_animdata(Scene *scene, char *name_from, char *name_to)
3214 {
3215         char str_from[32];
3216         FCurve *fcu;
3217         FCurve *fcu_last;
3218         FCurve *fcu_cpy;
3219         ListBase lb= {NULL, NULL};
3220
3221         if(scene->adt==NULL || scene->adt->action==NULL)
3222                 return;
3223
3224         sprintf(str_from, "[\"%s\"]", name_from);
3225
3226         fcu_last= scene->adt->action->curves.last;
3227
3228         for (fcu= scene->adt->action->curves.first; fcu && fcu->prev != fcu_last; fcu= fcu->next) {
3229                 if(strstr(fcu->rna_path, "sequence_editor.sequences_all[") && strstr(fcu->rna_path, str_from)) {
3230                         fcu_cpy= copy_fcurve(fcu);
3231                         BLI_addtail(&lb, fcu_cpy);
3232                 }
3233         }
3234
3235         /* notice validate is 0, keep this because the seq may not be added to the scene yet */
3236         BKE_animdata_fix_paths_rename(&scene->id, scene->adt, "sequence_editor.sequences_all", name_from, name_to, 0, 0, 0);
3237
3238         /* add the original fcurves back */
3239         BLI_movelisttolist(&scene->adt->action->curves, &lb);
3240 }
3241
3242 /* XXX - hackish function needed to remove all fcurves belonging to a sequencer strip */
3243 static void seq_free_animdata(Scene *scene, Sequence *seq)
3244 {
3245         char str[32];
3246         FCurve *fcu;
3247
3248         if(scene->adt==NULL || scene->adt->action==NULL)
3249                 return;
3250
3251         sprintf(str, "[\"%s\"]", seq->name+2);
3252
3253         fcu= scene->adt->action->curves.first; 
3254
3255         while (fcu) {
3256                 if(strstr(fcu->rna_path, "sequence_editor.sequences_all[") && strstr(fcu->rna_path, str)) {
3257                         FCurve *next_fcu = fcu->next;
3258                         
3259                         BLI_remlink(&scene->adt->action->curves, fcu);
3260                         free_fcurve(fcu);
3261
3262                         fcu = next_fcu;
3263                 } else {
3264                         fcu = fcu->next;
3265                 }
3266         }
3267 }
3268
3269
3270 Sequence *get_seq_by_name(ListBase *seqbase, const char *name, int recursive)
3271 {
3272         Sequence *iseq=NULL;
3273         Sequence *rseq=NULL;
3274
3275         for (iseq=seqbase->first; iseq; iseq=iseq->next) {
3276                 if (strcmp(name, iseq->name+2) == 0)
3277                         return iseq;
3278                 else if(recursive && (iseq->seqbase.first) && (rseq=get_seq_by_name(&iseq->seqbase, name, 1))) {
3279                         return rseq;
3280                 }
3281         }
3282
3283         return NULL;
3284 }
3285
3286
3287 Sequence *seq_active_get(Scene *scene)
3288 {
3289         Editing *ed= seq_give_editing(scene, FALSE);
3290         if(ed==NULL) return NULL;
3291         return ed->act_seq;
3292 }
3293
3294 void seq_active_set(Scene *scene, Sequence *seq)
3295 {
3296         Editing *ed= seq_give_editing(scene, FALSE);
3297         if(ed==NULL) return;
3298
3299         ed->act_seq= seq;
3300 }
3301
3302 int seq_active_pair_get(Scene *scene, Sequence **seq_act, Sequence **seq_other)
3303 {
3304         Editing *ed= seq_give_editing(scene, FALSE);
3305