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