Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / libvpx / source / libvpx / vpxdec.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <assert.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <string.h>
16 #include <limits.h>
17
18 #include "third_party/libyuv/include/libyuv/scale.h"
19
20 #include "./args.h"
21 #include "./ivfdec.h"
22
23 #define VPX_CODEC_DISABLE_COMPAT 1
24 #include "./vpx_config.h"
25 #include "vpx/vpx_decoder.h"
26 #include "vpx_ports/mem_ops.h"
27 #include "vpx_ports/vpx_timer.h"
28
29 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
30 #include "vpx/vp8dx.h"
31 #endif
32
33 #include "./md5_utils.h"
34
35 #include "./tools_common.h"
36 #if CONFIG_WEBM_IO
37 #include "./webmdec.h"
38 #endif
39 #include "./y4menc.h"
40
41 static const char *exec_name;
42
43 struct VpxDecInputContext {
44   struct VpxInputContext *vpx_input_ctx;
45   struct WebmInputContext *webm_ctx;
46 };
47
48 static const arg_def_t looparg = ARG_DEF(NULL, "loops", 1,
49                                           "Number of times to decode the file");
50 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
51                                           "Codec to use");
52 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
53                                           "Output raw YV12 frames");
54 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
55                                           "Output raw I420 frames");
56 static const arg_def_t flipuvarg = ARG_DEF(NULL, "flipuv", 0,
57                                            "Flip the chroma planes in the output");
58 static const arg_def_t rawvideo = ARG_DEF(NULL, "rawvideo", 0,
59                                           "Output raw YUV frames");
60 static const arg_def_t noblitarg = ARG_DEF(NULL, "noblit", 0,
61                                            "Don't process the decoded frames");
62 static const arg_def_t progressarg = ARG_DEF(NULL, "progress", 0,
63                                              "Show progress after each frame decodes");
64 static const arg_def_t limitarg = ARG_DEF(NULL, "limit", 1,
65                                           "Stop decoding after n frames");
66 static const arg_def_t skiparg = ARG_DEF(NULL, "skip", 1,
67                                          "Skip the first n input frames");
68 static const arg_def_t postprocarg = ARG_DEF(NULL, "postproc", 0,
69                                              "Postprocess decoded frames");
70 static const arg_def_t summaryarg = ARG_DEF(NULL, "summary", 0,
71                                             "Show timing summary");
72 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
73                                             "Output file name pattern (see below)");
74 static const arg_def_t threadsarg = ARG_DEF("t", "threads", 1,
75                                             "Max threads to use");
76 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
77                                             "Show version string");
78 static const arg_def_t error_concealment = ARG_DEF(NULL, "error-concealment", 0,
79                                                    "Enable decoder error-concealment");
80 static const arg_def_t scalearg = ARG_DEF("S", "scale", 0,
81                                             "Scale output frames uniformly");
82 static const arg_def_t continuearg =
83     ARG_DEF("k", "keep-going", 0, "(debug) Continue decoding after error");
84
85 static const arg_def_t fb_arg =
86     ARG_DEF(NULL, "frame-buffers", 1, "Number of frame buffers to use");
87
88 static const arg_def_t md5arg = ARG_DEF(NULL, "md5", 0,
89                                         "Compute the MD5 sum of the decoded frame");
90
91 static const arg_def_t *all_args[] = {
92   &codecarg, &use_yv12, &use_i420, &flipuvarg, &rawvideo, &noblitarg,
93   &progressarg, &limitarg, &skiparg, &postprocarg, &summaryarg, &outputfile,
94   &threadsarg, &verbosearg, &scalearg, &fb_arg,
95   &md5arg, &error_concealment, &continuearg,
96   NULL
97 };
98
99 #if CONFIG_VP8_DECODER
100 static const arg_def_t addnoise_level = ARG_DEF(NULL, "noise-level", 1,
101                                                 "Enable VP8 postproc add noise");
102 static const arg_def_t deblock = ARG_DEF(NULL, "deblock", 0,
103                                          "Enable VP8 deblocking");
104 static const arg_def_t demacroblock_level = ARG_DEF(NULL, "demacroblock-level", 1,
105                                                     "Enable VP8 demacroblocking, w/ level");
106 static const arg_def_t pp_debug_info = ARG_DEF(NULL, "pp-debug-info", 1,
107                                                "Enable VP8 visible debug info");
108 static const arg_def_t pp_disp_ref_frame = ARG_DEF(NULL, "pp-dbg-ref-frame", 1,
109                                                    "Display only selected reference frame per macro block");
110 static const arg_def_t pp_disp_mb_modes = ARG_DEF(NULL, "pp-dbg-mb-modes", 1,
111                                                   "Display only selected macro block modes");
112 static const arg_def_t pp_disp_b_modes = ARG_DEF(NULL, "pp-dbg-b-modes", 1,
113                                                  "Display only selected block modes");
114 static const arg_def_t pp_disp_mvs = ARG_DEF(NULL, "pp-dbg-mvs", 1,
115                                              "Draw only selected motion vectors");
116 static const arg_def_t mfqe = ARG_DEF(NULL, "mfqe", 0,
117                                       "Enable multiframe quality enhancement");
118
119 static const arg_def_t *vp8_pp_args[] = {
120   &addnoise_level, &deblock, &demacroblock_level, &pp_debug_info,
121   &pp_disp_ref_frame, &pp_disp_mb_modes, &pp_disp_b_modes, &pp_disp_mvs, &mfqe,
122   NULL
123 };
124 #endif
125
126 static int vpx_image_scale(vpx_image_t *src, vpx_image_t *dst,
127                            FilterModeEnum mode) {
128   assert(src->fmt == VPX_IMG_FMT_I420);
129   assert(dst->fmt == VPX_IMG_FMT_I420);
130   return I420Scale(src->planes[VPX_PLANE_Y], src->stride[VPX_PLANE_Y],
131                    src->planes[VPX_PLANE_U], src->stride[VPX_PLANE_U],
132                    src->planes[VPX_PLANE_V], src->stride[VPX_PLANE_V],
133                    src->d_w, src->d_h,
134                    dst->planes[VPX_PLANE_Y], dst->stride[VPX_PLANE_Y],
135                    dst->planes[VPX_PLANE_U], dst->stride[VPX_PLANE_U],
136                    dst->planes[VPX_PLANE_V], dst->stride[VPX_PLANE_V],
137                    dst->d_w, dst->d_h,
138                    mode);
139 }
140
141 void usage_exit() {
142   int i;
143
144   fprintf(stderr, "Usage: %s <options> filename\n\n"
145           "Options:\n", exec_name);
146   arg_show_usage(stderr, all_args);
147 #if CONFIG_VP8_DECODER
148   fprintf(stderr, "\nVP8 Postprocessing Options:\n");
149   arg_show_usage(stderr, vp8_pp_args);
150 #endif
151   fprintf(stderr,
152           "\nOutput File Patterns:\n\n"
153           "  The -o argument specifies the name of the file(s) to "
154           "write to. If the\n  argument does not include any escape "
155           "characters, the output will be\n  written to a single file. "
156           "Otherwise, the filename will be calculated by\n  expanding "
157           "the following escape characters:\n");
158   fprintf(stderr,
159           "\n\t%%w   - Frame width"
160           "\n\t%%h   - Frame height"
161           "\n\t%%<n> - Frame number, zero padded to <n> places (1..9)"
162           "\n\n  Pattern arguments are only supported in conjunction "
163           "with the --yv12 and\n  --i420 options. If the -o option is "
164           "not specified, the output will be\n  directed to stdout.\n"
165          );
166   fprintf(stderr, "\nIncluded decoders:\n\n");
167
168   for (i = 0; i < get_vpx_decoder_count(); ++i) {
169     const VpxInterface *const decoder = get_vpx_decoder_by_index(i);
170     fprintf(stderr, "    %-6s - %s\n",
171             decoder->name, vpx_codec_iface_name(decoder->codec_interface()));
172   }
173
174   exit(EXIT_FAILURE);
175 }
176
177 static int raw_read_frame(FILE *infile, uint8_t **buffer,
178                           size_t *bytes_read, size_t *buffer_size) {
179   char raw_hdr[RAW_FRAME_HDR_SZ];
180   size_t frame_size = 0;
181
182   if (fread(raw_hdr, RAW_FRAME_HDR_SZ, 1, infile) != 1) {
183     if (!feof(infile))
184       warn("Failed to read RAW frame size\n");
185   } else {
186     const size_t kCorruptFrameThreshold = 256 * 1024 * 1024;
187     const size_t kFrameTooSmallThreshold = 256 * 1024;
188     frame_size = mem_get_le32(raw_hdr);
189
190     if (frame_size > kCorruptFrameThreshold) {
191       warn("Read invalid frame size (%u)\n", (unsigned int)frame_size);
192       frame_size = 0;
193     }
194
195     if (frame_size < kFrameTooSmallThreshold) {
196       warn("Warning: Read invalid frame size (%u) - not a raw file?\n",
197            (unsigned int)frame_size);
198     }
199
200     if (frame_size > *buffer_size) {
201       uint8_t *new_buf = realloc(*buffer, 2 * frame_size);
202       if (new_buf) {
203         *buffer = new_buf;
204         *buffer_size = 2 * frame_size;
205       } else {
206         warn("Failed to allocate compressed data buffer\n");
207         frame_size = 0;
208       }
209     }
210   }
211
212   if (!feof(infile)) {
213     if (fread(*buffer, 1, frame_size, infile) != frame_size) {
214       warn("Failed to read full frame\n");
215       return 1;
216     }
217     *bytes_read = frame_size;
218   }
219
220   return 0;
221 }
222
223 static int read_frame(struct VpxDecInputContext *input, uint8_t **buf,
224                       size_t *bytes_in_buffer, size_t *buffer_size) {
225   switch (input->vpx_input_ctx->file_type) {
226 #if CONFIG_WEBM_IO
227     case FILE_TYPE_WEBM:
228       return webm_read_frame(input->webm_ctx,
229                              buf, bytes_in_buffer, buffer_size);
230 #endif
231     case FILE_TYPE_RAW:
232       return raw_read_frame(input->vpx_input_ctx->file,
233                             buf, bytes_in_buffer, buffer_size);
234     case FILE_TYPE_IVF:
235       return ivf_read_frame(input->vpx_input_ctx->file,
236                             buf, bytes_in_buffer, buffer_size);
237     default:
238       return 1;
239   }
240 }
241
242 static void update_image_md5(const vpx_image_t *img, const int planes[3],
243                              MD5Context *md5) {
244   int i, y;
245
246   for (i = 0; i < 3; ++i) {
247     const int plane = planes[i];
248     const unsigned char *buf = img->planes[plane];
249     const int stride = img->stride[plane];
250     const int w = vpx_img_plane_width(img, plane);
251     const int h = vpx_img_plane_height(img, plane);
252
253     for (y = 0; y < h; ++y) {
254       MD5Update(md5, buf, w);
255       buf += stride;
256     }
257   }
258 }
259
260 static void write_image_file(const vpx_image_t *img, const int planes[3],
261                              FILE *file) {
262   int i, y;
263
264   for (i = 0; i < 3; ++i) {
265     const int plane = planes[i];
266     const unsigned char *buf = img->planes[plane];
267     const int stride = img->stride[plane];
268     const int w = vpx_img_plane_width(img, plane);
269     const int h = vpx_img_plane_height(img, plane);
270
271     for (y = 0; y < h; ++y) {
272       fwrite(buf, 1, w, file);
273       buf += stride;
274     }
275   }
276 }
277
278 int file_is_raw(struct VpxInputContext *input) {
279   uint8_t buf[32];
280   int is_raw = 0;
281   vpx_codec_stream_info_t si;
282
283   si.sz = sizeof(si);
284
285   if (fread(buf, 1, 32, input->file) == 32) {
286     int i;
287
288     if (mem_get_le32(buf) < 256 * 1024 * 1024) {
289       for (i = 0; i < get_vpx_decoder_count(); ++i) {
290         const VpxInterface *const decoder = get_vpx_decoder_by_index(i);
291         if (!vpx_codec_peek_stream_info(decoder->codec_interface(),
292                                         buf + 4, 32 - 4, &si)) {
293           is_raw = 1;
294           input->fourcc = decoder->fourcc;
295           input->width = si.w;
296           input->height = si.h;
297           input->framerate.numerator = 30;
298           input->framerate.denominator = 1;
299           break;
300         }
301       }
302     }
303   }
304
305   rewind(input->file);
306   return is_raw;
307 }
308
309 void show_progress(int frame_in, int frame_out, uint64_t dx_time) {
310   fprintf(stderr,
311           "%d decoded frames/%d showed frames in %"PRId64" us (%.2f fps)\r",
312           frame_in, frame_out, dx_time,
313           (double)frame_out * 1000000.0 / (double)dx_time);
314 }
315
316 struct ExternalFrameBuffer {
317   uint8_t* data;
318   size_t size;
319   int in_use;
320 };
321
322 struct ExternalFrameBufferList {
323   int num_external_frame_buffers;
324   struct ExternalFrameBuffer *ext_fb;
325 };
326
327 // Callback used by libvpx to request an external frame buffer. |cb_priv|
328 // Application private data passed into the set function. |min_size| is the
329 // minimum size in bytes needed to decode the next frame. |fb| pointer to the
330 // frame buffer.
331 int get_vp9_frame_buffer(void *cb_priv, size_t min_size,
332                          vpx_codec_frame_buffer_t *fb) {
333   int i;
334   struct ExternalFrameBufferList *const ext_fb_list =
335       (struct ExternalFrameBufferList *)cb_priv;
336   if (ext_fb_list == NULL)
337     return -1;
338
339   // Find a free frame buffer.
340   for (i = 0; i < ext_fb_list->num_external_frame_buffers; ++i) {
341     if (!ext_fb_list->ext_fb[i].in_use)
342       break;
343   }
344
345   if (i == ext_fb_list->num_external_frame_buffers)
346     return -1;
347
348   if (ext_fb_list->ext_fb[i].size < min_size) {
349     free(ext_fb_list->ext_fb[i].data);
350     ext_fb_list->ext_fb[i].data = (uint8_t *)malloc(min_size);
351     if (!ext_fb_list->ext_fb[i].data)
352       return -1;
353
354     ext_fb_list->ext_fb[i].size = min_size;
355   }
356
357   fb->data = ext_fb_list->ext_fb[i].data;
358   fb->size = ext_fb_list->ext_fb[i].size;
359   ext_fb_list->ext_fb[i].in_use = 1;
360
361   // Set the frame buffer's private data to point at the external frame buffer.
362   fb->priv = &ext_fb_list->ext_fb[i];
363   return 0;
364 }
365
366 // Callback used by libvpx when there are no references to the frame buffer.
367 // |cb_priv| user private data passed into the set function. |fb| pointer
368 // to the frame buffer.
369 int release_vp9_frame_buffer(void *cb_priv,
370                              vpx_codec_frame_buffer_t *fb) {
371   struct ExternalFrameBuffer *const ext_fb =
372       (struct ExternalFrameBuffer *)fb->priv;
373   (void)cb_priv;
374   ext_fb->in_use = 0;
375   return 0;
376 }
377
378 void generate_filename(const char *pattern, char *out, size_t q_len,
379                        unsigned int d_w, unsigned int d_h,
380                        unsigned int frame_in) {
381   const char *p = pattern;
382   char *q = out;
383
384   do {
385     char *next_pat = strchr(p, '%');
386
387     if (p == next_pat) {
388       size_t pat_len;
389
390       /* parse the pattern */
391       q[q_len - 1] = '\0';
392       switch (p[1]) {
393         case 'w':
394           snprintf(q, q_len - 1, "%d", d_w);
395           break;
396         case 'h':
397           snprintf(q, q_len - 1, "%d", d_h);
398           break;
399         case '1':
400           snprintf(q, q_len - 1, "%d", frame_in);
401           break;
402         case '2':
403           snprintf(q, q_len - 1, "%02d", frame_in);
404           break;
405         case '3':
406           snprintf(q, q_len - 1, "%03d", frame_in);
407           break;
408         case '4':
409           snprintf(q, q_len - 1, "%04d", frame_in);
410           break;
411         case '5':
412           snprintf(q, q_len - 1, "%05d", frame_in);
413           break;
414         case '6':
415           snprintf(q, q_len - 1, "%06d", frame_in);
416           break;
417         case '7':
418           snprintf(q, q_len - 1, "%07d", frame_in);
419           break;
420         case '8':
421           snprintf(q, q_len - 1, "%08d", frame_in);
422           break;
423         case '9':
424           snprintf(q, q_len - 1, "%09d", frame_in);
425           break;
426         default:
427           die("Unrecognized pattern %%%c\n", p[1]);
428       }
429
430       pat_len = strlen(q);
431       if (pat_len >= q_len - 1)
432         die("Output filename too long.\n");
433       q += pat_len;
434       p += 2;
435       q_len -= pat_len;
436     } else {
437       size_t copy_len;
438
439       /* copy the next segment */
440       if (!next_pat)
441         copy_len = strlen(p);
442       else
443         copy_len = next_pat - p;
444
445       if (copy_len >= q_len - 1)
446         die("Output filename too long.\n");
447
448       memcpy(q, p, copy_len);
449       q[copy_len] = '\0';
450       q += copy_len;
451       p += copy_len;
452       q_len -= copy_len;
453     }
454   } while (*p);
455 }
456
457 static int is_single_file(const char *outfile_pattern) {
458   const char *p = outfile_pattern;
459
460   do {
461     p = strchr(p, '%');
462     if (p && p[1] >= '1' && p[1] <= '9')
463       return 0;  // pattern contains sequence number, so it's not unique
464     if (p)
465       p++;
466   } while (p);
467
468   return 1;
469 }
470
471 static void print_md5(unsigned char digest[16], const char *filename) {
472   int i;
473
474   for (i = 0; i < 16; ++i)
475     printf("%02x", digest[i]);
476   printf("  %s\n", filename);
477 }
478
479 static FILE *open_outfile(const char *name) {
480   if (strcmp("-", name) == 0) {
481     set_binary_mode(stdout);
482     return stdout;
483   } else {
484     FILE *file = fopen(name, "wb");
485     if (!file)
486       fatal("Failed to output file %s", name);
487     return file;
488   }
489 }
490
491 int main_loop(int argc, const char **argv_) {
492   vpx_codec_ctx_t       decoder;
493   char                  *fn = NULL;
494   int                    i;
495   uint8_t               *buf = NULL;
496   size_t                 bytes_in_buffer = 0, buffer_size = 0;
497   FILE                  *infile;
498   int                    frame_in = 0, frame_out = 0, flipuv = 0, noblit = 0;
499   int                    do_md5 = 0, progress = 0;
500   int                    stop_after = 0, postproc = 0, summary = 0, quiet = 1;
501   int                    arg_skip = 0;
502   int                    ec_enabled = 0;
503   int                    keep_going = 0;
504   const VpxInterface *interface = NULL;
505   const VpxInterface *fourcc_interface = NULL;
506   uint64_t dx_time = 0;
507   struct arg               arg;
508   char                   **argv, **argi, **argj;
509
510   int                     single_file;
511   int                     use_y4m = 1;
512   int                     opt_yv12 = 0;
513   int                     opt_i420 = 0;
514   vpx_codec_dec_cfg_t     cfg = {0};
515 #if CONFIG_VP8_DECODER
516   vp8_postproc_cfg_t      vp8_pp_cfg = {0};
517   int                     vp8_dbg_color_ref_frame = 0;
518   int                     vp8_dbg_color_mb_modes = 0;
519   int                     vp8_dbg_color_b_modes = 0;
520   int                     vp8_dbg_display_mv = 0;
521 #endif
522   int                     frames_corrupted = 0;
523   int                     dec_flags = 0;
524   int                     do_scale = 0;
525   vpx_image_t             *scaled_img = NULL;
526   int                     frame_avail, got_data;
527   int                     num_external_frame_buffers = 0;
528   struct ExternalFrameBufferList ext_fb_list = {0};
529
530   const char *outfile_pattern = NULL;
531   char outfile_name[PATH_MAX] = {0};
532   FILE *outfile = NULL;
533
534   MD5Context md5_ctx;
535   unsigned char md5_digest[16];
536
537   struct VpxDecInputContext input = {0};
538   struct VpxInputContext vpx_input_ctx = {0};
539 #if CONFIG_WEBM_IO
540   struct WebmInputContext webm_ctx = {0};
541   input.webm_ctx = &webm_ctx;
542 #endif
543   input.vpx_input_ctx = &vpx_input_ctx;
544
545   /* Parse command line */
546   exec_name = argv_[0];
547   argv = argv_dup(argc - 1, argv_ + 1);
548
549   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
550     memset(&arg, 0, sizeof(arg));
551     arg.argv_step = 1;
552
553     if (arg_match(&arg, &codecarg, argi)) {
554       interface = get_vpx_decoder_by_name(arg.val);
555       if (!interface)
556         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
557     } else if (arg_match(&arg, &looparg, argi)) {
558       // no-op
559     } else if (arg_match(&arg, &outputfile, argi))
560       outfile_pattern = arg.val;
561     else if (arg_match(&arg, &use_yv12, argi)) {
562       use_y4m = 0;
563       flipuv = 1;
564       opt_yv12 = 1;
565     } else if (arg_match(&arg, &use_i420, argi)) {
566       use_y4m = 0;
567       flipuv = 0;
568       opt_i420 = 1;
569     } else if (arg_match(&arg, &rawvideo, argi)) {
570       use_y4m = 0;
571     } else if (arg_match(&arg, &flipuvarg, argi))
572       flipuv = 1;
573     else if (arg_match(&arg, &noblitarg, argi))
574       noblit = 1;
575     else if (arg_match(&arg, &progressarg, argi))
576       progress = 1;
577     else if (arg_match(&arg, &limitarg, argi))
578       stop_after = arg_parse_uint(&arg);
579     else if (arg_match(&arg, &skiparg, argi))
580       arg_skip = arg_parse_uint(&arg);
581     else if (arg_match(&arg, &postprocarg, argi))
582       postproc = 1;
583     else if (arg_match(&arg, &md5arg, argi))
584       do_md5 = 1;
585     else if (arg_match(&arg, &summaryarg, argi))
586       summary = 1;
587     else if (arg_match(&arg, &threadsarg, argi))
588       cfg.threads = arg_parse_uint(&arg);
589     else if (arg_match(&arg, &verbosearg, argi))
590       quiet = 0;
591     else if (arg_match(&arg, &scalearg, argi))
592       do_scale = 1;
593     else if (arg_match(&arg, &fb_arg, argi))
594       num_external_frame_buffers = arg_parse_uint(&arg);
595
596 #if CONFIG_VP8_DECODER
597     else if (arg_match(&arg, &addnoise_level, argi)) {
598       postproc = 1;
599       vp8_pp_cfg.post_proc_flag |= VP8_ADDNOISE;
600       vp8_pp_cfg.noise_level = arg_parse_uint(&arg);
601     } else if (arg_match(&arg, &demacroblock_level, argi)) {
602       postproc = 1;
603       vp8_pp_cfg.post_proc_flag |= VP8_DEMACROBLOCK;
604       vp8_pp_cfg.deblocking_level = arg_parse_uint(&arg);
605     } else if (arg_match(&arg, &deblock, argi)) {
606       postproc = 1;
607       vp8_pp_cfg.post_proc_flag |= VP8_DEBLOCK;
608     } else if (arg_match(&arg, &mfqe, argi)) {
609       postproc = 1;
610       vp8_pp_cfg.post_proc_flag |= VP8_MFQE;
611     } else if (arg_match(&arg, &pp_debug_info, argi)) {
612       unsigned int level = arg_parse_uint(&arg);
613
614       postproc = 1;
615       vp8_pp_cfg.post_proc_flag &= ~0x7;
616
617       if (level)
618         vp8_pp_cfg.post_proc_flag |= level;
619     } else if (arg_match(&arg, &pp_disp_ref_frame, argi)) {
620       unsigned int flags = arg_parse_int(&arg);
621       if (flags) {
622         postproc = 1;
623         vp8_dbg_color_ref_frame = flags;
624       }
625     } else if (arg_match(&arg, &pp_disp_mb_modes, argi)) {
626       unsigned int flags = arg_parse_int(&arg);
627       if (flags) {
628         postproc = 1;
629         vp8_dbg_color_mb_modes = flags;
630       }
631     } else if (arg_match(&arg, &pp_disp_b_modes, argi)) {
632       unsigned int flags = arg_parse_int(&arg);
633       if (flags) {
634         postproc = 1;
635         vp8_dbg_color_b_modes = flags;
636       }
637     } else if (arg_match(&arg, &pp_disp_mvs, argi)) {
638       unsigned int flags = arg_parse_int(&arg);
639       if (flags) {
640         postproc = 1;
641         vp8_dbg_display_mv = flags;
642       }
643     } else if (arg_match(&arg, &error_concealment, argi)) {
644       ec_enabled = 1;
645     } else if (arg_match(&arg, &continuearg, argi)) {
646       keep_going = 1;
647     }
648
649 #endif
650     else
651       argj++;
652   }
653
654   /* Check for unrecognized options */
655   for (argi = argv; *argi; argi++)
656     if (argi[0][0] == '-' && strlen(argi[0]) > 1)
657       die("Error: Unrecognized option %s\n", *argi);
658
659   /* Handle non-option arguments */
660   fn = argv[0];
661
662   if (!fn)
663     usage_exit();
664
665   /* Open file */
666   infile = strcmp(fn, "-") ? fopen(fn, "rb") : set_binary_mode(stdin);
667
668   if (!infile) {
669     fprintf(stderr, "Failed to open file '%s'", strcmp(fn, "-") ? fn : "stdin");
670     return EXIT_FAILURE;
671   }
672 #if CONFIG_OS_SUPPORT
673   /* Make sure we don't dump to the terminal, unless forced to with -o - */
674   if (!outfile_pattern && isatty(fileno(stdout)) && !do_md5 && !noblit) {
675     fprintf(stderr,
676             "Not dumping raw video to your terminal. Use '-o -' to "
677             "override.\n");
678     return EXIT_FAILURE;
679   }
680 #endif
681   input.vpx_input_ctx->file = infile;
682   if (file_is_ivf(input.vpx_input_ctx))
683     input.vpx_input_ctx->file_type = FILE_TYPE_IVF;
684 #if CONFIG_WEBM_IO
685   else if (file_is_webm(input.webm_ctx, input.vpx_input_ctx))
686     input.vpx_input_ctx->file_type = FILE_TYPE_WEBM;
687 #endif
688   else if (file_is_raw(input.vpx_input_ctx))
689     input.vpx_input_ctx->file_type = FILE_TYPE_RAW;
690   else {
691     fprintf(stderr, "Unrecognized input file type.\n");
692 #if !CONFIG_WEBM_IO
693     fprintf(stderr, "vpxdec was built without WebM container support.\n");
694 #endif
695     return EXIT_FAILURE;
696   }
697
698   outfile_pattern = outfile_pattern ? outfile_pattern : "-";
699   single_file = is_single_file(outfile_pattern);
700
701   if (!noblit && single_file) {
702     generate_filename(outfile_pattern, outfile_name, PATH_MAX,
703                       vpx_input_ctx.width, vpx_input_ctx.height, 0);
704     if (do_md5)
705       MD5Init(&md5_ctx);
706     else
707       outfile = open_outfile(outfile_name);
708   }
709
710   if (use_y4m && !noblit) {
711     if (!single_file) {
712       fprintf(stderr, "YUV4MPEG2 not supported with output patterns,"
713               " try --i420 or --yv12.\n");
714       return EXIT_FAILURE;
715     }
716
717 #if CONFIG_WEBM_IO
718     if (vpx_input_ctx.file_type == FILE_TYPE_WEBM) {
719       if (webm_guess_framerate(input.webm_ctx, input.vpx_input_ctx)) {
720         fprintf(stderr, "Failed to guess framerate -- error parsing "
721                 "webm file?\n");
722         return EXIT_FAILURE;
723       }
724     }
725 #endif
726   }
727
728   fourcc_interface = get_vpx_decoder_by_fourcc(vpx_input_ctx.fourcc);
729   if (interface && fourcc_interface && interface != fourcc_interface)
730     warn("Header indicates codec: %s\n", fourcc_interface->name);
731   else
732     interface = fourcc_interface;
733
734   if (!interface)
735     interface = get_vpx_decoder_by_index(0);
736
737   dec_flags = (postproc ? VPX_CODEC_USE_POSTPROC : 0) |
738               (ec_enabled ? VPX_CODEC_USE_ERROR_CONCEALMENT : 0);
739   if (vpx_codec_dec_init(&decoder, interface->codec_interface(),
740                          &cfg, dec_flags)) {
741     fprintf(stderr, "Failed to initialize decoder: %s\n",
742             vpx_codec_error(&decoder));
743     return EXIT_FAILURE;
744   }
745
746   if (!quiet)
747     fprintf(stderr, "%s\n", decoder.name);
748
749 #if CONFIG_VP8_DECODER
750
751   if (vp8_pp_cfg.post_proc_flag
752       && vpx_codec_control(&decoder, VP8_SET_POSTPROC, &vp8_pp_cfg)) {
753     fprintf(stderr, "Failed to configure postproc: %s\n", vpx_codec_error(&decoder));
754     return EXIT_FAILURE;
755   }
756
757   if (vp8_dbg_color_ref_frame
758       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_REF_FRAME, vp8_dbg_color_ref_frame)) {
759     fprintf(stderr, "Failed to configure reference block visualizer: %s\n", vpx_codec_error(&decoder));
760     return EXIT_FAILURE;
761   }
762
763   if (vp8_dbg_color_mb_modes
764       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_MB_MODES, vp8_dbg_color_mb_modes)) {
765     fprintf(stderr, "Failed to configure macro block visualizer: %s\n", vpx_codec_error(&decoder));
766     return EXIT_FAILURE;
767   }
768
769   if (vp8_dbg_color_b_modes
770       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_B_MODES, vp8_dbg_color_b_modes)) {
771     fprintf(stderr, "Failed to configure block visualizer: %s\n", vpx_codec_error(&decoder));
772     return EXIT_FAILURE;
773   }
774
775   if (vp8_dbg_display_mv
776       && vpx_codec_control(&decoder, VP8_SET_DBG_DISPLAY_MV, vp8_dbg_display_mv)) {
777     fprintf(stderr, "Failed to configure motion vector visualizer: %s\n", vpx_codec_error(&decoder));
778     return EXIT_FAILURE;
779   }
780 #endif
781
782
783   if (arg_skip)
784     fprintf(stderr, "Skipping first %d frames.\n", arg_skip);
785   while (arg_skip) {
786     if (read_frame(&input, &buf, &bytes_in_buffer, &buffer_size))
787       break;
788     arg_skip--;
789   }
790
791   if (num_external_frame_buffers > 0) {
792     ext_fb_list.num_external_frame_buffers = num_external_frame_buffers;
793     ext_fb_list.ext_fb = (struct ExternalFrameBuffer *)calloc(
794         num_external_frame_buffers, sizeof(*ext_fb_list.ext_fb));
795     if (vpx_codec_set_frame_buffer_functions(
796             &decoder, get_vp9_frame_buffer, release_vp9_frame_buffer,
797             &ext_fb_list)) {
798       fprintf(stderr, "Failed to configure external frame buffers: %s\n",
799               vpx_codec_error(&decoder));
800       return EXIT_FAILURE;
801     }
802   }
803
804   frame_avail = 1;
805   got_data = 0;
806
807   /* Decode file */
808   while (frame_avail || got_data) {
809     vpx_codec_iter_t  iter = NULL;
810     vpx_image_t    *img;
811     struct vpx_usec_timer timer;
812     int                   corrupted;
813
814     frame_avail = 0;
815     if (!stop_after || frame_in < stop_after) {
816       if (!read_frame(&input, &buf, &bytes_in_buffer, &buffer_size)) {
817         frame_avail = 1;
818         frame_in++;
819
820         vpx_usec_timer_start(&timer);
821
822         if (vpx_codec_decode(&decoder, buf, (unsigned int)bytes_in_buffer,
823                              NULL, 0)) {
824           const char *detail = vpx_codec_error_detail(&decoder);
825           warn("Failed to decode frame %d: %s",
826                frame_in, vpx_codec_error(&decoder));
827
828           if (detail)
829             warn("Additional information: %s", detail);
830           if (!keep_going)
831             goto fail;
832         }
833
834         vpx_usec_timer_mark(&timer);
835         dx_time += vpx_usec_timer_elapsed(&timer);
836       }
837     }
838
839     vpx_usec_timer_start(&timer);
840
841     got_data = 0;
842     if ((img = vpx_codec_get_frame(&decoder, &iter))) {
843       ++frame_out;
844       got_data = 1;
845     }
846
847     vpx_usec_timer_mark(&timer);
848     dx_time += (unsigned int)vpx_usec_timer_elapsed(&timer);
849
850     if (vpx_codec_control(&decoder, VP8D_GET_FRAME_CORRUPTED, &corrupted)) {
851       warn("Failed VP8_GET_FRAME_CORRUPTED: %s", vpx_codec_error(&decoder));
852       goto fail;
853     }
854     frames_corrupted += corrupted;
855
856     if (progress)
857       show_progress(frame_in, frame_out, dx_time);
858
859     if (!noblit && img) {
860       const int PLANES_YUV[] = {VPX_PLANE_Y, VPX_PLANE_U, VPX_PLANE_V};
861       const int PLANES_YVU[] = {VPX_PLANE_Y, VPX_PLANE_V, VPX_PLANE_U};
862       const int *planes = flipuv ? PLANES_YVU : PLANES_YUV;
863
864       if (do_scale) {
865         if (frame_out == 1) {
866           // If the output frames are to be scaled to a fixed display size then
867           // use the width and height specified in the container. If either of
868           // these is set to 0, use the display size set in the first frame
869           // header. If that is unavailable, use the raw decoded size of the
870           // first decoded frame.
871           int display_width = vpx_input_ctx.width;
872           int display_height = vpx_input_ctx.height;
873           if (!display_width || !display_height) {
874             int display_size[2];
875             if (vpx_codec_control(&decoder, VP9D_GET_DISPLAY_SIZE,
876                                   display_size)) {
877               // As last resort use size of first frame as display size.
878               display_width = img->d_w;
879               display_height = img->d_h;
880             } else {
881               display_width = display_size[0];
882               display_height = display_size[1];
883             }
884           }
885           scaled_img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420, display_width,
886                                      display_height, 16);
887           scaled_img->bit_depth = img->bit_depth;
888         }
889
890         if (img->d_w != scaled_img->d_w || img->d_h != scaled_img->d_h) {
891 #if CONFIG_LIBYUV
892           vpx_image_scale(img, scaled_img, kFilterBox);
893           img = scaled_img;
894 #else
895           fprintf(stderr, "Failed  to scale output frame: %s.\n"
896                   "Scaling is disabled in this configuration. "
897                   "To enable scaling, configure with --enable-libyuv\n",
898                   vpx_codec_error(&decoder));
899           return EXIT_FAILURE;
900 #endif
901         }
902       }
903
904       if (single_file) {
905         if (use_y4m) {
906           char buf[Y4M_BUFFER_SIZE] = {0};
907           size_t len = 0;
908           if (frame_out == 1) {
909             // Y4M file header
910             len = y4m_write_file_header(buf, sizeof(buf),
911                                         vpx_input_ctx.width,
912                                         vpx_input_ctx.height,
913                                         &vpx_input_ctx.framerate,
914                                         img->fmt, img->bit_depth);
915             if (do_md5) {
916               MD5Update(&md5_ctx, (md5byte *)buf, (unsigned int)len);
917             } else {
918               fputs(buf, outfile);
919             }
920           }
921
922           // Y4M frame header
923           len = y4m_write_frame_header(buf, sizeof(buf));
924           if (do_md5) {
925             MD5Update(&md5_ctx, (md5byte *)buf, (unsigned int)len);
926           } else {
927             fputs(buf, outfile);
928           }
929         } else {
930           if (frame_out == 1) {
931             // Check if --yv12 or --i420 options are consistent with the
932             // bit-stream decoded
933             if (opt_i420) {
934               if (img->fmt != VPX_IMG_FMT_I420 &&
935                   img->fmt != VPX_IMG_FMT_I42016) {
936                 fprintf(stderr, "Cannot produce i420 output for bit-stream.\n");
937                 goto fail;
938               }
939             }
940             if (opt_yv12) {
941               if ((img->fmt != VPX_IMG_FMT_I420 &&
942                    img->fmt != VPX_IMG_FMT_YV12) || img->bit_depth != 8) {
943                 fprintf(stderr, "Cannot produce yv12 output for bit-stream.\n");
944                 goto fail;
945               }
946             }
947           }
948         }
949
950         if (do_md5) {
951           update_image_md5(img, planes, &md5_ctx);
952         } else {
953           write_image_file(img, planes, outfile);
954         }
955       } else {
956         generate_filename(outfile_pattern, outfile_name, PATH_MAX,
957                           img->d_w, img->d_h, frame_in);
958         if (do_md5) {
959           MD5Init(&md5_ctx);
960           update_image_md5(img, planes, &md5_ctx);
961           MD5Final(md5_digest, &md5_ctx);
962           print_md5(md5_digest, outfile_name);
963         } else {
964           outfile = open_outfile(outfile_name);
965           write_image_file(img, planes, outfile);
966           fclose(outfile);
967         }
968       }
969     }
970
971     if (stop_after && frame_in >= stop_after)
972       break;
973   }
974
975   if (summary || progress) {
976     show_progress(frame_in, frame_out, dx_time);
977     fprintf(stderr, "\n");
978   }
979
980   if (frames_corrupted)
981     fprintf(stderr, "WARNING: %d frames corrupted.\n", frames_corrupted);
982
983 fail:
984
985   if (vpx_codec_destroy(&decoder)) {
986     fprintf(stderr, "Failed to destroy decoder: %s\n",
987             vpx_codec_error(&decoder));
988     return EXIT_FAILURE;
989   }
990
991   if (!noblit && single_file) {
992     if (do_md5) {
993       MD5Final(md5_digest, &md5_ctx);
994       print_md5(md5_digest, outfile_name);
995     } else {
996       fclose(outfile);
997     }
998   }
999
1000 #if CONFIG_WEBM_IO
1001   if (input.vpx_input_ctx->file_type == FILE_TYPE_WEBM)
1002     webm_free(input.webm_ctx);
1003 #endif
1004
1005   if (input.vpx_input_ctx->file_type != FILE_TYPE_WEBM)
1006     free(buf);
1007
1008   if (scaled_img) vpx_img_free(scaled_img);
1009
1010   for (i = 0; i < ext_fb_list.num_external_frame_buffers; ++i) {
1011     free(ext_fb_list.ext_fb[i].data);
1012   }
1013   free(ext_fb_list.ext_fb);
1014
1015   fclose(infile);
1016   free(argv);
1017
1018   return frames_corrupted ? EXIT_FAILURE : EXIT_SUCCESS;
1019 }
1020
1021 int main(int argc, const char **argv_) {
1022   unsigned int loops = 1, i;
1023   char **argv, **argi, **argj;
1024   struct arg arg;
1025   int error = 0;
1026
1027   argv = argv_dup(argc - 1, argv_ + 1);
1028   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1029     memset(&arg, 0, sizeof(arg));
1030     arg.argv_step = 1;
1031
1032     if (arg_match(&arg, &looparg, argi)) {
1033       loops = arg_parse_uint(&arg);
1034       break;
1035     }
1036   }
1037   free(argv);
1038   for (i = 0; !error && i < loops; i++)
1039     error = main_loop(argc, argv_);
1040   return error;
1041 }