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