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