Merged changes in the trunk up to revision 42116.
[blender.git] / source / blender / imbuf / intern / indexer.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  * Peter Schlaile <peter [at] schlaile [dot] de> 2011
19  *
20  * Contributor(s): none yet.
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 #include "IMB_indexer.h"
26 #include "IMB_anim.h"
27 #include "AVI_avi.h"
28 #include "imbuf.h"
29 #include "MEM_guardedalloc.h"
30
31 #include "BLI_utildefines.h"
32 #include "BLI_blenlib.h"
33 #include "BLI_math_base.h"
34
35 #include "MEM_guardedalloc.h"
36 #include "DNA_userdef_types.h"
37 #include "BKE_global.h"
38 #include <stdlib.h>
39
40 #ifdef WITH_FFMPEG
41
42 #include "ffmpeg_compat.h"
43
44 #endif //WITH_FFMPEG
45
46
47 static char magic[] = "BlenMIdx";
48 static char temp_ext [] = "_part";
49
50 static int proxy_sizes[] = { IMB_PROXY_25, IMB_PROXY_50, IMB_PROXY_75,
51                              IMB_PROXY_100 };
52 static float proxy_fac[] = { 0.25, 0.50, 0.75, 1.00 };
53
54 #ifdef WITH_FFMPEG
55 static int tc_types[] = { IMB_TC_RECORD_RUN, IMB_TC_FREE_RUN,
56                           IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN };
57 #endif
58
59 #define INDEX_FILE_VERSION 1
60
61 /* ---------------------------------------------------------------------- 
62    - special indexers
63    ---------------------------------------------------------------------- 
64  */
65
66 extern void IMB_indexer_dv_new(anim_index_builder * idx);
67
68
69 /* ----------------------------------------------------------------------
70    - time code index functions
71    ---------------------------------------------------------------------- */
72
73 anim_index_builder * IMB_index_builder_create(const char * name)
74 {
75
76         anim_index_builder * rv
77                 = MEM_callocN( sizeof(struct anim_index_builder),
78                                "index builder");
79
80         fprintf(stderr, "Starting work on index: %s\n", name);
81
82         BLI_strncpy(rv->name, name, sizeof(rv->name));
83         BLI_strncpy(rv->temp_name, name, sizeof(rv->temp_name));
84
85         strcat(rv->temp_name, temp_ext);
86
87         BLI_make_existing_file(rv->temp_name);
88
89         rv->fp = fopen(rv->temp_name, "wb");
90
91         if (!rv->fp) {
92                 fprintf(stderr, "Couldn't open index target: %s! "
93                         "Index build broken!\n", rv->temp_name);
94                 MEM_freeN(rv);
95                 return NULL;
96         }
97
98         fprintf(rv->fp, "%s%c%.3d", magic, (ENDIAN_ORDER==B_ENDIAN)?'V':'v',
99                 INDEX_FILE_VERSION);
100
101         return rv;
102 }
103
104 void IMB_index_builder_add_entry(anim_index_builder * fp, 
105                                  int frameno,unsigned long long seek_pos,
106                                  unsigned long long seek_pos_dts,
107                                  unsigned long long pts)
108 {
109         fwrite(&frameno, sizeof(int), 1, fp->fp);
110         fwrite(&seek_pos, sizeof(unsigned long long), 1, fp->fp);
111         fwrite(&seek_pos_dts, sizeof(unsigned long long), 1, fp->fp);
112         fwrite(&pts, sizeof(unsigned long long), 1, fp->fp);
113 }
114
115 void IMB_index_builder_proc_frame(anim_index_builder * fp, 
116                                   unsigned char * buffer,
117                                   int data_size,
118                                   int frameno, unsigned long long seek_pos,
119                                   unsigned long long seek_pos_dts,
120                                   unsigned long long pts)
121 {
122         if (fp->proc_frame) {
123                 anim_index_entry e;
124                 e.frameno = frameno;
125                 e.seek_pos = seek_pos;
126                 e.seek_pos_dts = seek_pos_dts;
127                 e.pts = pts;
128
129                 fp->proc_frame(fp, buffer, data_size, &e);
130         } else {
131                 IMB_index_builder_add_entry(fp, frameno, seek_pos,
132                                             seek_pos_dts, pts);
133         }
134 }
135
136 void IMB_index_builder_finish(anim_index_builder * fp, int rollback)
137 {
138         if (fp->delete_priv_data) {
139                 fp->delete_priv_data(fp);
140         }
141
142         fclose(fp->fp);
143         
144         if (rollback) {
145                 unlink(fp->temp_name);
146         } else {
147                 rename(fp->temp_name, fp->name);
148         }
149
150         MEM_freeN(fp);
151 }
152
153 struct anim_index * IMB_indexer_open(const char * name)
154 {
155         char header[13];
156         struct anim_index * idx;
157         FILE * fp = fopen(name, "rb");
158         int i;
159
160         if (!fp) {
161                 return NULL;
162         }
163
164         if (fread(header, 12, 1, fp) != 1) {
165                 fclose(fp);
166                 return NULL;
167         }
168
169         header[12] = 0;
170
171         if (memcmp(header, magic, 8) != 0) {
172                 fclose(fp);
173                 return NULL;
174         }
175
176         if (atoi(header+9) != INDEX_FILE_VERSION) {
177                 fclose(fp);
178                 return NULL;
179         }
180
181         idx = MEM_callocN( sizeof(struct anim_index), "anim_index");
182
183         BLI_strncpy(idx->name, name, sizeof(idx->name));
184         
185         fseek(fp, 0, SEEK_END);
186
187         idx->num_entries = (ftell(fp) - 12)
188                 / (sizeof(int) // framepos
189                    + sizeof(unsigned long long) // seek_pos
190                    + sizeof(unsigned long long) // seek_pos_dts
191                    + sizeof(unsigned long long) // pts
192                         );
193         
194         fseek(fp, 12, SEEK_SET);
195
196         idx->entries = MEM_callocN( sizeof(struct anim_index_entry) 
197                                     * idx->num_entries, "anim_index_entries");
198
199         for (i = 0; i < idx->num_entries; i++) {
200                 fread(&idx->entries[i].frameno,
201                       sizeof(int), 1, fp);
202                 fread(&idx->entries[i].seek_pos,
203                       sizeof(unsigned long long), 1, fp);
204                 fread(&idx->entries[i].seek_pos_dts,
205                       sizeof(unsigned long long), 1, fp);
206                 fread(&idx->entries[i].pts,
207                       sizeof(unsigned long long), 1, fp);
208         }
209
210         if (((ENDIAN_ORDER == B_ENDIAN) != (header[8] == 'V'))) {
211                 for (i = 0; i < idx->num_entries; i++) {
212                         SWITCH_INT(idx->entries[i].frameno);
213                         SWITCH_INT64(idx->entries[i].seek_pos);
214                         SWITCH_INT64(idx->entries[i].seek_pos_dts);
215                         SWITCH_INT64(idx->entries[i].pts);
216                 }
217         }
218
219         fclose(fp);
220
221         return idx;
222 }
223
224 unsigned long long IMB_indexer_get_seek_pos(
225         struct anim_index * idx, int frame_index)
226 {
227         if (frame_index < 0) {
228                 frame_index = 0;
229         }
230         if (frame_index >= idx->num_entries) {
231                 frame_index = idx->num_entries - 1;
232         }
233         return idx->entries[frame_index].seek_pos;
234 }
235
236 unsigned long long IMB_indexer_get_seek_pos_dts(
237         struct anim_index * idx, int frame_index)
238 {
239         if (frame_index < 0) {
240                 frame_index = 0;
241         }
242         if (frame_index >= idx->num_entries) {
243                 frame_index = idx->num_entries - 1;
244         }
245         return idx->entries[frame_index].seek_pos_dts;
246 }
247
248 int IMB_indexer_get_frame_index(struct anim_index * idx, int frameno)
249 {
250         int len = idx->num_entries;
251         int half;
252         int middle;
253         int first = 0;
254
255         /* bsearch (lower bound) the right index */
256         
257         while (len > 0) {
258                 half = len >> 1;
259                 middle = first;
260
261                 middle += half;
262
263                 if (idx->entries[middle].frameno < frameno) {
264                         first = middle;
265                         ++first;
266                         len = len - half - 1;
267                 } else {
268                         len = half;
269                 }
270         }
271
272         if (first == idx->num_entries) {
273                 return idx->num_entries - 1;
274         } else {
275                 return first;
276         }
277 }
278
279 unsigned long long IMB_indexer_get_pts(struct anim_index * idx, 
280                                        int frame_index)
281 {
282         if (frame_index < 0) {
283                 frame_index = 0;
284         }
285         if (frame_index >= idx->num_entries) {
286                 frame_index = idx->num_entries - 1;
287         }
288         return idx->entries[frame_index].pts;
289 }
290
291 int IMB_indexer_get_duration(struct anim_index * idx)
292 {
293         if (idx->num_entries == 0) {
294                 return 0;
295         }
296         return idx->entries[idx->num_entries-1].frameno + 1;
297 }
298
299 int IMB_indexer_can_scan(struct anim_index * idx, 
300                          int old_frame_index, int new_frame_index)
301 {
302         /* makes only sense, if it is the same I-Frame and we are not
303            trying to run backwards in time... */
304         return (IMB_indexer_get_seek_pos(idx, old_frame_index)
305                 == IMB_indexer_get_seek_pos(idx, new_frame_index) && 
306                 old_frame_index < new_frame_index);
307 }
308
309 void IMB_indexer_close(struct anim_index * idx)
310 {
311         MEM_freeN(idx->entries);
312         MEM_freeN(idx);
313 }
314
315 int IMB_proxy_size_to_array_index(IMB_Proxy_Size pr_size)
316 {
317         switch (pr_size) {
318         case IMB_PROXY_NONE: /* if we got here, something is broken anyways,
319                                 so sane defaults... */
320                 return 0;
321         case IMB_PROXY_25:
322                 return 0;
323         case IMB_PROXY_50:
324                 return 1;
325         case IMB_PROXY_75:
326                 return 2;
327         case IMB_PROXY_100:
328                 return 3;
329         default:
330                 return 0;
331         };
332         return 0;
333 }
334
335 int IMB_timecode_to_array_index(IMB_Timecode_Type tc)
336 {
337         switch (tc) {
338         case IMB_TC_NONE: /* if we got here, something is broken anyways,
339                                 so sane defaults... */
340                 return 0;
341         case IMB_TC_RECORD_RUN:
342                 return 0;
343         case IMB_TC_FREE_RUN:
344                 return 1;
345         case IMB_TC_INTERPOLATED_REC_DATE_FREE_RUN:
346                 return 2;
347         default:
348                 return 0;
349         };
350         return 0;
351 }
352
353
354 /* ----------------------------------------------------------------------
355    - rebuild helper functions
356    ---------------------------------------------------------------------- */
357
358 static void get_index_dir(struct anim * anim, char * index_dir)
359 {
360         if (!anim->index_dir[0]) {
361                 char fname[FILE_MAXFILE];
362                 BLI_strncpy(index_dir, anim->name, FILE_MAXDIR);
363                 BLI_splitdirstring(index_dir, fname);
364                 BLI_join_dirfile(index_dir, FILE_MAXDIR, index_dir, "BL_proxy");
365                 BLI_join_dirfile(index_dir, FILE_MAXDIR, index_dir, fname);
366         } else {
367                 BLI_strncpy(index_dir, anim->index_dir, FILE_MAXDIR);
368         }
369 }
370
371 static void get_proxy_filename(struct anim * anim, IMB_Proxy_Size preview_size,
372                                char * fname, int temp)
373 {
374         char index_dir[FILE_MAXDIR];
375         int i = IMB_proxy_size_to_array_index(preview_size);
376
377         char proxy_name[256];
378         char proxy_temp_name[256];
379         char stream_suffix[20];
380         
381         stream_suffix[0] = 0;
382
383         if (anim->streamindex > 0) {
384                 BLI_snprintf(stream_suffix, 20, "_st%d", anim->streamindex);
385         }
386
387         BLI_snprintf(proxy_name, 256, "proxy_%d%s.avi", 
388                      (int) (proxy_fac[i] * 100), stream_suffix);
389         BLI_snprintf(proxy_temp_name, 256, "proxy_%d%s_part.avi", 
390                      (int) (proxy_fac[i] * 100), stream_suffix);
391
392         get_index_dir(anim, index_dir);
393
394         BLI_join_dirfile(fname, FILE_MAXFILE + FILE_MAXDIR, index_dir, 
395                          temp ? proxy_temp_name : proxy_name);
396 }
397
398 static void get_tc_filename(struct anim * anim, IMB_Timecode_Type tc,
399                             char * fname)
400 {
401         char index_dir[FILE_MAXDIR];
402         int i = IMB_timecode_to_array_index(tc);
403         const char * index_names[] = {
404                 "record_run%s.blen_tc", "free_run%s.blen_tc",
405                 "interp_free_run%s.blen_tc" };
406
407         char stream_suffix[20];
408         char index_name[256];
409         
410         stream_suffix[0] = 0;
411
412         if (anim->streamindex > 0) {
413                 BLI_snprintf(stream_suffix, 20, "_st%d", anim->streamindex);
414         }
415         
416         BLI_snprintf(index_name, 256, index_names[i], stream_suffix);
417
418         get_index_dir(anim, index_dir);
419         
420         BLI_join_dirfile(fname, FILE_MAXFILE + FILE_MAXDIR, 
421                          index_dir, index_name);
422 }
423
424 /* ----------------------------------------------------------------------
425    - ffmpeg rebuilder
426    ---------------------------------------------------------------------- */
427
428 #ifdef WITH_FFMPEG
429
430 struct proxy_output_ctx {
431         AVFormatContext* of;
432         AVStream* st;
433         AVCodecContext* c;
434         AVCodec* codec;
435         struct SwsContext * sws_ctx;
436         AVFrame* frame;
437         uint8_t* video_buffer;
438         int video_buffersize;
439         int cfra;
440         int proxy_size;
441         int orig_height;
442         struct anim * anim;
443 };
444
445 // work around stupid swscaler 16 bytes alignment bug...
446
447 static int round_up(int x, int mod)
448 {
449         return x + ((mod - (x % mod)) % mod);
450 }
451
452 static struct proxy_output_ctx * alloc_proxy_output_ffmpeg(
453         struct anim * anim,
454         AVStream * st, int proxy_size, int width, int height,
455         int UNUSED(quality))
456 {
457         struct proxy_output_ctx * rv = MEM_callocN(
458                 sizeof(struct proxy_output_ctx), "alloc_proxy_output");
459         
460         char fname[FILE_MAX];
461
462         // JPEG requires this
463         width = round_up(width, 8);
464         height = round_up(height, 8);
465
466         rv->proxy_size = proxy_size;
467         rv->anim = anim;
468
469         get_proxy_filename(rv->anim, rv->proxy_size, fname, TRUE);
470         BLI_make_existing_file(fname);
471
472         rv->of = avformat_alloc_context();
473         rv->of->oformat = av_guess_format("avi", NULL, NULL);
474         
475         BLI_snprintf(rv->of->filename, sizeof(rv->of->filename), "%s", fname);
476
477         fprintf(stderr, "Starting work on proxy: %s\n", rv->of->filename);
478
479         rv->st = av_new_stream(rv->of, 0);
480         rv->c = rv->st->codec;
481         rv->c->codec_type = AVMEDIA_TYPE_VIDEO;
482         rv->c->codec_id = CODEC_ID_MJPEG;
483         rv->c->width = width;
484         rv->c->height = height;
485
486         rv->of->oformat->video_codec = rv->c->codec_id;
487         rv->codec = avcodec_find_encoder(rv->c->codec_id);
488
489         if (!rv->codec) {
490                 fprintf(stderr, "No ffmpeg MJPEG encoder available? "
491                         "Proxy not built!\n");
492                 av_free(rv->of);
493                 return NULL;
494         }
495
496         if (rv->codec->pix_fmts) {
497                 rv->c->pix_fmt = rv->codec->pix_fmts[0];
498         } else {
499                 rv->c->pix_fmt = PIX_FMT_YUVJ420P;
500         }
501
502         rv->c->sample_aspect_ratio 
503                 = rv->st->sample_aspect_ratio 
504                 = st->codec->sample_aspect_ratio;
505
506         rv->c->time_base.den = 25;
507         rv->c->time_base.num = 1;
508         rv->st->time_base = rv->c->time_base;
509
510         if (rv->of->flags & AVFMT_GLOBALHEADER) {
511                 rv->c->flags |= CODEC_FLAG_GLOBAL_HEADER;
512         }
513
514         if (av_set_parameters(rv->of, NULL) < 0) {
515                 fprintf(stderr, "Couldn't set output parameters? "
516                         "Proxy not built!\n");
517                 av_free(rv->of);
518                 return 0;
519         }
520
521         if (avio_open(&rv->of->pb, fname, AVIO_FLAG_WRITE) < 0) {
522                 fprintf(stderr, "Couldn't open outputfile! "
523                         "Proxy not built!\n");
524                 av_free(rv->of);
525                 return 0;
526         }
527
528         avcodec_open(rv->c, rv->codec);
529
530         rv->video_buffersize = 2000000;
531         rv->video_buffer = (uint8_t*)MEM_mallocN(
532                 rv->video_buffersize, "FFMPEG video buffer");
533
534         rv->orig_height = st->codec->height;
535
536         if (st->codec->width != width || st->codec->height != height ||
537                 st->codec->pix_fmt != rv->c->pix_fmt)
538         {
539                 rv->frame = avcodec_alloc_frame();
540                 avpicture_fill((AVPicture*) rv->frame,
541                                MEM_mallocN(avpicture_get_size(
542                                                rv->c->pix_fmt,
543                                                round_up(width, 16), height),
544                                            "alloc proxy output frame"),
545                                rv->c->pix_fmt, round_up(width, 16), height);
546
547                 rv->sws_ctx = sws_getContext(
548                         st->codec->width,
549                         st->codec->height,
550                         st->codec->pix_fmt,
551                         width, height,
552                         rv->c->pix_fmt,
553                         SWS_FAST_BILINEAR | SWS_PRINT_INFO,
554                         NULL, NULL, NULL);
555         }
556
557         av_write_header(rv->of);
558
559         return rv;
560 }
561
562 static int add_to_proxy_output_ffmpeg(
563         struct proxy_output_ctx * ctx, AVFrame * frame)
564 {
565         int outsize = 0;
566
567         if (!ctx) {
568                 return 0;
569         }
570
571         if (    ctx->sws_ctx && frame &&
572                 (frame->data[0] || frame->data[1] ||
573                  frame->data[2] || frame->data[3]))
574         {
575                 sws_scale(ctx->sws_ctx, (const uint8_t * const*) frame->data,
576                           frame->linesize, 0, ctx->orig_height,
577                           ctx->frame->data, ctx->frame->linesize);
578         }
579
580         frame = ctx->sws_ctx ? (frame ? ctx->frame : 0) : frame;
581
582         if (frame) {
583                 frame->pts = ctx->cfra++;
584         }
585
586         outsize = avcodec_encode_video(
587                 ctx->c, ctx->video_buffer, ctx->video_buffersize, 
588                 frame);
589
590         if (outsize < 0) {
591                 fprintf(stderr, "Error encoding proxy frame %d for '%s'\n", 
592                         ctx->cfra - 1, ctx->of->filename);
593                 return 0;
594         }
595
596         if (outsize != 0) {
597                 AVPacket packet;
598                 av_init_packet(&packet);
599
600                 if (ctx->c->coded_frame->pts != AV_NOPTS_VALUE) {
601                         packet.pts = av_rescale_q(ctx->c->coded_frame->pts,
602                                                   ctx->c->time_base,
603                                                   ctx->st->time_base);
604                 }
605                 if (ctx->c->coded_frame->key_frame)
606                         packet.flags |= AV_PKT_FLAG_KEY;
607
608                 packet.stream_index = ctx->st->index;
609                 packet.data = ctx->video_buffer;
610                 packet.size = outsize;
611
612                 if (av_interleaved_write_frame(ctx->of, &packet) != 0) {
613                         fprintf(stderr, "Error writing proxy frame %d "
614                                 "into '%s'\n", ctx->cfra - 1, 
615                                 ctx->of->filename);
616                         return 0;
617                 }
618
619                 return 1;
620         } else {
621                 return 0;
622         }
623 }
624
625 static void free_proxy_output_ffmpeg(struct proxy_output_ctx * ctx,
626                                      int rollback)
627 {
628         int i;
629         char fname[FILE_MAX];
630         char fname_tmp[FILE_MAX];
631
632         if (!ctx) {
633                 return;
634         }
635
636         if (!rollback) {
637                 while (add_to_proxy_output_ffmpeg(ctx, NULL)) ;
638         }
639
640         avcodec_flush_buffers(ctx->c);
641
642         av_write_trailer(ctx->of);
643         
644         avcodec_close(ctx->c);
645         
646         for (i = 0; i < ctx->of->nb_streams; i++) {
647                 if (&ctx->of->streams[i]) {
648                         av_freep(&ctx->of->streams[i]);
649                 }
650         }
651
652         if (ctx->of->oformat) {
653                 if (!(ctx->of->oformat->flags & AVFMT_NOFILE)) {
654                         avio_close(ctx->of->pb);
655                 }
656         }
657         av_free(ctx->of);
658
659         MEM_freeN(ctx->video_buffer);
660
661         if (ctx->sws_ctx) {
662                 sws_freeContext(ctx->sws_ctx);
663
664                 MEM_freeN(ctx->frame->data[0]);
665                 av_free(ctx->frame);
666         }
667
668         get_proxy_filename(ctx->anim, ctx->proxy_size, 
669                            fname_tmp, TRUE);
670
671         if (rollback) {
672                 unlink(fname_tmp);
673         } else {
674                 get_proxy_filename(ctx->anim, ctx->proxy_size, 
675                                    fname, FALSE);
676                 rename(fname_tmp, fname);
677         }
678         
679         MEM_freeN(ctx);
680 }
681
682
683 static int index_rebuild_ffmpeg(struct anim * anim, 
684                                 IMB_Timecode_Type tcs_in_use,
685                                 IMB_Proxy_Size proxy_sizes_in_use,
686                                 int quality,
687                                 short *stop, short *do_update, 
688                                 float *progress)
689 {
690         int i, videoStream;
691         unsigned long long seek_pos = 0;
692         unsigned long long last_seek_pos = 0;
693         unsigned long long seek_pos_dts = 0;
694         unsigned long long seek_pos_pts = 0;
695         unsigned long long last_seek_pos_dts = 0;
696         unsigned long long start_pts = 0;
697         double frame_rate;
698         double pts_time_base;
699         int frameno = 0;
700         int start_pts_set = FALSE;
701
702         AVFormatContext *iFormatCtx;
703         AVCodecContext *iCodecCtx;
704         AVCodec *iCodec;
705         AVStream *iStream;
706         AVFrame* in_frame = 0;
707         AVPacket next_packet;
708         int streamcount;
709
710         struct proxy_output_ctx * proxy_ctx[IMB_PROXY_MAX_SLOT];
711         anim_index_builder * indexer [IMB_TC_MAX_SLOT];
712
713         int num_proxy_sizes = IMB_PROXY_MAX_SLOT;
714         int num_indexers = IMB_TC_MAX_SLOT;
715         uint64_t stream_size;
716
717         memset(proxy_ctx, 0, sizeof(proxy_ctx));
718         memset(indexer, 0, sizeof(indexer));
719
720         if(av_open_input_file(&iFormatCtx, anim->name, NULL, 0, NULL) != 0) {
721                 return 0;
722         }
723
724         if (av_find_stream_info(iFormatCtx) < 0) {
725                 av_close_input_file(iFormatCtx);
726                 return 0;
727         }
728
729         streamcount = anim->streamindex;
730
731         /* Find the video stream */
732         videoStream = -1;
733         for (i = 0; i < iFormatCtx->nb_streams; i++)
734                 if(iFormatCtx->streams[i]->codec->codec_type
735                    == AVMEDIA_TYPE_VIDEO) {
736                         if (streamcount > 0) {
737                                 streamcount--;
738                                 continue;
739                         }
740                         videoStream = i;
741                         break;
742                 }
743
744         if (videoStream == -1) {
745                 av_close_input_file(iFormatCtx);
746                 return 0;
747         }
748
749         iStream = iFormatCtx->streams[videoStream];
750         iCodecCtx = iStream->codec;
751
752         iCodec = avcodec_find_decoder(iCodecCtx->codec_id);
753         
754         if (iCodec == NULL) {
755                 av_close_input_file(iFormatCtx);
756                 return 0;
757         }
758
759         iCodecCtx->workaround_bugs = 1;
760
761         if (avcodec_open(iCodecCtx, iCodec) < 0) {
762                 av_close_input_file(iFormatCtx);
763                 return 0;
764         }
765
766         in_frame = avcodec_alloc_frame();
767
768         stream_size = avio_size(iFormatCtx->pb);
769
770         for (i = 0; i < num_proxy_sizes; i++) {
771                 if (proxy_sizes_in_use & proxy_sizes[i]) {
772                         proxy_ctx[i] = alloc_proxy_output_ffmpeg(
773                                 anim, iStream, proxy_sizes[i],
774                                 iCodecCtx->width * proxy_fac[i],
775                                 iCodecCtx->height * proxy_fac[i],
776                                 quality);
777                         if (!proxy_ctx[i]) {
778                                 proxy_sizes_in_use &= ~proxy_sizes[i];
779                         }
780                 }
781         }
782
783         for (i = 0; i < num_indexers; i++) {
784                 if (tcs_in_use & tc_types[i]) {
785                         char fname[FILE_MAX];
786
787                         get_tc_filename(anim, tc_types[i], fname);
788
789                         indexer[i] = IMB_index_builder_create(fname);
790                         if (!indexer[i]) {
791                                 tcs_in_use &= ~tc_types[i];
792                         }
793                 }
794         }
795
796         frame_rate = av_q2d(iStream->r_frame_rate);
797         pts_time_base = av_q2d(iStream->time_base);
798
799         while(av_read_frame(iFormatCtx, &next_packet) >= 0) {
800                 int frame_finished = 0;
801                 float next_progress =  (float)((int)floor(((double) next_packet.pos) * 100 /
802                                                    ((double) stream_size)+0.5)) / 100;
803
804                 if (*progress != next_progress) {
805                         *progress = next_progress;
806                         *do_update = 1;
807                 }
808
809                 if (*stop) {
810                         av_free_packet(&next_packet);
811                         break;
812                 }
813
814                 if (next_packet.stream_index == videoStream) {
815                         if (next_packet.flags & AV_PKT_FLAG_KEY) {
816                                 last_seek_pos = seek_pos;
817                                 last_seek_pos_dts = seek_pos_dts;
818                                 seek_pos = next_packet.pos;
819                                 seek_pos_dts = next_packet.dts;
820                                 seek_pos_pts = next_packet.pts;
821                         }
822
823                         avcodec_decode_video2(
824                                 iCodecCtx, in_frame, &frame_finished, 
825                                 &next_packet);
826                 }
827
828                 if (frame_finished) {
829                         unsigned long long s_pos = seek_pos;
830                         unsigned long long s_dts = seek_pos_dts;
831                         unsigned long long pts 
832                                 = av_get_pts_from_frame(iFormatCtx, in_frame);
833
834                         for (i = 0; i < num_proxy_sizes; i++) {
835                                 add_to_proxy_output_ffmpeg(
836                                         proxy_ctx[i], in_frame);
837                         }
838
839                         if (!start_pts_set) {
840                                 start_pts = pts;
841                                 start_pts_set = TRUE;
842                         }
843
844                         frameno = floor((pts - start_pts)
845                                 * pts_time_base * frame_rate + 0.5f);
846
847                         /* decoding starts *always* on I-Frames,
848                            so: P-Frames won't work, even if all the
849                            information is in place, when we seek
850                            to the I-Frame presented *after* the P-Frame,
851                            but located before the P-Frame within
852                            the stream */
853
854                         if (pts < seek_pos_pts) {
855                                 s_pos = last_seek_pos;
856                                 s_dts = last_seek_pos_dts;
857                         }
858
859                         for (i = 0; i < num_indexers; i++) {
860                                 if (tcs_in_use & tc_types[i]) {
861                                         IMB_index_builder_proc_frame(
862                                                 indexer[i], 
863                                                 next_packet.data, 
864                                                 next_packet.size,
865                                                 frameno, s_pos, s_dts, pts);
866                                 }
867                         }
868                 }
869                 av_free_packet(&next_packet);
870         }
871
872         for (i = 0; i < num_indexers; i++) {
873                 if (tcs_in_use & tc_types[i]) {
874                         IMB_index_builder_finish(indexer[i], *stop);
875                 }
876         }
877
878         for (i = 0; i < num_proxy_sizes; i++) {
879                 if (proxy_sizes_in_use & proxy_sizes[i]) {
880                         free_proxy_output_ffmpeg(proxy_ctx[i], *stop);
881                 }
882         }
883
884         av_free(in_frame);
885
886         return 1;
887 }
888
889 #endif
890
891 /* ----------------------------------------------------------------------
892    - internal AVI (fallback) rebuilder
893    ---------------------------------------------------------------------- */
894
895 static AviMovie * alloc_proxy_output_avi(
896         struct anim * anim, char * filename, int width, int height,
897         int quality)
898 {
899         int x, y;
900         AviFormat format;
901         double framerate;
902         AviMovie * avi;
903         short frs_sec = 25;      /* it doesn't really matter for proxies,
904                                     but sane defaults help anyways...*/
905         float frs_sec_base = 1.0;
906
907         IMB_anim_get_fps(anim, &frs_sec, &frs_sec_base);
908         
909         x = width;
910         y = height;
911
912         framerate= (double) frs_sec / (double) frs_sec_base;
913         
914         avi = MEM_mallocN (sizeof(AviMovie), "avimovie");
915
916         format = AVI_FORMAT_MJPEG;
917
918         if (AVI_open_compress (filename, avi, 1, format) != AVI_ERROR_NONE) {
919                 MEM_freeN(avi);
920                 return NULL;
921         }
922                         
923         AVI_set_compress_option (avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_WIDTH, &x);
924         AVI_set_compress_option (avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_HEIGHT, &y);
925         AVI_set_compress_option (avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_QUALITY, &quality);           
926         AVI_set_compress_option (avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_FRAMERATE, &framerate);
927
928         avi->interlace= 0;
929         avi->odd_fields= 0;
930
931         return avi;
932 }
933
934 static void index_rebuild_fallback(struct anim * anim,
935                                    IMB_Timecode_Type UNUSED(tcs_in_use),
936                                    IMB_Proxy_Size proxy_sizes_in_use,
937                                    int quality,
938                                    short *stop, short *do_update, 
939                                    float *progress)
940 {
941         int cnt = IMB_anim_get_duration(anim, IMB_TC_NONE);
942         int i, pos;
943         AviMovie * proxy_ctx[IMB_PROXY_MAX_SLOT];
944         char fname[FILE_MAX];
945         char fname_tmp[FILE_MAX];
946         
947         memset(proxy_ctx, 0, sizeof(proxy_ctx));
948
949         /* since timecode indices only work with ffmpeg right now,
950            don't know a sensible fallback here...
951
952            so no proxies, no game to play...
953         */
954         if (proxy_sizes_in_use == IMB_PROXY_NONE) {
955                 return;
956         }
957
958         for (i = 0; i < IMB_PROXY_MAX_SLOT; i++) {
959                 if (proxy_sizes_in_use & proxy_sizes[i]) {
960                         char fname[FILE_MAX];
961
962                         get_proxy_filename(anim, proxy_sizes[i], fname, TRUE);
963                         BLI_make_existing_file(fname);
964
965                         proxy_ctx[i] = alloc_proxy_output_avi(
966                                 anim, fname,
967                                 anim->x * proxy_fac[i],
968                                 anim->y * proxy_fac[i],
969                                 quality);
970                 }
971         }
972
973         for (pos = 0; pos < cnt; pos++) {
974                 struct ImBuf * ibuf = IMB_anim_absolute(
975                         anim, pos, IMB_TC_NONE, IMB_PROXY_NONE);
976                 int next_progress = (int) ((double) pos / (double) cnt);
977
978                 if (*progress != next_progress) {
979                         *progress = next_progress;
980                         *do_update = 1;
981                 }
982                 
983                 if (*stop) {
984                         break;
985                 }
986
987                 IMB_flipy(ibuf);
988
989                 for (i = 0; i < IMB_PROXY_MAX_SLOT; i++) {
990                         if (proxy_sizes_in_use & proxy_sizes[i]) {
991                                 int x = anim->x * proxy_fac[i];
992                                 int y = anim->y * proxy_fac[i];
993
994                                 struct ImBuf * s_ibuf = IMB_scalefastImBuf(
995                                         ibuf, x, y);
996
997                                 IMB_convert_rgba_to_abgr(s_ibuf);
998         
999                                 AVI_write_frame (proxy_ctx[i], pos, 
1000                                                  AVI_FORMAT_RGB32, 
1001                                                  s_ibuf->rect, x * y * 4);
1002
1003                                 /* note that libavi free's the buffer... */
1004                                 s_ibuf->rect = NULL;
1005
1006                                 IMB_freeImBuf(s_ibuf);
1007                         }
1008                 }
1009         }
1010
1011         for (i = 0; i < IMB_PROXY_MAX_SLOT; i++) {
1012                 if (proxy_sizes_in_use & proxy_sizes[i]) {
1013                         AVI_close_compress (proxy_ctx[i]);
1014                         MEM_freeN (proxy_ctx[i]);
1015
1016                         get_proxy_filename(anim, proxy_sizes[i], 
1017                                            fname_tmp, TRUE);
1018                         get_proxy_filename(anim, proxy_sizes[i], 
1019                                            fname, FALSE);
1020
1021                         if (*stop) {
1022                                 unlink(fname_tmp);
1023                         } else {
1024                                 rename(fname_tmp, fname);
1025                         }
1026                 }
1027         }
1028 }
1029
1030 /* ----------------------------------------------------------------------
1031    - public API
1032    ---------------------------------------------------------------------- */
1033
1034 void IMB_anim_index_rebuild(struct anim * anim, IMB_Timecode_Type tcs_in_use,
1035                             IMB_Proxy_Size proxy_sizes_in_use,
1036                             int quality,
1037                             short *stop, short *do_update, float *progress)
1038 {
1039         switch (anim->curtype) {
1040 #ifdef WITH_FFMPEG
1041         case ANIM_FFMPEG:
1042                 index_rebuild_ffmpeg(anim, tcs_in_use, proxy_sizes_in_use,
1043                                      quality, stop, do_update, progress);
1044                 break;
1045 #endif
1046         default:
1047                 index_rebuild_fallback(anim, tcs_in_use, proxy_sizes_in_use,
1048                                        quality, stop, do_update, progress);
1049                 break;
1050         }
1051 }
1052
1053 void IMB_free_indices(struct anim * anim)
1054 {
1055         int i;
1056
1057         for (i = 0; i < IMB_PROXY_MAX_SLOT; i++) {
1058                 if (anim->proxy_anim[i]) {
1059                         IMB_close_anim(anim->proxy_anim[i]);
1060                         anim->proxy_anim[i] = NULL;
1061                 }
1062         }
1063
1064         for (i = 0; i < IMB_TC_MAX_SLOT; i++) {
1065                 if (anim->curr_idx[i]) {
1066                         IMB_indexer_close(anim->curr_idx[i]);
1067                         anim->curr_idx[i] = NULL;
1068                 }
1069         }
1070
1071
1072         anim->proxies_tried = 0;
1073         anim->indices_tried = 0;
1074 }
1075
1076 void IMB_anim_set_index_dir(struct anim * anim, const char * dir)
1077 {
1078         if (strcmp(anim->index_dir, dir) == 0) {
1079                 return;
1080         }
1081         BLI_strncpy(anim->index_dir, dir, sizeof(anim->index_dir));
1082
1083         IMB_free_indices(anim);
1084 }
1085
1086 struct anim * IMB_anim_open_proxy(
1087         struct anim * anim, IMB_Proxy_Size preview_size)
1088 {
1089         char fname[FILE_MAX];
1090         int i = IMB_proxy_size_to_array_index(preview_size);
1091
1092         if (anim->proxy_anim[i]) {
1093                 return anim->proxy_anim[i];
1094         }
1095
1096         if (anim->proxies_tried & preview_size) {
1097                 return NULL;
1098         }
1099
1100         get_proxy_filename(anim, preview_size, fname, FALSE);
1101
1102         anim->proxy_anim[i] = IMB_open_anim(fname, 0, 0);
1103         
1104         anim->proxies_tried |= preview_size;
1105
1106         return anim->proxy_anim[i];
1107 }
1108
1109 struct anim_index * IMB_anim_open_index(
1110         struct anim * anim, IMB_Timecode_Type tc)
1111 {
1112         char fname[FILE_MAX];
1113         int i = IMB_timecode_to_array_index(tc);
1114
1115         if (anim->curr_idx[i]) {
1116                 return anim->curr_idx[i];
1117         }
1118
1119         if (anim->indices_tried & tc) {
1120                 return NULL;
1121         }
1122
1123         get_tc_filename(anim, tc, fname);
1124
1125         anim->curr_idx[i] = IMB_indexer_open(fname);
1126         
1127         anim->indices_tried |= tc;
1128
1129         return anim->curr_idx[i];
1130 }
1131
1132 int IMB_anim_index_get_frame_index(struct anim * anim, IMB_Timecode_Type tc,
1133                                    int position)
1134 {
1135         struct anim_index * idx = IMB_anim_open_index(anim, tc);
1136
1137         if (!idx) {
1138                 return position;
1139         }
1140
1141         return IMB_indexer_get_frame_index(idx, position);
1142 }
1143