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