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