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