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