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