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