]> granicus.if.org Git - libvpx/blob - vpxdec.c
Merge "Remove unused function in vp9_encodeframe"
[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 #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
79 static const arg_def_t md5arg = ARG_DEF(NULL, "md5", 0,
80                                         "Compute the MD5 sum of the decoded frame");
81
82 static const arg_def_t *all_args[] = {
83   &codecarg, &use_yv12, &use_i420, &flipuvarg, &noblitarg,
84   &progressarg, &limitarg, &skiparg, &postprocarg, &summaryarg, &outputfile,
85   &threadsarg, &verbosearg, &scalearg,
86   &md5arg,
87   &error_concealment,
88   NULL
89 };
90
91 #if CONFIG_VP8_DECODER
92 static const arg_def_t addnoise_level = ARG_DEF(NULL, "noise-level", 1,
93                                                 "Enable VP8 postproc add noise");
94 static const arg_def_t deblock = ARG_DEF(NULL, "deblock", 0,
95                                          "Enable VP8 deblocking");
96 static const arg_def_t demacroblock_level = ARG_DEF(NULL, "demacroblock-level", 1,
97                                                     "Enable VP8 demacroblocking, w/ level");
98 static const arg_def_t pp_debug_info = ARG_DEF(NULL, "pp-debug-info", 1,
99                                                "Enable VP8 visible debug info");
100 static const arg_def_t pp_disp_ref_frame = ARG_DEF(NULL, "pp-dbg-ref-frame", 1,
101                                                    "Display only selected reference frame per macro block");
102 static const arg_def_t pp_disp_mb_modes = ARG_DEF(NULL, "pp-dbg-mb-modes", 1,
103                                                   "Display only selected macro block modes");
104 static const arg_def_t pp_disp_b_modes = ARG_DEF(NULL, "pp-dbg-b-modes", 1,
105                                                  "Display only selected block modes");
106 static const arg_def_t pp_disp_mvs = ARG_DEF(NULL, "pp-dbg-mvs", 1,
107                                              "Draw only selected motion vectors");
108 static const arg_def_t mfqe = ARG_DEF(NULL, "mfqe", 0,
109                                       "Enable multiframe quality enhancement");
110
111 static const arg_def_t *vp8_pp_args[] = {
112   &addnoise_level, &deblock, &demacroblock_level, &pp_debug_info,
113   &pp_disp_ref_frame, &pp_disp_mb_modes, &pp_disp_b_modes, &pp_disp_mvs, &mfqe,
114   NULL
115 };
116 #endif
117
118 static int vpx_image_scale(vpx_image_t *src, vpx_image_t *dst,
119                            FilterMode mode) {
120   assert(src->fmt == VPX_IMG_FMT_I420);
121   assert(dst->fmt == VPX_IMG_FMT_I420);
122   return I420Scale(src->planes[VPX_PLANE_Y], src->stride[VPX_PLANE_Y],
123                    src->planes[VPX_PLANE_U], src->stride[VPX_PLANE_U],
124                    src->planes[VPX_PLANE_V], src->stride[VPX_PLANE_V],
125                    src->d_w, src->d_h,
126                    dst->planes[VPX_PLANE_Y], dst->stride[VPX_PLANE_Y],
127                    dst->planes[VPX_PLANE_U], dst->stride[VPX_PLANE_U],
128                    dst->planes[VPX_PLANE_V], dst->stride[VPX_PLANE_V],
129                    dst->d_w, dst->d_h,
130                    mode);
131 }
132
133 void usage_exit() {
134   int i;
135
136   fprintf(stderr, "Usage: %s <options> filename\n\n"
137           "Options:\n", exec_name);
138   arg_show_usage(stderr, all_args);
139 #if CONFIG_VP8_DECODER
140   fprintf(stderr, "\nVP8 Postprocessing Options:\n");
141   arg_show_usage(stderr, vp8_pp_args);
142 #endif
143   fprintf(stderr,
144           "\nOutput File Patterns:\n\n"
145           "  The -o argument specifies the name of the file(s) to "
146           "write to. If the\n  argument does not include any escape "
147           "characters, the output will be\n  written to a single file. "
148           "Otherwise, the filename will be calculated by\n  expanding "
149           "the following escape characters:\n");
150   fprintf(stderr,
151           "\n\t%%w   - Frame width"
152           "\n\t%%h   - Frame height"
153           "\n\t%%<n> - Frame number, zero padded to <n> places (1..9)"
154           "\n\n  Pattern arguments are only supported in conjunction "
155           "with the --yv12 and\n  --i420 options. If the -o option is "
156           "not specified, the output will be\n  directed to stdout.\n"
157          );
158   fprintf(stderr, "\nIncluded decoders:\n\n");
159
160   for (i = 0; i < get_vpx_decoder_count(); ++i) {
161     const VpxInterface *const decoder = get_vpx_decoder_by_index(i);
162     fprintf(stderr, "    %-6s - %s\n",
163             decoder->name, vpx_codec_iface_name(decoder->interface()));
164   }
165
166   exit(EXIT_FAILURE);
167 }
168
169 static int raw_read_frame(FILE *infile, uint8_t **buffer,
170                           size_t *bytes_read, size_t *buffer_size) {
171   char raw_hdr[RAW_FRAME_HDR_SZ];
172   size_t frame_size = 0;
173
174   if (fread(raw_hdr, RAW_FRAME_HDR_SZ, 1, infile) != 1) {
175     if (!feof(infile))
176       warn("Failed to read RAW frame size\n");
177   } else {
178     const size_t kCorruptFrameThreshold = 256 * 1024 * 1024;
179     const size_t kFrameTooSmallThreshold = 256 * 1024;
180     frame_size = mem_get_le32(raw_hdr);
181
182     if (frame_size > kCorruptFrameThreshold) {
183       warn("Read invalid frame size (%u)\n", (unsigned int)frame_size);
184       frame_size = 0;
185     }
186
187     if (frame_size < kFrameTooSmallThreshold) {
188       warn("Warning: Read invalid frame size (%u) - not a raw file?\n",
189            (unsigned int)frame_size);
190     }
191
192     if (frame_size > *buffer_size) {
193       uint8_t *new_buf = realloc(*buffer, 2 * frame_size);
194       if (new_buf) {
195         *buffer = new_buf;
196         *buffer_size = 2 * frame_size;
197       } else {
198         warn("Failed to allocate compressed data buffer\n");
199         frame_size = 0;
200       }
201     }
202   }
203
204   if (!feof(infile)) {
205     if (fread(*buffer, 1, frame_size, infile) != frame_size) {
206       warn("Failed to read full frame\n");
207       return 1;
208     }
209     *bytes_read = frame_size;
210   }
211
212   return 0;
213 }
214
215 static int read_frame(struct VpxDecInputContext *input, uint8_t **buf,
216                       size_t *bytes_in_buffer, size_t *buffer_size) {
217   switch (input->vpx_input_ctx->file_type) {
218     case FILE_TYPE_WEBM:
219       return webm_read_frame(input->webm_ctx,
220                              buf, bytes_in_buffer, buffer_size);
221     case FILE_TYPE_RAW:
222       return raw_read_frame(input->vpx_input_ctx->file,
223                             buf, bytes_in_buffer, buffer_size);
224     case FILE_TYPE_IVF:
225       return ivf_read_frame(input->vpx_input_ctx->file,
226                             buf, bytes_in_buffer, buffer_size);
227     default:
228       return 1;
229   }
230 }
231
232 static int get_image_plane_width(int plane, const vpx_image_t *img) {
233   return (plane > 0 && img->x_chroma_shift > 0) ?
234              (img->d_w + 1) >> img->x_chroma_shift :
235              img->d_w;
236 }
237
238 static int get_image_plane_height(int plane, const vpx_image_t *img) {
239   return (plane > 0 &&  img->y_chroma_shift > 0) ?
240              (img->d_h + 1) >> img->y_chroma_shift :
241              img->d_h;
242 }
243
244 static void update_image_md5(const vpx_image_t *img, const int planes[3],
245                              MD5Context *md5) {
246   int i, y;
247
248   for (i = 0; i < 3; ++i) {
249     const int plane = planes[i];
250     const unsigned char *buf = img->planes[plane];
251     const int stride = img->stride[plane];
252     const int w = get_image_plane_width(plane, img);
253     const int h = get_image_plane_height(plane, img);
254
255     for (y = 0; y < h; ++y) {
256       MD5Update(md5, buf, w);
257       buf += stride;
258     }
259   }
260 }
261
262 static void write_image_file(const vpx_image_t *img, const int planes[3],
263                              FILE *file) {
264   int i, y;
265
266   for (i = 0; i < 3; ++i) {
267     const int plane = planes[i];
268     const unsigned char *buf = img->planes[plane];
269     const int stride = img->stride[plane];
270     const int w = get_image_plane_width(plane, img);
271     const int h = get_image_plane_height(plane, img);
272
273     for (y = 0; y < h; ++y) {
274       fwrite(buf, 1, w, file);
275       buf += stride;
276     }
277   }
278 }
279
280 int file_is_raw(struct VpxInputContext *input) {
281   uint8_t buf[32];
282   int is_raw = 0;
283   vpx_codec_stream_info_t si;
284
285   si.sz = sizeof(si);
286
287   if (fread(buf, 1, 32, input->file) == 32) {
288     int i;
289
290     if (mem_get_le32(buf) < 256 * 1024 * 1024) {
291       for (i = 0; i < get_vpx_decoder_count(); ++i) {
292         const VpxInterface *const decoder = get_vpx_decoder_by_index(i);
293         if (!vpx_codec_peek_stream_info(decoder->interface(),
294                                         buf + 4, 32 - 4, &si)) {
295           is_raw = 1;
296           input->fourcc = decoder->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 static int is_single_file(const char *outfile_pattern) {
397   const char *p = outfile_pattern;
398
399   do {
400     p = strchr(p, '%');
401     if (p && p[1] >= '1' && p[1] <= '9')
402       return 0;  // pattern contains sequence number, so it's not unique
403     if (p)
404       p++;
405   } while (p);
406
407   return 1;
408 }
409
410 static void print_md5(unsigned char digest[16], const char *filename) {
411   int i;
412
413   for (i = 0; i < 16; ++i)
414     printf("%02x", digest[i]);
415   printf("  %s\n", filename);
416 }
417
418 static FILE *open_outfile(const char *name) {
419   if (strcmp("-", name) == 0) {
420     set_binary_mode(stdout);
421     return stdout;
422   } else {
423     FILE *file = fopen(name, "wb");
424     if (!file)
425       fatal("Failed to output file %s", name);
426     return file;
427   }
428 }
429
430 int main_loop(int argc, const char **argv_) {
431   vpx_codec_ctx_t       decoder;
432   char                  *fn = NULL;
433   uint8_t               *buf = NULL;
434   size_t                 bytes_in_buffer = 0, buffer_size = 0;
435   FILE                  *infile;
436   int                    frame_in = 0, frame_out = 0, flipuv = 0, noblit = 0;
437   int                    do_md5 = 0, progress = 0;
438   int                    stop_after = 0, postproc = 0, summary = 0, quiet = 1;
439   int                    arg_skip = 0;
440   int                    ec_enabled = 0;
441   const VpxInterface *interface = NULL;
442   const VpxInterface *fourcc_interface = NULL;
443   unsigned long          dx_time = 0;
444   struct arg               arg;
445   char                   **argv, **argi, **argj;
446
447   int                     single_file;
448   int                     use_y4m = 1;
449   vpx_codec_dec_cfg_t     cfg = {0};
450 #if CONFIG_VP8_DECODER
451   vp8_postproc_cfg_t      vp8_pp_cfg = {0};
452   int                     vp8_dbg_color_ref_frame = 0;
453   int                     vp8_dbg_color_mb_modes = 0;
454   int                     vp8_dbg_color_b_modes = 0;
455   int                     vp8_dbg_display_mv = 0;
456 #endif
457   int                     frames_corrupted = 0;
458   int                     dec_flags = 0;
459   int                     do_scale = 0;
460   vpx_image_t             *scaled_img = NULL;
461   int                     frame_avail, got_data;
462
463   const char *outfile_pattern = NULL;
464   char outfile_name[PATH_MAX] = {0};
465   FILE *outfile = NULL;
466
467   MD5Context md5_ctx;
468   unsigned char md5_digest[16];
469
470   struct VpxDecInputContext input = {0};
471   struct VpxInputContext vpx_input_ctx = {0};
472   struct WebmInputContext webm_ctx = {0};
473   input.vpx_input_ctx = &vpx_input_ctx;
474   input.webm_ctx = &webm_ctx;
475
476   /* Parse command line */
477   exec_name = argv_[0];
478   argv = argv_dup(argc - 1, argv_ + 1);
479
480   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
481     memset(&arg, 0, sizeof(arg));
482     arg.argv_step = 1;
483
484     if (arg_match(&arg, &codecarg, argi)) {
485       interface = get_vpx_decoder_by_name(arg.val);
486       if (!interface)
487         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
488     } else if (arg_match(&arg, &looparg, argi)) {
489       // no-op
490     } else if (arg_match(&arg, &outputfile, argi))
491       outfile_pattern = arg.val;
492     else if (arg_match(&arg, &use_yv12, argi)) {
493       use_y4m = 0;
494       flipuv = 1;
495     } else if (arg_match(&arg, &use_i420, argi)) {
496       use_y4m = 0;
497       flipuv = 0;
498     } else if (arg_match(&arg, &flipuvarg, argi))
499       flipuv = 1;
500     else if (arg_match(&arg, &noblitarg, argi))
501       noblit = 1;
502     else if (arg_match(&arg, &progressarg, argi))
503       progress = 1;
504     else if (arg_match(&arg, &limitarg, argi))
505       stop_after = arg_parse_uint(&arg);
506     else if (arg_match(&arg, &skiparg, argi))
507       arg_skip = arg_parse_uint(&arg);
508     else if (arg_match(&arg, &postprocarg, argi))
509       postproc = 1;
510     else if (arg_match(&arg, &md5arg, argi))
511       do_md5 = 1;
512     else if (arg_match(&arg, &summaryarg, argi))
513       summary = 1;
514     else if (arg_match(&arg, &threadsarg, argi))
515       cfg.threads = arg_parse_uint(&arg);
516     else if (arg_match(&arg, &verbosearg, argi))
517       quiet = 0;
518     else if (arg_match(&arg, &scalearg, argi))
519       do_scale = 1;
520
521 #if CONFIG_VP8_DECODER
522     else if (arg_match(&arg, &addnoise_level, argi)) {
523       postproc = 1;
524       vp8_pp_cfg.post_proc_flag |= VP8_ADDNOISE;
525       vp8_pp_cfg.noise_level = arg_parse_uint(&arg);
526     } else if (arg_match(&arg, &demacroblock_level, argi)) {
527       postproc = 1;
528       vp8_pp_cfg.post_proc_flag |= VP8_DEMACROBLOCK;
529       vp8_pp_cfg.deblocking_level = arg_parse_uint(&arg);
530     } else if (arg_match(&arg, &deblock, argi)) {
531       postproc = 1;
532       vp8_pp_cfg.post_proc_flag |= VP8_DEBLOCK;
533     } else if (arg_match(&arg, &mfqe, argi)) {
534       postproc = 1;
535       vp8_pp_cfg.post_proc_flag |= VP8_MFQE;
536     } else if (arg_match(&arg, &pp_debug_info, argi)) {
537       unsigned int level = arg_parse_uint(&arg);
538
539       postproc = 1;
540       vp8_pp_cfg.post_proc_flag &= ~0x7;
541
542       if (level)
543         vp8_pp_cfg.post_proc_flag |= level;
544     } else if (arg_match(&arg, &pp_disp_ref_frame, argi)) {
545       unsigned int flags = arg_parse_int(&arg);
546       if (flags) {
547         postproc = 1;
548         vp8_dbg_color_ref_frame = flags;
549       }
550     } else if (arg_match(&arg, &pp_disp_mb_modes, argi)) {
551       unsigned int flags = arg_parse_int(&arg);
552       if (flags) {
553         postproc = 1;
554         vp8_dbg_color_mb_modes = flags;
555       }
556     } else if (arg_match(&arg, &pp_disp_b_modes, argi)) {
557       unsigned int flags = arg_parse_int(&arg);
558       if (flags) {
559         postproc = 1;
560         vp8_dbg_color_b_modes = flags;
561       }
562     } else if (arg_match(&arg, &pp_disp_mvs, argi)) {
563       unsigned int flags = arg_parse_int(&arg);
564       if (flags) {
565         postproc = 1;
566         vp8_dbg_display_mv = flags;
567       }
568     } else if (arg_match(&arg, &error_concealment, argi)) {
569       ec_enabled = 1;
570     }
571
572 #endif
573     else
574       argj++;
575   }
576
577   /* Check for unrecognized options */
578   for (argi = argv; *argi; argi++)
579     if (argi[0][0] == '-' && strlen(argi[0]) > 1)
580       die("Error: Unrecognized option %s\n", *argi);
581
582   /* Handle non-option arguments */
583   fn = argv[0];
584
585   if (!fn)
586     usage_exit();
587
588   /* Open file */
589   infile = strcmp(fn, "-") ? fopen(fn, "rb") : set_binary_mode(stdin);
590
591   if (!infile) {
592     fprintf(stderr, "Failed to open file '%s'", strcmp(fn, "-") ? fn : "stdin");
593     return EXIT_FAILURE;
594   }
595 #if CONFIG_OS_SUPPORT
596   /* Make sure we don't dump to the terminal, unless forced to with -o - */
597   if (!outfile_pattern && isatty(fileno(stdout)) && !do_md5 && !noblit) {
598     fprintf(stderr,
599             "Not dumping raw video to your terminal. Use '-o -' to "
600             "override.\n");
601     return EXIT_FAILURE;
602   }
603 #endif
604   input.vpx_input_ctx->file = infile;
605   if (file_is_ivf(input.vpx_input_ctx))
606     input.vpx_input_ctx->file_type = FILE_TYPE_IVF;
607   else if (file_is_webm(input.webm_ctx, input.vpx_input_ctx))
608     input.vpx_input_ctx->file_type = FILE_TYPE_WEBM;
609   else if (file_is_raw(input.vpx_input_ctx))
610     input.vpx_input_ctx->file_type = FILE_TYPE_RAW;
611   else {
612     fprintf(stderr, "Unrecognized input file type.\n");
613     return EXIT_FAILURE;
614   }
615
616   outfile_pattern = outfile_pattern ? outfile_pattern : "-";
617   single_file = is_single_file(outfile_pattern);
618
619   if (!noblit && single_file) {
620     generate_filename(outfile_pattern, outfile_name, PATH_MAX,
621                       vpx_input_ctx.width, vpx_input_ctx.height, 0);
622     if (do_md5)
623       MD5Init(&md5_ctx);
624     else
625       outfile = open_outfile(outfile_name);
626   }
627
628   if (use_y4m && !noblit) {
629     if (!single_file) {
630       fprintf(stderr, "YUV4MPEG2 not supported with output patterns,"
631               " try --i420 or --yv12.\n");
632       return EXIT_FAILURE;
633     }
634
635     if (vpx_input_ctx.file_type == FILE_TYPE_WEBM) {
636       if (webm_guess_framerate(input.webm_ctx, input.vpx_input_ctx)) {
637         fprintf(stderr, "Failed to guess framerate -- error parsing "
638                 "webm file?\n");
639         return EXIT_FAILURE;
640       }
641     }
642   }
643
644   fourcc_interface = get_vpx_decoder_by_fourcc(vpx_input_ctx.fourcc);
645   if (interface && fourcc_interface && interface != fourcc_interface)
646     warn("Header indicates codec: %s\n", fourcc_interface->name);
647   else
648     interface = fourcc_interface;
649
650   if (!interface)
651     interface = get_vpx_decoder_by_index(0);
652
653   dec_flags = (postproc ? VPX_CODEC_USE_POSTPROC : 0) |
654               (ec_enabled ? VPX_CODEC_USE_ERROR_CONCEALMENT : 0);
655   if (vpx_codec_dec_init(&decoder, interface->interface(), &cfg, dec_flags)) {
656     fprintf(stderr, "Failed to initialize decoder: %s\n",
657             vpx_codec_error(&decoder));
658     return EXIT_FAILURE;
659   }
660
661   if (!quiet)
662     fprintf(stderr, "%s\n", decoder.name);
663
664 #if CONFIG_VP8_DECODER
665
666   if (vp8_pp_cfg.post_proc_flag
667       && vpx_codec_control(&decoder, VP8_SET_POSTPROC, &vp8_pp_cfg)) {
668     fprintf(stderr, "Failed to configure postproc: %s\n", vpx_codec_error(&decoder));
669     return EXIT_FAILURE;
670   }
671
672   if (vp8_dbg_color_ref_frame
673       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_REF_FRAME, vp8_dbg_color_ref_frame)) {
674     fprintf(stderr, "Failed to configure reference block visualizer: %s\n", vpx_codec_error(&decoder));
675     return EXIT_FAILURE;
676   }
677
678   if (vp8_dbg_color_mb_modes
679       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_MB_MODES, vp8_dbg_color_mb_modes)) {
680     fprintf(stderr, "Failed to configure macro block visualizer: %s\n", vpx_codec_error(&decoder));
681     return EXIT_FAILURE;
682   }
683
684   if (vp8_dbg_color_b_modes
685       && vpx_codec_control(&decoder, VP8_SET_DBG_COLOR_B_MODES, vp8_dbg_color_b_modes)) {
686     fprintf(stderr, "Failed to configure block visualizer: %s\n", vpx_codec_error(&decoder));
687     return EXIT_FAILURE;
688   }
689
690   if (vp8_dbg_display_mv
691       && vpx_codec_control(&decoder, VP8_SET_DBG_DISPLAY_MV, vp8_dbg_display_mv)) {
692     fprintf(stderr, "Failed to configure motion vector visualizer: %s\n", vpx_codec_error(&decoder));
693     return EXIT_FAILURE;
694   }
695 #endif
696
697
698   if (arg_skip)
699     fprintf(stderr, "Skipping first %d frames.\n", arg_skip);
700   while (arg_skip) {
701     if (read_frame(&input, &buf, &bytes_in_buffer, &buffer_size))
702       break;
703     arg_skip--;
704   }
705
706   frame_avail = 1;
707   got_data = 0;
708
709   /* Decode file */
710   while (frame_avail || got_data) {
711     vpx_codec_iter_t  iter = NULL;
712     vpx_image_t    *img;
713     struct vpx_usec_timer timer;
714     int                   corrupted;
715
716     frame_avail = 0;
717     if (!stop_after || frame_in < stop_after) {
718       if (!read_frame(&input, &buf, &bytes_in_buffer, &buffer_size)) {
719         frame_avail = 1;
720         frame_in++;
721
722         vpx_usec_timer_start(&timer);
723
724         if (vpx_codec_decode(&decoder, buf, bytes_in_buffer, NULL, 0)) {
725           const char *detail = vpx_codec_error_detail(&decoder);
726           warn("Failed to decode frame %d: %s",
727                frame_in, vpx_codec_error(&decoder));
728
729           if (detail)
730             warn("Additional information: %s", detail);
731           goto fail;
732         }
733
734         vpx_usec_timer_mark(&timer);
735         dx_time += (unsigned int)vpx_usec_timer_elapsed(&timer);
736       }
737     }
738
739     vpx_usec_timer_start(&timer);
740
741     got_data = 0;
742     if ((img = vpx_codec_get_frame(&decoder, &iter))) {
743       ++frame_out;
744       got_data = 1;
745     }
746
747     vpx_usec_timer_mark(&timer);
748     dx_time += (unsigned int)vpx_usec_timer_elapsed(&timer);
749
750     if (vpx_codec_control(&decoder, VP8D_GET_FRAME_CORRUPTED, &corrupted)) {
751       warn("Failed VP8_GET_FRAME_CORRUPTED: %s", vpx_codec_error(&decoder));
752       goto fail;
753     }
754     frames_corrupted += corrupted;
755
756     if (progress)
757       show_progress(frame_in, frame_out, dx_time);
758
759     if (!noblit && img) {
760       const int PLANES_YUV[] = {VPX_PLANE_Y, VPX_PLANE_U, VPX_PLANE_V};
761       const int PLANES_YVU[] = {VPX_PLANE_Y, VPX_PLANE_V, VPX_PLANE_U};
762       const int *planes = flipuv ? PLANES_YVU : PLANES_YUV;
763
764       if (do_scale) {
765         if (frame_out == 1) {
766           // If the output frames are to be scaled to a fixed display size then
767           // use the width and height specified in the container. If either of
768           // these is set to 0, use the display size set in the first frame
769           // header. If that is unavailable, use the raw decoded size of the
770           // first decoded frame.
771           int display_width = vpx_input_ctx.width;
772           int display_height = vpx_input_ctx.height;
773           if (!display_width || !display_height) {
774             int display_size[2];
775             if (vpx_codec_control(&decoder, VP9D_GET_DISPLAY_SIZE,
776                                   display_size)) {
777               // As last resort use size of first frame as display size.
778               display_width = img->d_w;
779               display_height = img->d_h;
780             } else {
781               display_width = display_size[0];
782               display_height = display_size[1];
783             }
784           }
785           scaled_img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420, display_width,
786                                      display_height, 16);
787         }
788
789         if (img->d_w != scaled_img->d_w || img->d_h != scaled_img->d_h) {
790           vpx_image_scale(img, scaled_img, kFilterBox);
791           img = scaled_img;
792         }
793       }
794
795       if (single_file) {
796         if (use_y4m) {
797           char buf[Y4M_BUFFER_SIZE] = {0};
798           size_t len = 0;
799           if (frame_out == 1) {
800             // Y4M file header
801             len = y4m_write_file_header(buf, sizeof(buf),
802                                         vpx_input_ctx.width,
803                                         vpx_input_ctx.height,
804                                         &vpx_input_ctx.framerate, img->fmt);
805             if (do_md5) {
806               MD5Update(&md5_ctx, (md5byte *)buf, len);
807             } else {
808               fputs(buf, outfile);
809             }
810           }
811
812           // Y4M frame header
813           len = y4m_write_frame_header(buf, sizeof(buf));
814           if (do_md5) {
815             MD5Update(&md5_ctx, (md5byte *)buf, len);
816           } else {
817             fputs(buf, outfile);
818           }
819         }
820
821         if (do_md5) {
822           update_image_md5(img, planes, &md5_ctx);
823         } else {
824           write_image_file(img, planes, outfile);
825         }
826       } else {
827         generate_filename(outfile_pattern, outfile_name, PATH_MAX,
828                           img->d_w, img->d_h, frame_in);
829         if (do_md5) {
830           MD5Init(&md5_ctx);
831           update_image_md5(img, planes, &md5_ctx);
832           MD5Final(md5_digest, &md5_ctx);
833           print_md5(md5_digest, outfile_name);
834         } else {
835           outfile = open_outfile(outfile_name);
836           write_image_file(img, planes, outfile);
837           fclose(outfile);
838         }
839       }
840     }
841
842     if (stop_after && frame_in >= stop_after)
843       break;
844   }
845
846   if (summary || progress) {
847     show_progress(frame_in, frame_out, dx_time);
848     fprintf(stderr, "\n");
849   }
850
851   if (frames_corrupted)
852     fprintf(stderr, "WARNING: %d frames corrupted.\n", frames_corrupted);
853
854 fail:
855
856   if (vpx_codec_destroy(&decoder)) {
857     fprintf(stderr, "Failed to destroy decoder: %s\n",
858             vpx_codec_error(&decoder));
859     return EXIT_FAILURE;
860   }
861
862   if (!noblit && single_file) {
863     if (do_md5) {
864       MD5Final(md5_digest, &md5_ctx);
865       print_md5(md5_digest, outfile_name);
866     } else {
867       fclose(outfile);
868     }
869   }
870
871   if (input.vpx_input_ctx->file_type == FILE_TYPE_WEBM)
872     webm_free(input.webm_ctx);
873   else
874     free(buf);
875
876   if (scaled_img) vpx_img_free(scaled_img);
877
878   fclose(infile);
879   free(argv);
880
881   return frames_corrupted ? EXIT_FAILURE : EXIT_SUCCESS;
882 }
883
884 int main(int argc, const char **argv_) {
885   unsigned int loops = 1, i;
886   char **argv, **argi, **argj;
887   struct arg arg;
888   int error = 0;
889
890   argv = argv_dup(argc - 1, argv_ + 1);
891   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
892     memset(&arg, 0, sizeof(arg));
893     arg.argv_step = 1;
894
895     if (arg_match(&arg, &looparg, argi)) {
896       loops = arg_parse_uint(&arg);
897       break;
898     }
899   }
900   free(argv);
901   for (i = 0; !error && i < loops; i++)
902     error = main_loop(argc, argv_);
903   return error;
904 }