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