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