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