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