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