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