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