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