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