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