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