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