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