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