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