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