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