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