e5aa9b4915e40617628ff988a292ffd16b99f836
[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 #if 0
1600                                         seq_anim_add_suffix(scene, sanim->anim, i);
1601 #else
1602                                         /* we already have the suffix */
1603                                         IMB_suffix_anim(sanim->anim, suffix);
1604 #endif
1605                                 }
1606                                 else {
1607                                         if (openfile) {
1608                                                 sanim->anim = openanim(
1609                                                         name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0),
1610                                                         seq->streamindex, seq->strip->colorspace_settings.name);
1611                                         }
1612                                         else {
1613                                                 sanim->anim = openanim_noload(
1614                                                         name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0),
1615                                                         seq->streamindex, seq->strip->colorspace_settings.name);
1616                                         }
1617
1618                                         /* no individual view files - monoscopic, stereo 3d or exr multiview */
1619                                         totfiles = 1;
1620                                 }
1621
1622                                 if (sanim->anim && use_proxy) {
1623                                         seq_proxy_index_dir_set(sanim->anim, dir);
1624                                 }
1625                         }
1626                         is_multiview_loaded = true;
1627                 }
1628         }
1629
1630         if (is_multiview_loaded == false) {
1631                 StripAnim *sanim;
1632
1633                 sanim = MEM_mallocN(sizeof(StripAnim), "Strip Anim");
1634                 BLI_addtail(&seq->anims, sanim);
1635
1636                 if (openfile) {
1637                         sanim->anim = openanim(
1638                                 name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0),
1639                                 seq->streamindex, seq->strip->colorspace_settings.name);
1640                 }
1641                 else {
1642                         sanim->anim = openanim_noload(
1643                                 name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0),
1644                                 seq->streamindex, seq->strip->colorspace_settings.name);
1645                 }
1646
1647                 if (sanim->anim && use_proxy) {
1648                         seq_proxy_index_dir_set(sanim->anim, dir);
1649                 }
1650         }
1651 }
1652
1653 static bool seq_proxy_get_fname(Editing *ed, Sequence *seq, int cfra, int render_size, char *name, const int view_id)
1654 {
1655         int frameno;
1656         char dir[PROXY_MAXFILE];
1657         StripAnim *sanim;
1658         char suffix[24] = {'\0'};
1659
1660         StripProxy *proxy = seq->strip->proxy;
1661         if (!proxy) {
1662                 return false;
1663         }
1664
1665         /* MOVIE tracks (only exception: custom files) are now handled
1666          * internally by ImBuf module for various reasons: proper time code
1667          * support, quicker index build, using one file instead
1668          * of a full directory of jpeg files, etc. Trying to support old
1669          * and new method at once could lead to funny effects, if people
1670          * have both, a directory full of jpeg files and proxy avis, so
1671          * sorry folks, please rebuild your proxies... */
1672
1673         sanim = BLI_findlink(&seq->anims, view_id);
1674
1675         if (ed->proxy_storage == SEQ_EDIT_PROXY_DIR_STORAGE) {
1676                 char fname[FILE_MAXFILE];
1677                 if (ed->proxy_dir[0] == 0)
1678                         BLI_strncpy(dir, "//BL_proxy", sizeof(dir));
1679                 else
1680                         BLI_strncpy(dir, ed->proxy_dir, sizeof(dir));
1681
1682                 if (sanim && sanim->anim) {
1683                         IMB_anim_get_fname(sanim->anim, fname, FILE_MAXFILE);
1684                 }
1685                 else if (seq->type == SEQ_TYPE_IMAGE) {
1686                         fname[0] = 0;
1687                 }
1688                 else {
1689                         /* We could make a name here, except non-movie's don't generate proxies,
1690                          * cancel until other types of sequence strips are supported. */
1691                         return false;
1692                 }
1693                 BLI_path_append(dir, sizeof(dir), fname);
1694                 BLI_path_abs(name, BKE_main_blendfile_path_from_global());
1695         }
1696         else if ((proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_DIR) && (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE)) {
1697                 BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1698         }
1699         else if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE) {
1700                 BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1701         }
1702         else if (sanim && sanim->anim && (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_DIR)) {
1703                 char fname[FILE_MAXFILE];
1704                 BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1705                 IMB_anim_get_fname(sanim->anim, fname, FILE_MAXFILE);
1706                 BLI_path_append(dir, sizeof(dir), fname);
1707         }
1708         else if (seq->type == SEQ_TYPE_IMAGE) {
1709                 if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_DIR)
1710                         BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir));
1711                 else
1712                         BLI_snprintf(dir, PROXY_MAXFILE, "%s/BL_proxy", seq->strip->dir);
1713         }
1714         else {
1715                 return false;
1716         }
1717
1718         if (view_id > 0)
1719                 BLI_snprintf(suffix, sizeof(suffix), "_%d", view_id);
1720
1721         if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE &&
1722             ed->proxy_storage != SEQ_EDIT_PROXY_DIR_STORAGE)
1723         {
1724                 char fname[FILE_MAXFILE];
1725                 BLI_join_dirfile(fname, PROXY_MAXFILE, dir, proxy->file);
1726                 BLI_path_abs(fname, BKE_main_blendfile_path_from_global());
1727                 if (suffix[0] != '\0') {
1728                         /* TODO(sergey): This will actually append suffix after extension
1729                          * which is weird but how was originally coded in multiview branch.
1730                          */
1731                         BLI_snprintf(name, PROXY_MAXFILE, "%s_%s", fname, suffix);
1732                 }
1733                 else {
1734                         BLI_strncpy(name, fname, PROXY_MAXFILE);
1735                 }
1736
1737                 return true;
1738         }
1739
1740         /* generate a separate proxy directory for each preview size */
1741
1742         if (seq->type == SEQ_TYPE_IMAGE) {
1743                 BLI_snprintf(name, PROXY_MAXFILE, "%s/images/%d/%s_proxy%s", dir, render_size,
1744                              BKE_sequencer_give_stripelem(seq, cfra)->name, suffix);
1745                 frameno = 1;
1746         }
1747         else {
1748                 frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1749                 BLI_snprintf(name, PROXY_MAXFILE, "%s/proxy_misc/%d/####%s", dir, render_size, suffix);
1750         }
1751
1752         BLI_path_abs(name, BKE_main_blendfile_path_from_global());
1753         BLI_path_frame(name, frameno, 0);
1754
1755         strcat(name, ".jpg");
1756
1757         return true;
1758 }
1759
1760 static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int cfra)
1761 {
1762         char name[PROXY_MAXFILE];
1763         IMB_Proxy_Size psize = seq_rendersize_to_proxysize(context->preview_render_size);
1764         int size_flags;
1765         int render_size = context->preview_render_size;
1766         StripProxy *proxy = seq->strip->proxy;
1767         Editing *ed = context->scene->ed;
1768         StripAnim *sanim;
1769
1770         if (!(seq->flag & SEQ_USE_PROXY)) {
1771                 return NULL;
1772         }
1773
1774         /* dirty hack to distinguish 100% render size from PROXY_100 */
1775         if (render_size == 99) {
1776                 render_size = 100;
1777         }
1778
1779         size_flags = proxy->build_size_flags;
1780
1781         /* only use proxies, if they are enabled (even if present!) */
1782         if (psize == IMB_PROXY_NONE || ((size_flags & psize) != psize)) {
1783                 return NULL;
1784         }
1785
1786         if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE) {
1787                 int frameno = (int)give_stripelem_index(seq, cfra) + seq->anim_startofs;
1788                 if (proxy->anim == NULL) {
1789                         if (seq_proxy_get_fname(ed, seq, cfra, render_size, name, context->view_id) == 0) {
1790                                 return NULL;
1791                         }
1792
1793                         proxy->anim = openanim(name, IB_rect, 0, seq->strip->colorspace_settings.name);
1794                 }
1795                 if (proxy->anim == NULL) {
1796                         return NULL;
1797                 }
1798
1799                 seq_open_anim_file(context->scene, seq, true);
1800                 sanim = seq->anims.first;
1801
1802                 frameno = IMB_anim_index_get_frame_index(sanim ? sanim->anim : NULL, seq->strip->proxy->tc, frameno);
1803
1804                 return IMB_anim_absolute(proxy->anim, frameno, IMB_TC_NONE, IMB_PROXY_NONE);
1805         }
1806
1807         if (seq_proxy_get_fname(ed, seq, cfra, render_size, name, context->view_id) == 0) {
1808                 return NULL;
1809         }
1810
1811         if (BLI_exists(name)) {
1812                 ImBuf *ibuf = IMB_loadiffname(name, IB_rect, NULL);
1813
1814                 if (ibuf)
1815                         sequencer_imbuf_assign_spaces(context->scene, ibuf);
1816
1817                 return ibuf;
1818         }
1819         else {
1820                 return NULL;
1821         }
1822 }
1823
1824 static void seq_proxy_build_frame(
1825         const SeqRenderData *context, SeqRenderState *state,
1826         Sequence *seq, int cfra,
1827         int proxy_render_size, const bool overwrite)
1828 {
1829         char name[PROXY_MAXFILE];
1830         int quality;
1831         int rectx, recty;
1832         int ok;
1833         ImBuf *ibuf_tmp, *ibuf;
1834         Editing *ed = context->scene->ed;
1835
1836         if (!seq_proxy_get_fname(ed, seq, cfra, proxy_render_size, name, context->view_id)) {
1837                 return;
1838         }
1839
1840         if (!overwrite && BLI_exists(name)) {
1841                 return;
1842         }
1843
1844         ibuf_tmp = seq_render_strip(context, state, seq, cfra);
1845
1846         rectx = (proxy_render_size * ibuf_tmp->x) / 100;
1847         recty = (proxy_render_size * ibuf_tmp->y) / 100;
1848
1849         if (ibuf_tmp->x != rectx || ibuf_tmp->y != recty) {
1850                 ibuf = IMB_dupImBuf(ibuf_tmp);
1851                 IMB_metadata_copy(ibuf, ibuf_tmp);
1852                 IMB_freeImBuf(ibuf_tmp);
1853                 IMB_scalefastImBuf(ibuf, (short)rectx, (short)recty);
1854         }
1855         else {
1856                 ibuf = ibuf_tmp;
1857         }
1858
1859         /* depth = 32 is intentionally left in, otherwise ALPHA channels
1860          * won't work... */
1861         quality = seq->strip->proxy->quality;
1862         ibuf->ftype = IMB_FTYPE_JPG;
1863         ibuf->foptions.quality = quality;
1864
1865         /* unsupported feature only confuses other s/w */
1866         if (ibuf->planes == 32)
1867                 ibuf->planes = 24;
1868
1869         BLI_make_existing_file(name);
1870
1871         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1872         if (ok == 0) {
1873                 perror(name);
1874         }
1875
1876         IMB_freeImBuf(ibuf);
1877 }
1878
1879 /**
1880  * Returns whether the file this context would read from even exist,
1881  * if not, don't create the context
1882  */
1883 static bool seq_proxy_multiview_context_invalid(Sequence *seq, Scene *scene, const int view_id)
1884 {
1885         if ((scene->r.scemode & R_MULTIVIEW) == 0)
1886                 return false;
1887
1888         if ((seq->type == SEQ_TYPE_IMAGE) && (seq->views_format == R_IMF_VIEWS_INDIVIDUAL)) {
1889                 static char prefix[FILE_MAX];
1890                 static const char *ext = NULL;
1891                 char str[FILE_MAX];
1892
1893                 if (view_id == 0) {
1894                         char path[FILE_MAX];
1895                         BLI_join_dirfile(path, sizeof(path), seq->strip->dir,
1896                                          seq->strip->stripdata->name);
1897                         BLI_path_abs(path, BKE_main_blendfile_path_from_global());
1898                         BKE_scene_multiview_view_prefix_get(scene, path, prefix, &ext);
1899                 }
1900                 else {
1901                         prefix[0] = '\0';
1902                 }
1903
1904                 if (prefix[0] == '\0')
1905                         return view_id != 0;
1906
1907                 seq_multiview_name(scene, view_id, prefix, ext, str, FILE_MAX);
1908
1909                 if (BLI_access(str, R_OK) == 0)
1910                         return false;
1911                 else
1912                         return view_id != 0;
1913         }
1914         return false;
1915 }
1916
1917 /**
1918  * This returns the maximum possible number of required contexts
1919  */
1920 static int seq_proxy_context_count(Sequence *seq, Scene *scene)
1921 {
1922         int num_views = 1;
1923
1924         if ((scene->r.scemode & R_MULTIVIEW) == 0)
1925                 return 1;
1926
1927         switch (seq->type) {
1928                 case SEQ_TYPE_MOVIE:
1929                 {
1930                         num_views = BLI_listbase_count(&seq->anims);
1931                         break;
1932                 }
1933                 case SEQ_TYPE_IMAGE:
1934                 {
1935                         switch (seq->views_format) {
1936                                 case R_IMF_VIEWS_INDIVIDUAL:
1937                                         num_views = BKE_scene_multiview_num_views_get(&scene->r);
1938                                         break;
1939                                 case R_IMF_VIEWS_STEREO_3D:
1940                                         num_views = 2;
1941                                         break;
1942                                 case R_IMF_VIEWS_MULTIVIEW:
1943                                         /* not supported at the moment */
1944                                         /* pass through */
1945                                 default:
1946                                         num_views = 1;
1947                         }
1948                         break;
1949                 }
1950         }
1951
1952         return num_views;
1953 }
1954
1955 void BKE_sequencer_proxy_rebuild_context(
1956         Main *bmain, Depsgraph *depsgraph, Scene *scene,
1957         Sequence *seq, struct GSet *file_list, ListBase *queue)
1958 {
1959         SeqIndexBuildContext *context;
1960         Sequence *nseq;
1961         LinkData *link;
1962         int num_files;
1963         int i;
1964
1965         if (!seq->strip || !seq->strip->proxy) {
1966                 return;
1967         }
1968
1969         if (!(seq->flag & SEQ_USE_PROXY)) {
1970                 return;
1971         }
1972
1973         num_files = seq_proxy_context_count(seq, scene);
1974
1975         for (i = 0; i < num_files; i++) {
1976                 if (seq_proxy_multiview_context_invalid(seq, scene, i))
1977                         continue;
1978
1979                 context = MEM_callocN(sizeof(SeqIndexBuildContext), "seq proxy rebuild context");
1980
1981                 nseq = BKE_sequence_dupli_recursive(scene, scene, seq, 0);
1982
1983                 context->tc_flags   = nseq->strip->proxy->build_tc_flags;
1984                 context->size_flags = nseq->strip->proxy->build_size_flags;
1985                 context->quality    = nseq->strip->proxy->quality;
1986                 context->overwrite = (nseq->strip->proxy->build_flags & SEQ_PROXY_SKIP_EXISTING) == 0;
1987
1988                 context->bmain = bmain;
1989                 context->depsgraph = depsgraph;
1990                 context->scene = scene;
1991                 context->orig_seq = seq;
1992                 context->seq = nseq;
1993
1994                 context->view_id = i; /* only for images */
1995
1996                 link = BLI_genericNodeN(context);
1997                 BLI_addtail(queue, link);
1998
1999                 if (nseq->type == SEQ_TYPE_MOVIE) {
2000                         StripAnim *sanim;
2001
2002                         seq_open_anim_file(scene, nseq, true);
2003                         sanim = BLI_findlink(&nseq->anims,  i);
2004
2005                         if (sanim->anim) {
2006                                 context->index_context = IMB_anim_index_rebuild_context(sanim->anim,
2007                                         context->tc_flags, context->size_flags, context->quality,
2008                                         context->overwrite, file_list);
2009                         }
2010                 }
2011         }
2012 }
2013
2014 void BKE_sequencer_proxy_rebuild(SeqIndexBuildContext *context, short *stop, short *do_update, float *progress)
2015 {
2016         const bool overwrite = context->overwrite;
2017         SeqRenderData render_context;
2018         Sequence *seq = context->seq;
2019         Scene *scene = context->scene;
2020         Main *bmain = context->bmain;
2021         int cfra;
2022
2023         if (seq->type == SEQ_TYPE_MOVIE) {
2024                 if (context->index_context) {
2025                         IMB_anim_index_rebuild(context->index_context, stop, do_update, progress);
2026                 }
2027
2028                 return;
2029         }
2030
2031         if (!(seq->flag & SEQ_USE_PROXY)) {
2032                 return;
2033         }
2034
2035         /* that's why it is called custom... */
2036         if (seq->strip->proxy && seq->strip->proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE) {
2037                 return;
2038         }
2039
2040         /* fail safe code */
2041
2042         BKE_sequencer_new_render_data(
2043                 bmain, context->depsgraph, context->scene,
2044                 (scene->r.size * (float) scene->r.xsch) / 100.0f + 0.5f,
2045                 (scene->r.size * (float) scene->r.ysch) / 100.0f + 0.5f, 100,
2046                 false,
2047                 &render_context);
2048
2049         render_context.skip_cache = true;
2050         render_context.is_proxy_render = true;
2051         render_context.view_id = context->view_id;
2052
2053         SeqRenderState state;
2054         sequencer_state_init(&state);
2055
2056         for (cfra = seq->startdisp + seq->startstill;  cfra < seq->enddisp - seq->endstill; cfra++) {
2057                 if (context->size_flags & IMB_PROXY_25) {
2058                         seq_proxy_build_frame(&render_context, &state, seq, cfra, 25, overwrite);
2059                 }
2060                 if (context->size_flags & IMB_PROXY_50) {
2061                         seq_proxy_build_frame(&render_context, &state, seq, cfra, 50, overwrite);
2062                 }
2063                 if (context->size_flags & IMB_PROXY_75) {
2064                         seq_proxy_build_frame(&render_context, &state, seq, cfra, 75, overwrite);
2065                 }
2066                 if (context->size_flags & IMB_PROXY_100) {
2067                         seq_proxy_build_frame(&render_context, &state, seq, cfra, 100, overwrite);
2068                 }
2069
2070                 *progress = (float) (cfra - seq->startdisp - seq->startstill) / (seq->enddisp - seq->endstill - seq->startdisp - seq->startstill);
2071                 *do_update = true;
2072
2073                 if (*stop || G.is_break)
2074                         break;
2075         }
2076 }
2077
2078 void BKE_sequencer_proxy_rebuild_finish(SeqIndexBuildContext *context, bool stop)
2079 {
2080         if (context->index_context) {
2081                 StripAnim *sanim;
2082
2083                 for (sanim = context->seq->anims.first; sanim; sanim = sanim->next)
2084                         IMB_close_anim_proxies(sanim->anim);
2085
2086                 for (sanim = context->orig_seq->anims.first; sanim; sanim = sanim->next)
2087                         IMB_close_anim_proxies(sanim->anim);
2088
2089                 IMB_anim_index_rebuild_finish(context->index_context, stop);
2090         }
2091
2092         seq_free_sequence_recurse(NULL, context->seq);
2093
2094         MEM_freeN(context);
2095 }
2096
2097 void BKE_sequencer_proxy_set(struct Sequence *seq, bool value)
2098 {
2099         if (value) {
2100                 seq->flag |= SEQ_USE_PROXY;
2101                 if (seq->strip->proxy == NULL) {
2102                         seq->strip->proxy = MEM_callocN(sizeof(struct StripProxy), "StripProxy");
2103                         seq->strip->proxy->quality = 90;
2104                         seq->strip->proxy->build_tc_flags = SEQ_PROXY_TC_ALL;
2105                         seq->strip->proxy->build_size_flags = SEQ_PROXY_IMAGE_SIZE_25;
2106                 }
2107         }
2108         else {
2109                 seq->flag &= ~SEQ_USE_PROXY;
2110         }
2111 }
2112
2113 /*********************** color balance *************************/
2114
2115 static StripColorBalance calc_cb(StripColorBalance *cb_)
2116 {
2117         StripColorBalance cb = *cb_;
2118         int c;
2119
2120         for (c = 0; c < 3; c++) {
2121                 cb.lift[c] = 2.0f - cb.lift[c];
2122         }
2123
2124         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_LIFT) {
2125                 for (c = 0; c < 3; c++) {
2126                         /* tweak to give more subtle results
2127                          * values above 1.0 are scaled */
2128                         if (cb.lift[c] > 1.0f)
2129                                 cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0;
2130
2131                         cb.lift[c] = 2.0f - cb.lift[c];
2132                 }
2133         }
2134
2135         if (cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAIN) {
2136                 for (c = 0; c < 3; c++) {
2137                         if (cb.gain[c] != 0.0f) {
2138                                 cb.gain[c] = 1.0f / cb.gain[c];
2139                         }
2140                         else {
2141                                 cb.gain[c] = 1000000; /* should be enough :) */
2142                         }
2143                 }
2144         }
2145
2146         if (!(cb.flag & SEQ_COLOR_BALANCE_INVERSE_GAMMA)) {
2147                 for (c = 0; c < 3; c++) {
2148                         if (cb.gamma[c] != 0.0f) {
2149                                 cb.gamma[c] = 1.0f / cb.gamma[c];
2150                         }
2151                         else {
2152                                 cb.gamma[c] = 1000000; /* should be enough :) */
2153                         }
2154                 }
2155         }
2156
2157         return cb;
2158 }
2159
2160 /* note: lift is actually 2-lift */
2161 MINLINE float color_balance_fl(float in, const float lift, const float gain, const float gamma, const float mul)
2162 {
2163         float x = (((in - 1.0f) * lift) + 1.0f) * gain;
2164
2165         /* prevent NaN */
2166         if (x < 0.f)
2167                 x = 0.f;
2168
2169         return powf(x, gamma) * mul;
2170 }
2171
2172 static void make_cb_table_float(float lift, float gain, float gamma,
2173                                 float *table, float mul)
2174 {
2175         int y;
2176
2177         for (y = 0; y < 256; y++) {
2178                 float v = color_balance_fl((float)y * (1.0f / 255.0f), lift, gain, gamma, mul);
2179
2180                 table[y] = v;
2181         }
2182 }
2183
2184 static void color_balance_byte_byte(StripColorBalance *cb_, unsigned char *rect, unsigned char *mask_rect, int width, int height, float mul)
2185 {
2186         //unsigned char cb_tab[3][256];
2187         unsigned char *cp = rect;
2188         unsigned char *e = cp + width * 4 * height;
2189         unsigned char *m = mask_rect;
2190
2191         StripColorBalance cb = calc_cb(cb_);
2192
2193         while (cp < e) {
2194                 float p[4];
2195                 int c;
2196
2197                 straight_uchar_to_premul_float(p, cp);
2198
2199                 for (c = 0; c < 3; c++) {
2200                         float t = color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
2201
2202                         if (m) {
2203                                 float m_normal = (float) m[c] / 255.0f;
2204
2205                                 p[c] = p[c] * (1.0f - m_normal) + t * m_normal;
2206                         }
2207                         else
2208                                 p[c] = t;
2209                 }
2210
2211                 premul_float_to_straight_uchar(cp, p);
2212
2213                 cp += 4;
2214                 if (m)
2215                         m += 4;
2216         }
2217 }
2218
2219 static void color_balance_byte_float(StripColorBalance *cb_, unsigned char *rect, float *rect_float, unsigned char *mask_rect, int width, int height, float mul)
2220 {
2221         float cb_tab[4][256];
2222         int c, i;
2223         unsigned char *p = rect;
2224         unsigned char *e = p + width * 4 * height;
2225         unsigned char *m = mask_rect;
2226         float *o;
2227         StripColorBalance cb;
2228
2229         o = rect_float;
2230
2231         cb = calc_cb(cb_);
2232
2233         for (c = 0; c < 3; c++) {
2234                 make_cb_table_float(cb.lift[c], cb.gain[c], cb.gamma[c], cb_tab[c], mul);
2235         }
2236
2237         for (i = 0; i < 256; i++) {
2238                 cb_tab[3][i] = ((float)i) * (1.0f / 255.0f);
2239         }
2240
2241         while (p < e) {
2242                 if (m) {
2243                         float t[3] = {m[0] / 255.0f, m[1] / 255.0f, m[2] / 255.0f};
2244
2245                         p[0] = p[0] * (1.0f - t[0]) + t[0] * cb_tab[0][p[0]];
2246                         p[1] = p[1] * (1.0f - t[1]) + t[1] * cb_tab[1][p[1]];
2247                         p[2] = p[2] * (1.0f - t[2]) + t[2] * cb_tab[2][p[2]];
2248
2249                         m += 4;
2250                 }
2251                 else {
2252                         o[0] = cb_tab[0][p[0]];
2253                         o[1] = cb_tab[1][p[1]];
2254                         o[2] = cb_tab[2][p[2]];
2255                 }
2256
2257                 o[3] = cb_tab[3][p[3]];
2258
2259                 p += 4; o += 4;
2260         }
2261 }
2262
2263 static void color_balance_float_float(StripColorBalance *cb_, float *rect_float, float *mask_rect_float, int width, int height, float mul)
2264 {
2265         float *p = rect_float;
2266         const float *e = rect_float + width * 4 * height;
2267         const float *m = mask_rect_float;
2268         StripColorBalance cb = calc_cb(cb_);
2269
2270         while (p < e) {
2271                 int c;
2272                 for (c = 0; c < 3; c++) {
2273                         float t = color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul);
2274
2275                         if (m)
2276                                 p[c] = p[c] * (1.0f - m[c]) + t * m[c];
2277                         else
2278                                 p[c] = t;
2279                 }
2280
2281                 p += 4;
2282                 if (m)
2283                         m += 4;
2284         }
2285 }
2286
2287 typedef struct ColorBalanceInitData {
2288         StripColorBalance *cb;
2289         ImBuf *ibuf;
2290         float mul;
2291         ImBuf *mask;
2292         bool make_float;
2293 } ColorBalanceInitData;
2294
2295 typedef struct ColorBalanceThread {
2296         StripColorBalance *cb;
2297         float mul;
2298
2299         int width, height;
2300
2301         unsigned char *rect, *mask_rect;
2302         float *rect_float, *mask_rect_float;
2303
2304         bool make_float;
2305 } ColorBalanceThread;
2306
2307 static void color_balance_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
2308 {
2309         ColorBalanceThread *handle = (ColorBalanceThread *) handle_v;
2310         ColorBalanceInitData *init_data = (ColorBalanceInitData *) init_data_v;
2311         ImBuf *ibuf = init_data->ibuf;
2312         ImBuf *mask = init_data->mask;
2313
2314         int offset = 4 * start_line * ibuf->x;
2315
2316         memset(handle, 0, sizeof(ColorBalanceThread));
2317
2318         handle->cb = init_data->cb;
2319         handle->mul = init_data->mul;
2320         handle->width = ibuf->x;
2321         handle->height = tot_line;
2322         handle->make_float = init_data->make_float;
2323
2324         if (ibuf->rect)
2325                 handle->rect = (unsigned char *) ibuf->rect + offset;
2326
2327         if (ibuf->rect_float)
2328                 handle->rect_float = ibuf->rect_float + offset;
2329
2330         if (mask) {
2331                 if (mask->rect)
2332                         handle->mask_rect = (unsigned char *) mask->rect + offset;
2333
2334                 if (mask->rect_float)
2335                         handle->mask_rect_float = mask->rect_float + offset;
2336         }
2337         else {
2338                 handle->mask_rect = NULL;
2339                 handle->mask_rect_float = NULL;
2340         }
2341 }
2342
2343 static void *color_balance_do_thread(void *thread_data_v)
2344 {
2345         ColorBalanceThread *thread_data = (ColorBalanceThread *) thread_data_v;
2346         StripColorBalance *cb = thread_data->cb;
2347         int width = thread_data->width, height = thread_data->height;
2348         unsigned char *rect = thread_data->rect;
2349         unsigned char *mask_rect = thread_data->mask_rect;
2350         float *rect_float = thread_data->rect_float;
2351         float *mask_rect_float = thread_data->mask_rect_float;
2352         float mul = thread_data->mul;
2353
2354         if (rect_float) {
2355                 color_balance_float_float(cb, rect_float, mask_rect_float, width, height, mul);
2356         }
2357         else if (thread_data->make_float) {
2358                 color_balance_byte_float(cb, rect, rect_float, mask_rect, width, height, mul);
2359         }
2360         else {
2361                 color_balance_byte_byte(cb, rect, mask_rect, width, height, mul);
2362         }
2363
2364         return NULL;
2365 }
2366
2367 /* cfra is offset by fra_offset only in case we are using a real mask. */
2368 ImBuf *BKE_sequencer_render_mask_input(
2369         const SeqRenderData *context, int mask_input_type, Sequence *mask_sequence, Mask *mask_id,
2370         int cfra, int fra_offset, bool make_float)
2371 {
2372         ImBuf *mask_input = NULL;
2373
2374         if (mask_input_type == SEQUENCE_MASK_INPUT_STRIP) {
2375                 if (mask_sequence) {
2376                         SeqRenderState state;
2377                         sequencer_state_init(&state);
2378
2379                         mask_input = seq_render_strip(context, &state, mask_sequence, cfra);
2380
2381                         if (make_float) {
2382                                 if (!mask_input->rect_float)
2383                                         IMB_float_from_rect(mask_input);
2384                         }
2385                         else {
2386                                 if (!mask_input->rect)
2387                                         IMB_rect_from_float(mask_input);
2388                         }
2389                 }
2390         }
2391         else if (mask_input_type == SEQUENCE_MASK_INPUT_ID) {
2392                 mask_input = seq_render_mask(context, mask_id, cfra - fra_offset, make_float);
2393         }
2394
2395         return mask_input;
2396 }
2397
2398 void BKE_sequencer_color_balance_apply(StripColorBalance *cb, ImBuf *ibuf, float mul, bool make_float, ImBuf *mask_input)
2399 {
2400         ColorBalanceInitData init_data;
2401
2402         if (!ibuf->rect_float && make_float)
2403                 imb_addrectfloatImBuf(ibuf);
2404
2405         init_data.cb = cb;
2406         init_data.ibuf = ibuf;
2407         init_data.mul = mul;
2408         init_data.make_float = make_float;
2409         init_data.mask = mask_input;
2410
2411         IMB_processor_apply_threaded(ibuf->y, sizeof(ColorBalanceThread), &init_data,
2412                                      color_balance_init_handle, color_balance_do_thread);
2413
2414         /* color balance either happens on float buffer or byte buffer, but never on both,
2415          * free byte buffer if there's float buffer since float buffer would be used for
2416          * color balance in favor of byte buffer
2417          */
2418         if (ibuf->rect_float && ibuf->rect)
2419                 imb_freerectImBuf(ibuf);
2420 }
2421
2422 /*
2423  * input preprocessing for SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP and SEQ_TYPE_SCENE
2424  *
2425  * Do all the things you can't really do afterwards using sequence effects
2426  * (read: before rescaling to render resolution has been done)
2427  *
2428  * Order is important!
2429  *
2430  * - Deinterlace
2431  * - Crop and transform in image source coordinate space
2432  * - Flip X + Flip Y (could be done afterwards, backward compatibility)
2433  * - Promote image to float data (affects pipeline operations afterwards)
2434  * - Color balance (is most efficient in the byte -> float
2435  *   (future: half -> float should also work fine!)
2436  *   case, if done on load, since we can use lookup tables)
2437  * - Premultiply
2438  */
2439
2440 bool BKE_sequencer_input_have_to_preprocess(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra))
2441 {
2442         float mul;
2443
2444         if (context->is_proxy_render) {
2445                 return false;
2446         }
2447
2448         if (seq->flag & (SEQ_FILTERY | SEQ_USE_CROP | SEQ_USE_TRANSFORM | SEQ_FLIPX | SEQ_FLIPY | SEQ_MAKE_FLOAT)) {
2449                 return true;
2450         }
2451
2452         mul = seq->mul;
2453
2454         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2455                 mul *= seq->blend_opacity / 100.0f;
2456         }
2457
2458         if (mul != 1.0f) {
2459                 return true;
2460         }
2461
2462         if (seq->sat != 1.0f) {
2463                 return true;
2464         }
2465
2466         if (seq->modifiers.first) {
2467                 return true;
2468         }
2469
2470         return false;
2471 }
2472
2473 static ImBuf *input_preprocess(const SeqRenderData *context, Sequence *seq, float cfra, ImBuf *ibuf,
2474                                const bool is_proxy_image, const bool is_preprocessed)
2475 {
2476         Scene *scene = context->scene;
2477         float mul;
2478
2479         ibuf = IMB_makeSingleUser(ibuf);
2480
2481         if ((seq->flag & SEQ_FILTERY) &&
2482             !ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP))
2483         {
2484                 IMB_filtery(ibuf);
2485         }
2486
2487         if (seq->flag & (SEQ_USE_CROP | SEQ_USE_TRANSFORM)) {
2488                 StripCrop c = {0};
2489                 StripTransform t = {0};
2490                 int sx, sy, dx, dy;
2491
2492                 if (is_proxy_image) {
2493                         double f = seq_rendersize_to_scale_factor(context->preview_render_size);
2494
2495                         if (f != 1.0) {
2496                                 IMB_scalefastImBuf(ibuf, ibuf->x / f, ibuf->y / f);
2497                         }
2498                 }
2499
2500                 if (seq->flag & SEQ_USE_CROP && seq->strip->crop) {
2501                         c = *seq->strip->crop;
2502                 }
2503                 if (seq->flag & SEQ_USE_TRANSFORM && seq->strip->transform) {
2504                         t = *seq->strip->transform;
2505                 }
2506
2507                 if (is_preprocessed) {
2508                         double xscale = scene->r.xsch ? ((double)context->rectx / (double)scene->r.xsch) : 1.0;
2509                         double yscale = scene->r.ysch ? ((double)context->recty / (double)scene->r.ysch) : 1.0;
2510                         if (seq->flag & SEQ_USE_TRANSFORM) {
2511                                 t.xofs *= xscale;
2512                                 t.yofs *= yscale;
2513                         }
2514                         if (seq->flag & SEQ_USE_CROP) {
2515                                 c.left *= xscale;
2516                                 c.right *= xscale;
2517                                 c.top *= yscale;
2518                                 c.bottom *= yscale;
2519                         }
2520                 }
2521
2522                 sx = ibuf->x - c.left - c.right;
2523                 sy = ibuf->y - c.top - c.bottom;
2524
2525                 if (seq->flag & SEQ_USE_TRANSFORM) {
2526                         if (is_preprocessed) {
2527                                 dx = context->rectx;
2528                                 dy = context->recty;
2529                         }
2530                         else {
2531                                 dx = scene->r.xsch;
2532                                 dy = scene->r.ysch;
2533                         }
2534                 }
2535                 else {
2536                         dx = sx;
2537                         dy = sy;
2538                 }
2539
2540                 if (c.top  + c.bottom >= ibuf->y ||
2541                     c.left + c.right  >= ibuf->x ||
2542                     t.xofs >= dx || t.yofs >= dy)
2543                 {
2544                         make_black_ibuf(ibuf);
2545                 }
2546                 else {
2547                         ImBuf *i = IMB_allocImBuf(dx, dy, 32, ibuf->rect_float ? IB_rectfloat : IB_rect);
2548
2549                         IMB_rectcpy(i, ibuf, t.xofs, t.yofs, c.left, c.bottom, sx, sy);
2550                         sequencer_imbuf_assign_spaces(scene, i);
2551
2552                         IMB_metadata_copy(i, ibuf);
2553                         IMB_freeImBuf(ibuf);
2554
2555                         ibuf = i;
2556                 }
2557         }
2558
2559         if (seq->flag & SEQ_FLIPX) {
2560                 IMB_flipx(ibuf);
2561         }
2562
2563         if (seq->flag & SEQ_FLIPY) {
2564                 IMB_flipy(ibuf);
2565         }
2566
2567         if (seq->sat != 1.0f) {
2568                 IMB_saturation(ibuf, seq->sat);
2569         }
2570
2571         mul = seq->mul;
2572
2573         if (seq->blend_mode == SEQ_BLEND_REPLACE) {
2574                 mul *= seq->blend_opacity / 100.0f;
2575         }
2576
2577         if (seq->flag & SEQ_MAKE_FLOAT) {
2578                 if (!ibuf->rect_float) {
2579                         BKE_sequencer_imbuf_to_sequencer_space(scene, ibuf, true);
2580                 }
2581
2582                 if (ibuf->rect) {
2583                         imb_freerectImBuf(ibuf);
2584                 }
2585         }
2586
2587         if (mul != 1.0f) {
2588                 multibuf(ibuf, mul);
2589         }
2590
2591         if (ibuf->x != context->rectx || ibuf->y != context->recty) {
2592                 if (scene->r.mode & R_OSA) {
2593                         IMB_scaleImBuf(ibuf, (short)context->rectx, (short)context->recty);
2594                 }
2595                 else {
2596                         IMB_scalefastImBuf(ibuf, (short)context->rectx, (short)context->recty);
2597                 }
2598         }
2599
2600         if (seq->modifiers.first) {
2601                 ImBuf *ibuf_new = BKE_sequence_modifier_apply_stack(context, seq, ibuf, cfra);
2602
2603                 if (ibuf_new != ibuf) {
2604                         IMB_metadata_copy(ibuf_new, ibuf);
2605                         IMB_freeImBuf(ibuf);
2606                         ibuf = ibuf_new;
2607                 }
2608         }
2609
2610         return ibuf;
2611 }
2612
2613 static ImBuf *copy_from_ibuf_still(const SeqRenderData *context, Sequence *seq, float nr)
2614 {
2615         ImBuf *rval = NULL;
2616         ImBuf *ibuf = NULL;
2617
2618         if (nr == 0) {
2619                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL);
2620         }
2621         else if (nr == seq->len - 1) {
2622                 ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL);
2623         }
2624
2625         if (ibuf) {
2626                 rval = IMB_dupImBuf(ibuf);
2627                 IMB_metadata_copy(rval, ibuf);
2628                 IMB_freeImBuf(ibuf);
2629         }
2630
2631         return rval;
2632 }
2633
2634 static void copy_to_ibuf_still(const SeqRenderData *context, Sequence *seq, float nr, ImBuf *ibuf)
2635 {
2636         /* warning: ibuf may be NULL if the video fails to load */
2637         if (nr == 0 || nr == seq->len - 1) {
2638                 /* we have to store a copy, since the passed ibuf
2639                  * could be preprocessed afterwards (thereby silently
2640                  * changing the cached image... */
2641                 ImBuf *oibuf = ibuf;
2642                 ibuf = IMB_dupImBuf(oibuf);
2643
2644                 if (ibuf) {
2645                         IMB_metadata_copy(ibuf, oibuf);
2646                         sequencer_imbuf_assign_spaces(context->scene, ibuf);
2647                 }
2648
2649                 if (nr == 0) {
2650                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf);
2651                 }
2652
2653                 if (nr == seq->len - 1) {
2654                         BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf);
2655                 }
2656
2657                 IMB_freeImBuf(ibuf);
2658         }
2659 }
2660
2661 /*********************** strip rendering functions  *************************/
2662
2663 typedef struct RenderEffectInitData {
2664         struct SeqEffectHandle *sh;
2665         const SeqRenderData *context;
2666         Sequence *seq;
2667         float cfra, facf0, facf1;
2668         ImBuf *ibuf1, *ibuf2, *ibuf3;
2669
2670         ImBuf *out;
2671 } RenderEffectInitData;
2672
2673 typedef struct RenderEffectThread {
2674         struct SeqEffectHandle *sh;
2675         const SeqRenderData *context;
2676         Sequence *seq;
2677         float cfra, facf0, facf1;
2678         ImBuf *ibuf1, *ibuf2, *ibuf3;
2679
2680         ImBuf *out;
2681         int start_line, tot_line;
2682 } RenderEffectThread;
2683
2684 static void render_effect_execute_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
2685 {
2686         RenderEffectThread *handle = (RenderEffectThread *) handle_v;
2687         RenderEffectInitData *init_data = (RenderEffectInitData *) init_data_v;
2688
2689         handle->sh = init_data->sh;
2690         handle->context = init_data->context;
2691         handle->seq = init_data->seq;
2692         handle->cfra = init_data->cfra;
2693         handle->facf0 = init_data->facf0;
2694         handle->facf1 = init_data->facf1;
2695         handle->ibuf1 = init_data->ibuf1;
2696         handle->ibuf2 = init_data->ibuf2;
2697         handle->ibuf3 = init_data->ibuf3;
2698         handle->out = init_data->out;
2699
2700         handle->start_line = start_line;
2701         handle->tot_line = tot_line;
2702 }
2703
2704 static void *render_effect_execute_do_thread(void *thread_data_v)
2705 {
2706         RenderEffectThread *thread_data = (RenderEffectThread *) thread_data_v;
2707
2708         thread_data->sh->execute_slice(thread_data->context, thread_data->seq, thread_data->cfra,
2709                                        thread_data->facf0, thread_data->facf1, thread_data->ibuf1,
2710                                        thread_data->ibuf2, thread_data->ibuf3, thread_data->start_line,
2711                                        thread_data->tot_line, thread_data->out);
2712
2713         return NULL;
2714 }
2715
2716 static ImBuf *seq_render_effect_execute_threaded(struct SeqEffectHandle *sh, const SeqRenderData *context, Sequence *seq,
2717                                                  float cfra, float facf0, float facf1,
2718                                                  ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
2719 {
2720         RenderEffectInitData init_data;
2721         ImBuf *out = sh->init_execution(context, ibuf1, ibuf2, ibuf3);
2722
2723         init_data.sh = sh;
2724         init_data.context = context;
2725         init_data.seq = seq;
2726         init_data.cfra = cfra;
2727         init_data.facf0 = facf0;
2728         init_data.facf1 = facf1;
2729         init_data.ibuf1 = ibuf1;
2730         init_data.ibuf2 = ibuf2;
2731         init_data.ibuf3 = ibuf3;
2732         init_data.out = out;
2733
2734         IMB_processor_apply_threaded(out->y, sizeof(RenderEffectThread), &init_data,
2735                                      render_effect_execute_init_handle, render_effect_execute_do_thread);
2736
2737         return out;
2738 }
2739
2740 static ImBuf *seq_render_effect_strip_impl(
2741         const SeqRenderData *context, SeqRenderState *state,
2742         Sequence *seq, float cfra)
2743 {
2744         Scene *scene = context->scene;
2745         float fac, facf;
2746         int early_out;
2747         int i;
2748         struct SeqEffectHandle sh = BKE_sequence_get_effect(seq);
2749         FCurve *fcu = NULL;
2750         ImBuf *ibuf[3];
2751         Sequence *input[3];
2752         ImBuf *out = NULL;
2753
2754         ibuf[0] = ibuf[1] = ibuf[2] = NULL;
2755
2756         input[0] = seq->seq1; input[1] = seq->seq2; input[2] = seq->seq3;
2757
2758         if (!sh.execute && !(sh.execute_slice && sh.init_execution)) {
2759                 /* effect not supported in this version... */
2760                 out = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect);
2761                 return out;
2762         }
2763
2764         if (seq->flag & SEQ_USE_EFFECT_DEFAULT_FADE) {
2765                 sh.get_default_fac(seq, cfra, &fac, &facf);
2766                 facf = fac;
2767         }
2768         else {
2769                 fcu = id_data_find_fcurve(&scene->id, seq, &RNA_Sequence, "effect_fader", 0, NULL);
2770                 if (fcu) {
2771                         fac = facf = evaluate_fcurve(fcu, cfra);
2772                 }
2773                 else {
2774                         fac = facf = seq->effect_fader;
2775                 }
2776         }
2777
2778         early_out = sh.early_out(seq, fac, facf);
2779
2780         switch (early_out) {
2781                 case EARLY_NO_INPUT:
2782                         out = sh.execute(context, seq, cfra, fac, facf, NULL, NULL, NULL);
2783                         break;
2784                 case EARLY_DO_EFFECT:
2785                         for (i = 0; i < 3; i++) {
2786                                 if (input[i])
2787                                         ibuf[i] = seq_render_strip(context, state, input[i], cfra);
2788                         }
2789
2790                         if (ibuf[0] && ibuf[1]) {
2791                                 if (sh.multithreaded)
2792                                         out = seq_render_effect_execute_threaded(&sh, context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
2793                                 else
2794                                         out = sh.execute(context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]);
2795                         }
2796                         break;
2797                 case EARLY_USE_INPUT_1:
2798                         if (input[0]) {
2799                                 ibuf[0] = seq_render_strip(context, state, input[0], cfra);
2800                         }
2801                         if (ibuf[0]) {
2802                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
2803                                         out = IMB_dupImBuf(ibuf[0]);
2804                                 }
2805                                 else {
2806                                         out = ibuf[0];
2807                                         IMB_refImBuf(out);
2808                                 }
2809                         }
2810                         break;
2811                 case EARLY_USE_INPUT_2:
2812                         if (input[1]) {
2813                                 ibuf[1] = seq_render_strip(context, state, input[1], cfra);
2814                         }
2815                         if (ibuf[1]) {
2816                                 if (BKE_sequencer_input_have_to_preprocess(context, seq, cfra)) {
2817                                         out = IMB_dupImBuf(ibuf[1]);
2818                                 }
2819                                 else {
2820                                         out = ibuf[1];
2821                                         IMB_refImBuf(out);
2822                                 }
2823                         }
2824                         break;
2825         }
2826
2827         for (i = 0; i < 3; i++) {
2828                 IMB_freeImBuf(ibuf[i]);
2829         }
2830
2831         if (out == NULL) {
2832                 out = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect);
2833         }
2834
2835         return out;
2836 }
2837
2838 static ImBuf *seq_render_image_strip(const SeqRenderData *context, Sequence *seq, float nr, float cfra)
2839 {
2840         ImBuf *ibuf = NULL;
2841         char name[FILE_MAX];
2842         bool is_multiview = (seq->flag & SEQ_USE_VIEWS) != 0 &&
2843                             (context->scene->r.scemode & R_MULTIVIEW) != 0;
2844         StripElem *s_elem = BKE_sequencer_give_stripelem(seq, cfra);
2845         int flag;
2846
2847         if (s_elem) {
2848                 BLI_join_dirfile(name, sizeof(name), seq->strip->dir, s_elem->name);
2849                 BLI_path_abs(name, BKE_main_blendfile_path_from_global());
2850         }
2851
2852         flag = IB_rect | IB_metadata;
2853         if (seq->alpha_mode == SEQ_ALPHA_PREMUL)
2854                 flag |= IB_alphamode_premul;
2855
2856         if (!s_elem) {
2857                 /* don't do anything */
2858         }
2859         else if (is_multiview) {
2860                 const int totfiles = seq_num_files(context->scene, seq->views_format, true);
2861                 int totviews;
2862                 struct ImBuf **ibufs_arr;
2863                 char prefix[FILE_MAX];
2864                 const char *ext = NULL;
2865                 int i;
2866
2867                 if (totfiles > 1) {
2868                         BKE_scene_multiview_view_prefix_get(context->scene, name, prefix, &ext);
2869                         if (prefix[0] == '\0') {
2870                                 goto monoview_image;
2871                         }
2872                 }
2873                 else {
2874                         prefix[0] = '\0';
2875                 }
2876
2877                 totviews = BKE_scene_multiview_num_views_get(&context->scene->r);
2878                 ibufs_arr = MEM_callocN(sizeof(ImBuf *) * totviews, "Sequence Image Views Imbufs");
2879
2880                 for (i = 0; i < totfiles; i++) {
2881
2882                         if (prefix[0] == '\0') {
2883                                 ibufs_arr[i] = IMB_loadiffname(name, flag, seq->strip->colorspace_settings.name);
2884                         }
2885                         else {
2886                                 char str[FILE_MAX];
2887                                 seq_multiview_name(context->scene, i, prefix, ext, str, FILE_MAX);
2888                                 ibufs_arr[i] = IMB_loadiffname(str, flag, seq->strip->colorspace_settings.name);
2889                         }
2890
2891                         if (ibufs_arr[i]) {
2892                                 /* we don't need both (speed reasons)! */
2893                                 if (ibufs_arr[i]->rect_float && ibufs_arr[i]->rect)
2894                                         imb_freerectImBuf(ibufs_arr[i]);
2895                         }
2896                 }
2897
2898                 if (seq->views_format == R_IMF_VIEWS_STEREO_3D && ibufs_arr[0])
2899                         IMB_ImBufFromStereo3d(seq->stereo3d_format, ibufs_arr[0], &ibufs_arr[0], &ibufs_arr[1]);
2900
2901                 for (i = 0; i < totviews; i++) {
2902                         if (ibufs_arr[i]) {
2903                                 SeqRenderData localcontext = *context;
2904                                 localcontext.view_id = i;
2905
2906                                 /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2907                                 BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibufs_arr[i], false);
2908
2909                                 if (i != context->view_id) {
2910                                         copy_to_ibuf_still(&localcontext, seq, nr, ibufs_arr[i]);
2911                                         BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_STRIPELEM_IBUF, ibufs_arr[i]);
2912                                 }
2913                         }
2914                 }
2915
2916                 /* return the original requested ImBuf */
2917                 ibuf = ibufs_arr[context->view_id];
2918                 if (ibuf) {
2919                         s_elem->orig_width  = ibufs_arr[0]->x;
2920                         s_elem->orig_height = ibufs_arr[0]->y;
2921                 }
2922
2923                 /* "remove" the others (decrease their refcount) */
2924                 for (i = 0; i < totviews; i++) {
2925                         if (ibufs_arr[i] != ibuf) {
2926                                 IMB_freeImBuf(ibufs_arr[i]);
2927                         }
2928                 }
2929
2930                 MEM_freeN(ibufs_arr);
2931         }
2932         else {
2933 monoview_image:
2934                 if ((ibuf = IMB_loadiffname(name, flag, seq->strip->colorspace_settings.name))) {
2935                         /* we don't need both (speed reasons)! */
2936                         if (ibuf->rect_float && ibuf->rect)
2937                                 imb_freerectImBuf(ibuf);
2938
2939                         /* all sequencer color is done in SRGB space, linear gives odd crossfades */
2940                         BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf, false);
2941
2942                         s_elem->orig_width  = ibuf->x;
2943                         s_elem->orig_height = ibuf->y;
2944                 }
2945         }
2946
2947         return ibuf;
2948 }
2949
2950 static ImBuf *seq_render_movie_strip(const SeqRenderData *context, Sequence *seq, float nr, float cfra)
2951 {
2952         ImBuf *ibuf = NULL;
2953         StripAnim *sanim;
2954         bool is_multiview = (seq->flag & SEQ_USE_VIEWS) != 0 &&
2955                             (context->scene->r.scemode & R_MULTIVIEW) != 0;
2956
2957         /* load all the videos */
2958         seq_open_anim_file(context->scene, seq, false);
2959
2960         if (is_multiview) {
2961                 ImBuf **ibuf_arr;
2962                 const int totfiles = seq_num_files(context->scene, seq->views_format, true);
2963                 int totviews;
2964                 int i;
2965
2966                 if (totfiles != BLI_listbase_count_at_most(&seq->anims, totfiles + 1))
2967                         goto monoview_movie;
2968
2969                 totviews = BKE_scene_multiview_num_views_get(&context->scene->r);
2970                 ibuf_arr = MEM_callocN(sizeof(ImBuf *) * totviews, "Sequence Image Views Imbufs");
2971
2972                 for (i = 0, sanim = seq->anims.first; sanim; sanim = sanim->next, i++) {
2973                         if (sanim->anim) {
2974                                 IMB_Proxy_Size proxy_size = seq_rendersize_to_proxysize(context->preview_render_size);
2975                                 IMB_anim_set_preseek(sanim->anim, seq->anim_preseek);
2976
2977                                 ibuf_arr[i] = IMB_anim_absolute(sanim->anim, nr + seq->anim_startofs,
2978                                                                 seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
2979                                                                 proxy_size);
2980
2981                                 /* fetching for requested proxy size failed, try fetching the original instead */
2982                                 if (!ibuf_arr[i] && proxy_size != IMB_PROXY_NONE) {
2983                                         ibuf_arr[i] = IMB_anim_absolute(sanim->anim, nr + seq->anim_startofs,
2984                                                                         seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
2985                                                                         IMB_PROXY_NONE);
2986                                 }
2987                                 if (ibuf_arr[i]) {
2988                                         /* we don't need both (speed reasons)! */
2989                                         if (ibuf_arr[i]->rect_float && ibuf_arr[i]->rect)
2990                                                 imb_freerectImBuf(ibuf_arr[i]);
2991                                 }
2992                         }
2993                 }
2994
2995                 if (seq->views_format == R_IMF_VIEWS_STEREO_3D) {
2996                         if (ibuf_arr[0]) {
2997                                 IMB_ImBufFromStereo3d(seq->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
2998                         }
2999                         else {
3000                                 /* probably proxy hasn't been created yet */
3001                                 MEM_freeN(ibuf_arr);
3002                                 return NULL;
3003                         }
3004                 }
3005
3006                 for (i = 0; i < totviews; i++) {
3007                         SeqRenderData localcontext = *context;
3008                         localcontext.view_id = i;
3009
3010                         if (ibuf_arr[i]) {
3011                                 /* all sequencer color is done in SRGB space, linear gives odd crossfades */
3012                                 BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf_arr[i], false);
3013                         }
3014                         if (i != context->view_id) {
3015                                 copy_to_ibuf_still(&localcontext, seq, nr, ibuf_arr[i]);
3016                                 BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf_arr[i]);
3017                         }
3018                 }
3019
3020                 /* return the original requested ImBuf */
3021                 ibuf = ibuf_arr[context->view_id];
3022                 if (ibuf) {
3023                         seq->strip->stripdata->orig_width = ibuf->x;
3024                         seq->strip->stripdata->orig_height = ibuf->y;
3025                 }
3026
3027                 /* "remove" the others (decrease their refcount) */
3028                 for (i = 0; i < totviews; i++) {
3029                         if (ibuf_arr[i] != ibuf) {
3030                                 IMB_freeImBuf(ibuf_arr[i]);
3031                         }
3032                 }
3033
3034                 MEM_freeN(ibuf_arr);
3035         }
3036         else {
3037 monoview_movie:
3038                 sanim = seq->anims.first;
3039                 if (sanim && sanim->anim) {
3040                         IMB_Proxy_Size proxy_size = seq_rendersize_to_proxysize(context->preview_render_size);
3041                         IMB_anim_set_preseek(sanim->anim, seq->anim_preseek);
3042
3043                         ibuf = IMB_anim_absolute(sanim->anim, nr + seq->anim_startofs,
3044                                                  seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
3045                                                  proxy_size);
3046
3047                         /* fetching for requested proxy size failed, try fetching the original instead */
3048                         if (!ibuf && proxy_size != IMB_PROXY_NONE) {
3049                                 ibuf = IMB_anim_absolute(sanim->anim, nr + seq->anim_startofs,
3050                                                          seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN,
3051                                                          IMB_PROXY_NONE);
3052                         }
3053                         if (ibuf) {
3054                                 BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf, false);
3055
3056                                 /* we don't need both (speed reasons)! */
3057                                 if (ibuf->rect_float && ibuf->rect) {
3058                                         imb_freerectImBuf(ibuf);
3059                                 }
3060
3061                                 seq->strip->stripdata->orig_width = ibuf->x;
3062                                 seq->strip->stripdata->orig_height = ibuf->y;
3063                         }
3064                 }
3065         }
3066         return ibuf;
3067 }
3068
3069 static ImBuf *seq_render_movieclip_strip(const SeqRenderData *context, Sequence *seq, float nr)
3070 {
3071         ImBuf *ibuf = NULL;
3072         MovieClipUser user;
3073         float tloc[2], tscale, tangle;
3074
3075         if (!seq->clip) {
3076                 return NULL;
3077         }
3078
3079         memset(&user, 0, sizeof(MovieClipUser));
3080
3081         BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs + seq->clip->start_frame);
3082
3083         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
3084
3085         switch (seq_rendersize_to_proxysize(context->preview_render_size)) {
3086                 case IMB_PROXY_NONE:
3087                         user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
3088                         break;
3089                 case IMB_PROXY_100:
3090                         user.render_size = MCLIP_PROXY_RENDER_SIZE_100;
3091                         break;
3092                 case IMB_PROXY_75:
3093                         user.render_size = MCLIP_PROXY_RENDER_SIZE_75;
3094                         break;
3095                 case IMB_PROXY_50:
3096                         user.render_size = MCLIP_PROXY_RENDER_SIZE_50;
3097                         break;
3098                 case IMB_PROXY_25:
3099                         user.render_size = MCLIP_PROXY_RENDER_SIZE_25;
3100                         break;
3101         }
3102
3103         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_UNDISTORTED) {
3104                 user.render_flag = MCLIP_PROXY_RENDER_UNDISTORT;
3105         }
3106
3107         if (seq->clip_flag & SEQ_MOVIECLIP_RENDER_STABILIZED) {
3108                 ibuf = BKE_movieclip_get_stable_ibuf(seq->clip, &user, tloc, &tscale, &tangle, 0);
3109         }
3110         else {
3111                 ibuf = BKE_movieclip_get_ibuf_flag(seq->clip, &user, 0, MOVIECLIP_CACHE_SKIP);
3112         }
3113
3114         return ibuf;
3115 }
3116
3117
3118 static ImBuf *seq_render_mask(const SeqRenderData *context, Mask *mask, float nr, bool make_float)
3119 {
3120         /* TODO - add option to rasterize to alpha imbuf? */
3121         ImBuf *ibuf = NULL;
3122         float *maskbuf;
3123         int i;
3124
3125         if (!mask) {
3126                 return NULL;
3127         }
3128         else {
3129                 AnimData *adt;
3130                 Mask *mask_temp;
3131                 MaskRasterHandle *mr_handle;
3132
3133                 mask_temp = BKE_mask_copy_nolib(mask);
3134
3135                 BKE_mask_evaluate(mask_temp, mask->sfra + nr, true);
3136
3137                 /* anim-data */
3138                 adt = BKE_animdata_from_id(&mask->id);
3139                 BKE_animsys_evaluate_animdata(context->depsgraph, context->scene, &mask_temp->id, adt, nr, ADT_RECALC_ANIM);
3140
3141                 maskbuf = MEM_mallocN(sizeof(float) * context->rectx * context->recty, __func__);
3142
3143                 mr_handle = BKE_maskrasterize_handle_new();
3144
3145                 BKE_maskrasterize_handle_init(mr_handle, mask_temp, context->rectx, context->recty, true, true, true);
3146
3147                 BKE_mask_free(mask_temp);
3148                 MEM_freeN(mask_temp);
3149
3150                 BKE_maskrasterize_buffer(mr_handle, context->rectx, context->recty, maskbuf);
3151
3152                 BKE_maskrasterize_handle_free(mr_handle);
3153         }
3154
3155
3156         if (make_float) {
3157                 /* pixels */
3158                 const float *fp_src;
3159                 float *fp_dst;
3160
3161                 ibuf = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rectfloat);
3162
3163                 fp_src = maskbuf;
3164                 fp_dst = ibuf->rect_float;
3165                 i = context->rectx * context->recty;
3166                 while (--i) {
3167                         fp_dst[0] = fp_dst[1] = fp_dst[2] = *fp_src;
3168                         fp_dst[3] = 1.0f;
3169
3170                         fp_src += 1;
3171                         fp_dst += 4;
3172                 }
3173         }
3174         else {
3175                 /* pixels */
3176                 const float *fp_src;
3177                 unsigned char *ub_dst;
3178
3179                 ibuf = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect);
3180
3181                 fp_src = maskbuf;
3182                 ub_dst = (unsigned char *)ibuf->rect;
3183                 i = context->rectx * context->recty;