Rough merge of master into experimental
[platform/upstream/libvpx.git] / vpxenc.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 "vpx_config.h"
12
13 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
15 #else
16 #define USE_POSIX_MMAP 1
17 #endif
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <assert.h>
25 #include "vpx/vpx_encoder.h"
26 #include "vpx/vpx_decoder.h"
27 #if USE_POSIX_MMAP
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/mman.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #endif
34
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
37 #endif
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
40 #endif
41
42 #include "vpx_ports/mem_ops.h"
43 #include "vpx_ports/vpx_timer.h"
44 #include "tools_common.h"
45 #include "y4minput.h"
46 #include "libmkv/EbmlWriter.h"
47 #include "libmkv/EbmlIDs.h"
48
49 /* Need special handling of these functions on Windows */
50 #if defined(_MSC_VER)
51 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
52 typedef __int64 off_t;
53 #define fseeko _fseeki64
54 #define ftello _ftelli64
55 #elif defined(_WIN32)
56 /* MinGW defines off_t as long
57    and uses f{seek,tell}o64/off64_t for large files */
58 #define fseeko fseeko64
59 #define ftello ftello64
60 #define off_t off64_t
61 #endif
62
63 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
64
65 /* We should use 32-bit file operations in WebM file format
66  * when building ARM executable file (.axf) with RVCT */
67 #if !CONFIG_OS_SUPPORT
68 typedef long off_t;
69 #define fseeko fseek
70 #define ftello ftell
71 #endif
72
73 /* Swallow warnings about unused results of fread/fwrite */
74 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
75                          FILE *stream) {
76   return fread(ptr, size, nmemb, stream);
77 }
78 #define fread wrap_fread
79
80 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
81                           FILE *stream) {
82   return fwrite(ptr, size, nmemb, stream);
83 }
84 #define fwrite wrap_fwrite
85
86
87 static const char *exec_name;
88
89 static const struct codec_item {
90   char const              *name;
91   const vpx_codec_iface_t *(*iface)(void);
92   const vpx_codec_iface_t *(*dx_iface)(void);
93   unsigned int             fourcc;
94 } codecs[] = {
95 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
96   {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, 0x30385056},
97 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
98   {"vp8", &vpx_codec_vp8_cx, NULL, 0x30385056},
99 #endif
100 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
101   {"vp9", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, 0x30385056},
102 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
103   {"vp9", &vpx_codec_vp8_cx, NULL, 0x30385056},
104 #endif
105 };
106
107 static void usage_exit();
108
109 #define LOG_ERROR(label) do \
110   {\
111     const char *l=label;\
112     va_list ap;\
113     va_start(ap, fmt);\
114     if(l)\
115       fprintf(stderr, "%s: ", l);\
116     vfprintf(stderr, fmt, ap);\
117     fprintf(stderr, "\n");\
118     va_end(ap);\
119   } while(0)
120
121 void die(const char *fmt, ...) {
122   LOG_ERROR(NULL);
123   usage_exit();
124 }
125
126
127 void fatal(const char *fmt, ...) {
128   LOG_ERROR("Fatal");
129   exit(EXIT_FAILURE);
130 }
131
132
133 void warn(const char *fmt, ...) {
134   LOG_ERROR("Warning");
135 }
136
137
138 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
139   va_list ap;
140
141   va_start(ap, s);
142   if (ctx->err) {
143     const char *detail = vpx_codec_error_detail(ctx);
144
145     vfprintf(stderr, s, ap);
146     fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
147
148     if (detail)
149       fprintf(stderr, "    %s\n", detail);
150
151     exit(EXIT_FAILURE);
152   }
153 }
154
155 /* This structure is used to abstract the different ways of handling
156  * first pass statistics.
157  */
158 typedef struct {
159   vpx_fixed_buf_t buf;
160   int             pass;
161   FILE           *file;
162   char           *buf_ptr;
163   size_t          buf_alloc_sz;
164 } stats_io_t;
165
166 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
167   int res;
168
169   stats->pass = pass;
170
171   if (pass == 0) {
172     stats->file = fopen(fpf, "wb");
173     stats->buf.sz = 0;
174     stats->buf.buf = NULL,
175                res = (stats->file != NULL);
176   } else {
177 #if 0
178 #elif USE_POSIX_MMAP
179     struct stat stat_buf;
180     int fd;
181
182     fd = open(fpf, O_RDONLY);
183     stats->file = fdopen(fd, "rb");
184     fstat(fd, &stat_buf);
185     stats->buf.sz = stat_buf.st_size;
186     stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
187                           fd, 0);
188     res = (stats->buf.buf != NULL);
189 #else
190     size_t nbytes;
191
192     stats->file = fopen(fpf, "rb");
193
194     if (fseek(stats->file, 0, SEEK_END))
195       fatal("First-pass stats file must be seekable!");
196
197     stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
198     rewind(stats->file);
199
200     stats->buf.buf = malloc(stats->buf_alloc_sz);
201
202     if (!stats->buf.buf)
203       fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
204             (unsigned long)stats->buf_alloc_sz);
205
206     nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
207     res = (nbytes == stats->buf.sz);
208 #endif
209   }
210
211   return res;
212 }
213
214 int stats_open_mem(stats_io_t *stats, int pass) {
215   int res;
216   stats->pass = pass;
217
218   if (!pass) {
219     stats->buf.sz = 0;
220     stats->buf_alloc_sz = 64 * 1024;
221     stats->buf.buf = malloc(stats->buf_alloc_sz);
222   }
223
224   stats->buf_ptr = stats->buf.buf;
225   res = (stats->buf.buf != NULL);
226   return res;
227 }
228
229
230 void stats_close(stats_io_t *stats, int last_pass) {
231   if (stats->file) {
232     if (stats->pass == last_pass) {
233 #if 0
234 #elif USE_POSIX_MMAP
235       munmap(stats->buf.buf, stats->buf.sz);
236 #else
237       free(stats->buf.buf);
238 #endif
239     }
240
241     fclose(stats->file);
242     stats->file = NULL;
243   } else {
244     if (stats->pass == last_pass)
245       free(stats->buf.buf);
246   }
247 }
248
249 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
250   if (stats->file) {
251     (void) fwrite(pkt, 1, len, stats->file);
252   } else {
253     if (stats->buf.sz + len > stats->buf_alloc_sz) {
254       size_t  new_sz = stats->buf_alloc_sz + 64 * 1024;
255       char   *new_ptr = realloc(stats->buf.buf, new_sz);
256
257       if (new_ptr) {
258         stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
259         stats->buf.buf = new_ptr;
260         stats->buf_alloc_sz = new_sz;
261       } else
262         fatal("Failed to realloc firstpass stats buffer.");
263     }
264
265     memcpy(stats->buf_ptr, pkt, len);
266     stats->buf.sz += len;
267     stats->buf_ptr += len;
268   }
269 }
270
271 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
272   return stats->buf;
273 }
274
275 /* Stereo 3D packed frame format */
276 typedef enum stereo_format {
277   STEREO_FORMAT_MONO       = 0,
278   STEREO_FORMAT_LEFT_RIGHT = 1,
279   STEREO_FORMAT_BOTTOM_TOP = 2,
280   STEREO_FORMAT_TOP_BOTTOM = 3,
281   STEREO_FORMAT_RIGHT_LEFT = 11
282 } stereo_format_t;
283
284 enum video_file_type {
285   FILE_TYPE_RAW,
286   FILE_TYPE_IVF,
287   FILE_TYPE_Y4M
288 };
289
290 struct detect_buffer {
291   char buf[4];
292   size_t buf_read;
293   size_t position;
294 };
295
296
297 struct input_state {
298   char                 *fn;
299   FILE                 *file;
300   y4m_input             y4m;
301   struct detect_buffer  detect;
302   enum video_file_type  file_type;
303   unsigned int          w;
304   unsigned int          h;
305   struct vpx_rational   framerate;
306   int                   use_i420;
307 };
308
309
310 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
311 static int read_frame(struct input_state *input, vpx_image_t *img) {
312   FILE *f = input->file;
313   enum video_file_type file_type = input->file_type;
314   y4m_input *y4m = &input->y4m;
315   struct detect_buffer *detect = &input->detect;
316   int plane = 0;
317   int shortread = 0;
318
319   if (file_type == FILE_TYPE_Y4M) {
320     if (y4m_input_fetch_frame(y4m, f, img) < 1)
321       return 0;
322   } else {
323     if (file_type == FILE_TYPE_IVF) {
324       char junk[IVF_FRAME_HDR_SZ];
325
326       /* Skip the frame header. We know how big the frame should be. See
327        * write_ivf_frame_header() for documentation on the frame header
328        * layout.
329        */
330       (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
331     }
332
333     for (plane = 0; plane < 3; plane++) {
334       unsigned char *ptr;
335       int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
336       int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
337       int r;
338
339       /* Determine the correct plane based on the image format. The for-loop
340        * always counts in Y,U,V order, but this may not match the order of
341        * the data on disk.
342        */
343       switch (plane) {
344         case 1:
345           ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
346           break;
347         case 2:
348           ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
349           break;
350         default:
351           ptr = img->planes[plane];
352       }
353
354       for (r = 0; r < h; r++) {
355         size_t needed = w;
356         size_t buf_position = 0;
357         const size_t left = detect->buf_read - detect->position;
358         if (left > 0) {
359           const size_t more = (left < needed) ? left : needed;
360           memcpy(ptr, detect->buf + detect->position, more);
361           buf_position = more;
362           needed -= more;
363           detect->position += more;
364         }
365         if (needed > 0) {
366           shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
367         }
368
369         ptr += img->stride[plane];
370       }
371     }
372   }
373
374   return !shortread;
375 }
376
377
378 unsigned int file_is_y4m(FILE      *infile,
379                          y4m_input *y4m,
380                          char       detect[4]) {
381   if (memcmp(detect, "YUV4", 4) == 0) {
382     return 1;
383   }
384   return 0;
385 }
386
387 #define IVF_FILE_HDR_SZ (32)
388 unsigned int file_is_ivf(struct input_state *input,
389                          unsigned int *fourcc) {
390   char raw_hdr[IVF_FILE_HDR_SZ];
391   int is_ivf = 0;
392   FILE *infile = input->file;
393   unsigned int *width = &input->w;
394   unsigned int *height = &input->h;
395   struct detect_buffer *detect = &input->detect;
396
397   if (memcmp(detect->buf, "DKIF", 4) != 0)
398     return 0;
399
400   /* See write_ivf_file_header() for more documentation on the file header
401    * layout.
402    */
403   if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
404       == IVF_FILE_HDR_SZ - 4) {
405     {
406       is_ivf = 1;
407
408       if (mem_get_le16(raw_hdr + 4) != 0)
409         warn("Unrecognized IVF version! This file may not decode "
410              "properly.");
411
412       *fourcc = mem_get_le32(raw_hdr + 8);
413     }
414   }
415
416   if (is_ivf) {
417     *width = mem_get_le16(raw_hdr + 12);
418     *height = mem_get_le16(raw_hdr + 14);
419     detect->position = 4;
420   }
421
422   return is_ivf;
423 }
424
425
426 static void write_ivf_file_header(FILE *outfile,
427                                   const vpx_codec_enc_cfg_t *cfg,
428                                   unsigned int fourcc,
429                                   int frame_cnt) {
430   char header[32];
431
432   if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
433     return;
434
435   header[0] = 'D';
436   header[1] = 'K';
437   header[2] = 'I';
438   header[3] = 'F';
439   mem_put_le16(header + 4,  0);                 /* version */
440   mem_put_le16(header + 6,  32);                /* headersize */
441   mem_put_le32(header + 8,  fourcc);            /* headersize */
442   mem_put_le16(header + 12, cfg->g_w);          /* width */
443   mem_put_le16(header + 14, cfg->g_h);          /* height */
444   mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
445   mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
446   mem_put_le32(header + 24, frame_cnt);         /* length */
447   mem_put_le32(header + 28, 0);                 /* unused */
448
449   (void) fwrite(header, 1, 32, outfile);
450 }
451
452
453 static void write_ivf_frame_header(FILE *outfile,
454                                    const vpx_codec_cx_pkt_t *pkt) {
455   char             header[12];
456   vpx_codec_pts_t  pts;
457
458   if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
459     return;
460
461   pts = pkt->data.frame.pts;
462   mem_put_le32(header, (int)pkt->data.frame.sz);
463   mem_put_le32(header + 4, pts & 0xFFFFFFFF);
464   mem_put_le32(header + 8, pts >> 32);
465
466   (void) fwrite(header, 1, 12, outfile);
467 }
468
469 static void write_ivf_frame_size(FILE *outfile, size_t size) {
470   char             header[4];
471   mem_put_le32(header, (int)size);
472   (void) fwrite(header, 1, 4, outfile);
473 }
474
475
476 typedef off_t EbmlLoc;
477
478
479 struct cue_entry {
480   unsigned int time;
481   uint64_t     loc;
482 };
483
484
485 struct EbmlGlobal {
486   int debug;
487
488   FILE    *stream;
489   int64_t last_pts_ms;
490   vpx_rational_t  framerate;
491
492   /* These pointers are to the start of an element */
493   off_t    position_reference;
494   off_t    seek_info_pos;
495   off_t    segment_info_pos;
496   off_t    track_pos;
497   off_t    cue_pos;
498   off_t    cluster_pos;
499
500   /* This pointer is to a specific element to be serialized */
501   off_t    track_id_pos;
502
503   /* These pointers are to the size field of the element */
504   EbmlLoc  startSegment;
505   EbmlLoc  startCluster;
506
507   uint32_t cluster_timecode;
508   int      cluster_open;
509
510   struct cue_entry *cue_list;
511   unsigned int      cues;
512
513 };
514
515
516 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
517   (void) fwrite(buffer_in, 1, len, glob->stream);
518 }
519
520 #define WRITE_BUFFER(s) \
521   for(i = len-1; i>=0; i--)\
522   { \
523     x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
524     Ebml_Write(glob, &x, 1); \
525   }
526 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
527   char x;
528   int i;
529
530   /* buffer_size:
531    * 1 - int8_t;
532    * 2 - int16_t;
533    * 3 - int32_t;
534    * 4 - int64_t;
535    */
536   switch (buffer_size) {
537     case 1:
538       WRITE_BUFFER(int8_t)
539       break;
540     case 2:
541       WRITE_BUFFER(int16_t)
542       break;
543     case 4:
544       WRITE_BUFFER(int32_t)
545       break;
546     case 8:
547       WRITE_BUFFER(int64_t)
548       break;
549     default:
550       break;
551   }
552 }
553 #undef WRITE_BUFFER
554
555 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
556  * one, but not a 32 bit one.
557  */
558 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
559   unsigned char sizeSerialized = 4 | 0x80;
560   Ebml_WriteID(glob, class_id);
561   Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
562   Ebml_Serialize(glob, &ui, sizeof(ui), 4);
563 }
564
565
566 static void
567 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
568                      unsigned long class_id) {
569   /* todo this is always taking 8 bytes, this may need later optimization */
570   /* this is a key that says length unknown */
571   uint64_t unknownLen = LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
572
573   Ebml_WriteID(glob, class_id);
574   *ebmlLoc = ftello(glob->stream);
575   Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
576 }
577
578 static void
579 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
580   off_t pos;
581   uint64_t size;
582
583   /* Save the current stream pointer */
584   pos = ftello(glob->stream);
585
586   /* Calculate the size of this element */
587   size = pos - *ebmlLoc - 8;
588   size |= LITERALU64(0x01000000, 0x00000000);
589
590   /* Seek back to the beginning of the element and write the new size */
591   fseeko(glob->stream, *ebmlLoc, SEEK_SET);
592   Ebml_Serialize(glob, &size, sizeof(size), 8);
593
594   /* Reset the stream pointer */
595   fseeko(glob->stream, pos, SEEK_SET);
596 }
597
598
599 static void
600 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
601   uint64_t offset = pos - ebml->position_reference;
602   EbmlLoc start;
603   Ebml_StartSubElement(ebml, &start, Seek);
604   Ebml_SerializeBinary(ebml, SeekID, id);
605   Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
606   Ebml_EndSubElement(ebml, &start);
607 }
608
609
610 static void
611 write_webm_seek_info(EbmlGlobal *ebml) {
612
613   off_t pos;
614
615   /* Save the current stream pointer */
616   pos = ftello(ebml->stream);
617
618   if (ebml->seek_info_pos)
619     fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
620   else
621     ebml->seek_info_pos = pos;
622
623   {
624     EbmlLoc start;
625
626     Ebml_StartSubElement(ebml, &start, SeekHead);
627     write_webm_seek_element(ebml, Tracks, ebml->track_pos);
628     write_webm_seek_element(ebml, Cues,   ebml->cue_pos);
629     write_webm_seek_element(ebml, Info,   ebml->segment_info_pos);
630     Ebml_EndSubElement(ebml, &start);
631   }
632   {
633     /* segment info */
634     EbmlLoc startInfo;
635     uint64_t frame_time;
636     char version_string[64];
637
638     /* Assemble version string */
639     if (ebml->debug)
640       strcpy(version_string, "vpxenc");
641     else {
642       strcpy(version_string, "vpxenc ");
643       strncat(version_string,
644               vpx_codec_version_str(),
645               sizeof(version_string) - 1 - strlen(version_string));
646     }
647
648     frame_time = (uint64_t)1000 * ebml->framerate.den
649                  / ebml->framerate.num;
650     ebml->segment_info_pos = ftello(ebml->stream);
651     Ebml_StartSubElement(ebml, &startInfo, Info);
652     Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
653     Ebml_SerializeFloat(ebml, Segment_Duration,
654                         (double)(ebml->last_pts_ms + frame_time));
655     Ebml_SerializeString(ebml, 0x4D80, version_string);
656     Ebml_SerializeString(ebml, 0x5741, version_string);
657     Ebml_EndSubElement(ebml, &startInfo);
658   }
659 }
660
661
662 static void
663 write_webm_file_header(EbmlGlobal                *glob,
664                        const vpx_codec_enc_cfg_t *cfg,
665                        const struct vpx_rational *fps,
666                        stereo_format_t            stereo_fmt) {
667   {
668     EbmlLoc start;
669     Ebml_StartSubElement(glob, &start, EBML);
670     Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
671     Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
672     Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
673     Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
674     Ebml_SerializeString(glob, DocType, "webm");
675     Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
676     Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
677     Ebml_EndSubElement(glob, &start);
678   }
679   {
680     Ebml_StartSubElement(glob, &glob->startSegment, Segment);
681     glob->position_reference = ftello(glob->stream);
682     glob->framerate = *fps;
683     write_webm_seek_info(glob);
684
685     {
686       EbmlLoc trackStart;
687       glob->track_pos = ftello(glob->stream);
688       Ebml_StartSubElement(glob, &trackStart, Tracks);
689       {
690         unsigned int trackNumber = 1;
691         uint64_t     trackID = 0;
692
693         EbmlLoc start;
694         Ebml_StartSubElement(glob, &start, TrackEntry);
695         Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
696         glob->track_id_pos = ftello(glob->stream);
697         Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
698         Ebml_SerializeUnsigned(glob, TrackType, 1);
699         Ebml_SerializeString(glob, CodecID, "V_VP8");
700         {
701           unsigned int pixelWidth = cfg->g_w;
702           unsigned int pixelHeight = cfg->g_h;
703           float        frameRate   = (float)fps->num / (float)fps->den;
704
705           EbmlLoc videoStart;
706           Ebml_StartSubElement(glob, &videoStart, Video);
707           Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
708           Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
709           Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
710           Ebml_SerializeFloat(glob, FrameRate, frameRate);
711           Ebml_EndSubElement(glob, &videoStart);
712         }
713         Ebml_EndSubElement(glob, &start); /* Track Entry */
714       }
715       Ebml_EndSubElement(glob, &trackStart);
716     }
717     /* segment element is open */
718   }
719 }
720
721
722 static void
723 write_webm_block(EbmlGlobal                *glob,
724                  const vpx_codec_enc_cfg_t *cfg,
725                  const vpx_codec_cx_pkt_t  *pkt) {
726   unsigned long  block_length;
727   unsigned char  track_number;
728   unsigned short block_timecode = 0;
729   unsigned char  flags;
730   int64_t        pts_ms;
731   int            start_cluster = 0, is_keyframe;
732
733   /* Calculate the PTS of this frame in milliseconds */
734   pts_ms = pkt->data.frame.pts * 1000
735            * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
736   if (pts_ms <= glob->last_pts_ms)
737     pts_ms = glob->last_pts_ms + 1;
738   glob->last_pts_ms = pts_ms;
739
740   /* Calculate the relative time of this block */
741   if (pts_ms - glob->cluster_timecode > SHRT_MAX)
742     start_cluster = 1;
743   else
744     block_timecode = (unsigned short)pts_ms - glob->cluster_timecode;
745
746   is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
747   if (start_cluster || is_keyframe) {
748     if (glob->cluster_open)
749       Ebml_EndSubElement(glob, &glob->startCluster);
750
751     /* Open the new cluster */
752     block_timecode = 0;
753     glob->cluster_open = 1;
754     glob->cluster_timecode = (uint32_t)pts_ms;
755     glob->cluster_pos = ftello(glob->stream);
756     Ebml_StartSubElement(glob, &glob->startCluster, Cluster); /* cluster */
757     Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
758
759     /* Save a cue point if this is a keyframe. */
760     if (is_keyframe) {
761       struct cue_entry *cue, *new_cue_list;
762
763       new_cue_list = realloc(glob->cue_list,
764                              (glob->cues + 1) * sizeof(struct cue_entry));
765       if (new_cue_list)
766         glob->cue_list = new_cue_list;
767       else
768         fatal("Failed to realloc cue list.");
769
770       cue = &glob->cue_list[glob->cues];
771       cue->time = glob->cluster_timecode;
772       cue->loc = glob->cluster_pos;
773       glob->cues++;
774     }
775   }
776
777   /* Write the Simple Block */
778   Ebml_WriteID(glob, SimpleBlock);
779
780   block_length = (unsigned long)pkt->data.frame.sz + 4;
781   block_length |= 0x10000000;
782   Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
783
784   track_number = 1;
785   track_number |= 0x80;
786   Ebml_Write(glob, &track_number, 1);
787
788   Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
789
790   flags = 0;
791   if (is_keyframe)
792     flags |= 0x80;
793   if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
794     flags |= 0x08;
795   Ebml_Write(glob, &flags, 1);
796
797   Ebml_Write(glob, pkt->data.frame.buf, (unsigned long)pkt->data.frame.sz);
798 }
799
800
801 static void
802 write_webm_file_footer(EbmlGlobal *glob, long hash) {
803
804   if (glob->cluster_open)
805     Ebml_EndSubElement(glob, &glob->startCluster);
806
807   {
808     EbmlLoc start;
809     unsigned int i;
810
811     glob->cue_pos = ftello(glob->stream);
812     Ebml_StartSubElement(glob, &start, Cues);
813     for (i = 0; i < glob->cues; i++) {
814       struct cue_entry *cue = &glob->cue_list[i];
815       EbmlLoc start;
816
817       Ebml_StartSubElement(glob, &start, CuePoint);
818       {
819         EbmlLoc start;
820
821         Ebml_SerializeUnsigned(glob, CueTime, cue->time);
822
823         Ebml_StartSubElement(glob, &start, CueTrackPositions);
824         Ebml_SerializeUnsigned(glob, CueTrack, 1);
825         Ebml_SerializeUnsigned64(glob, CueClusterPosition,
826                                  cue->loc - glob->position_reference);
827         Ebml_EndSubElement(glob, &start);
828       }
829       Ebml_EndSubElement(glob, &start);
830     }
831     Ebml_EndSubElement(glob, &start);
832   }
833
834   Ebml_EndSubElement(glob, &glob->startSegment);
835
836   /* Patch up the seek info block */
837   write_webm_seek_info(glob);
838
839   /* Patch up the track id */
840   fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
841   Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
842
843   fseeko(glob->stream, 0, SEEK_END);
844 }
845
846
847 /* Murmur hash derived from public domain reference implementation at
848  *   http:// sites.google.com/site/murmurhash/
849  */
850 static unsigned int murmur(const void *key, int len, unsigned int seed) {
851   const unsigned int m = 0x5bd1e995;
852   const int r = 24;
853
854   unsigned int h = seed ^ len;
855
856   const unsigned char *data = (const unsigned char *)key;
857
858   while (len >= 4) {
859     unsigned int k;
860
861     k  = data[0];
862     k |= data[1] << 8;
863     k |= data[2] << 16;
864     k |= data[3] << 24;
865
866     k *= m;
867     k ^= k >> r;
868     k *= m;
869
870     h *= m;
871     h ^= k;
872
873     data += 4;
874     len -= 4;
875   }
876
877   switch (len) {
878     case 3:
879       h ^= data[2] << 16;
880     case 2:
881       h ^= data[1] << 8;
882     case 1:
883       h ^= data[0];
884       h *= m;
885   };
886
887   h ^= h >> 13;
888   h *= m;
889   h ^= h >> 15;
890
891   return h;
892 }
893
894 #include "math.h"
895 #define MAX_PSNR 100
896 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
897   double psnr;
898
899   if ((double)Mse > 0.0)
900     psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
901   else
902     psnr = MAX_PSNR;      /* Limit to prevent / 0 */
903
904   if (psnr > MAX_PSNR)
905     psnr = MAX_PSNR;
906
907   return psnr;
908 }
909
910
911 #include "args.h"
912 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
913                                            "Debug mode (makes output deterministic)");
914 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
915                                             "Output filename");
916 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
917                                           "Input file is YV12 ");
918 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
919                                           "Input file is I420 (default)");
920 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
921                                           "Codec to use");
922 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
923                                                   "Number of passes (1/2)");
924 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
925                                                   "Pass to execute (1/2)");
926 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
927                                                   "First pass statistics file name");
928 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
929                                        "Stop encoding after n input frames");
930 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
931                                       "Skip the first n input frames");
932 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
933                                                   "Deadline per frame (usec)");
934 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
935                                                   "Use Best Quality Deadline");
936 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
937                                                   "Use Good Quality Deadline");
938 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
939                                                   "Use Realtime Quality Deadline");
940 static const arg_def_t quietarg         = ARG_DEF("q", "quiet", 0,
941                                                   "Do not print encode progress");
942 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
943                                                   "Show encoder parameters");
944 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
945                                                   "Show PSNR in status line");
946 static const arg_def_t recontest        = ARG_DEF(NULL, "test-decode", 0,
947                                                   "Test encode/decode mismatch");
948 static const arg_def_t framerate        = ARG_DEF(NULL, "fps", 1,
949                                                   "Stream frame rate (rate/scale)");
950 static const arg_def_t use_ivf          = ARG_DEF(NULL, "ivf", 0,
951                                                   "Output IVF (default is WebM)");
952 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
953                                           "Makes encoder output partitions. Requires IVF output!");
954 static const arg_def_t q_hist_n         = ARG_DEF(NULL, "q-hist", 1,
955                                                   "Show quantizer histogram (n-buckets)");
956 static const arg_def_t rate_hist_n         = ARG_DEF(NULL, "rate-hist", 1,
957                                                      "Show rate histogram (n-buckets)");
958 static const arg_def_t *main_args[] = {
959   &debugmode,
960   &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
961   &deadline, &best_dl, &good_dl, &rt_dl,
962   &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
963   NULL
964 };
965
966 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
967                                                   "Usage profile number to use");
968 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
969                                                   "Max number of threads to use");
970 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
971                                                   "Bitstream profile number to use");
972 static const arg_def_t width            = ARG_DEF("w", "width", 1,
973                                                   "Frame width");
974 static const arg_def_t height           = ARG_DEF("h", "height", 1,
975                                                   "Frame height");
976 static const struct arg_enum_list stereo_mode_enum[] = {
977   {"mono", STEREO_FORMAT_MONO},
978   {"left-right", STEREO_FORMAT_LEFT_RIGHT},
979   {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
980   {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
981   {"right-left", STEREO_FORMAT_RIGHT_LEFT},
982   {NULL, 0}
983 };
984 static const arg_def_t stereo_mode      = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
985                                                        "Stereo 3D video format", stereo_mode_enum);
986 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
987                                                   "Output timestamp precision (fractional seconds)");
988 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
989                                                   "Enable error resiliency features");
990 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
991                                                   "Max number of frames to lag");
992
993 static const arg_def_t *global_args[] = {
994   &use_yv12, &use_i420, &usage, &threads, &profile,
995   &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
996   &lag_in_frames, NULL
997 };
998
999 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
1000                                                     "Temporal resampling threshold (buf %)");
1001 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
1002                                                     "Spatial resampling enabled (bool)");
1003 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
1004                                                     "Upscale threshold (buf %)");
1005 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1006                                                     "Downscale threshold (buf %)");
1007 static const struct arg_enum_list end_usage_enum[] = {
1008   {"vbr", VPX_VBR},
1009   {"cbr", VPX_CBR},
1010   {"cq",  VPX_CQ},
1011   {NULL, 0}
1012 };
1013 static const arg_def_t end_usage          = ARG_DEF_ENUM(NULL, "end-usage", 1,
1014                                                          "Rate control mode", end_usage_enum);
1015 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
1016                                                     "Bitrate (kbps)");
1017 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
1018                                                     "Minimum (best) quantizer");
1019 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
1020                                                     "Maximum (worst) quantizer");
1021 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
1022                                                     "Datarate undershoot (min) target (%)");
1023 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
1024                                                     "Datarate overshoot (max) target (%)");
1025 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
1026                                                     "Client buffer size (ms)");
1027 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
1028                                                     "Client initial buffer size (ms)");
1029 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
1030                                                     "Client optimal buffer size (ms)");
1031 static const arg_def_t *rc_args[] = {
1032   &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1033   &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1034   &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1035   NULL
1036 };
1037
1038
1039 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1040                                           "CBR/VBR bias (0=CBR, 100=VBR)");
1041 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1042                                                 "GOP min bitrate (% of target)");
1043 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1044                                                 "GOP max bitrate (% of target)");
1045 static const arg_def_t *rc_twopass_args[] = {
1046   &bias_pct, &minsection_pct, &maxsection_pct, NULL
1047 };
1048
1049
1050 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1051                                              "Minimum keyframe interval (frames)");
1052 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1053                                              "Maximum keyframe interval (frames)");
1054 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1055                                              "Disable keyframe placement");
1056 static const arg_def_t *kf_args[] = {
1057   &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1058 };
1059
1060
1061 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1062 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1063                                             "Noise sensitivity (frames to blur)");
1064 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1065                                            "Filter sharpness (0-7)");
1066 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1067                                                "Motion detection threshold");
1068 #endif
1069
1070 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1071 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1072                                           "CPU Used (-16..16)");
1073 #endif
1074
1075
1076 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1077 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1078                                              "Number of token partitions to use, log2");
1079 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1080                                              "Enable automatic alt reference frames");
1081 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1082                                                 "AltRef Max Frames");
1083 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1084                                                "AltRef Strength");
1085 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1086                                            "AltRef Type");
1087 static const struct arg_enum_list tuning_enum[] = {
1088   {"psnr", VP8_TUNE_PSNR},
1089   {"ssim", VP8_TUNE_SSIM},
1090   {NULL, 0}
1091 };
1092 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1093                                                 "Material to favor", tuning_enum);
1094 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1095                                           "Constrained Quality Level");
1096 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1097                                                     "Max I-frame bitrate (pct)");
1098 #if CONFIG_LOSSLESS
1099 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
1100 #endif
1101
1102 static const arg_def_t *vp8_args[] = {
1103   &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1104   &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1105   &tune_ssim, &cq_level, &max_intra_rate_pct,
1106 #if CONFIG_LOSSLESS
1107   &lossless,
1108 #endif
1109   NULL
1110 };
1111 static const int vp8_arg_ctrl_map[] = {
1112   VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1113   VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1114   VP8E_SET_TOKEN_PARTITIONS,
1115   VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
1116   VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
1117 #if CONFIG_LOSSLESS
1118   VP9E_SET_LOSSLESS,
1119 #endif
1120   0
1121 };
1122 #endif
1123
1124 static const arg_def_t *no_args[] = { NULL };
1125
1126 static void usage_exit() {
1127   int i;
1128
1129   fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1130           exec_name);
1131
1132   fprintf(stderr, "\nOptions:\n");
1133   arg_show_usage(stdout, main_args);
1134   fprintf(stderr, "\nEncoder Global Options:\n");
1135   arg_show_usage(stdout, global_args);
1136   fprintf(stderr, "\nRate Control Options:\n");
1137   arg_show_usage(stdout, rc_args);
1138   fprintf(stderr, "\nTwopass Rate Control Options:\n");
1139   arg_show_usage(stdout, rc_twopass_args);
1140   fprintf(stderr, "\nKeyframe Placement Options:\n");
1141   arg_show_usage(stdout, kf_args);
1142 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1143   fprintf(stderr, "\nVP8 Specific Options:\n");
1144   arg_show_usage(stdout, vp8_args);
1145 #endif
1146   fprintf(stderr, "\nStream timebase (--timebase):\n"
1147           "  The desired precision of timestamps in the output, expressed\n"
1148           "  in fractional seconds. Default is 1/1000.\n");
1149   fprintf(stderr, "\n"
1150           "Included encoders:\n"
1151           "\n");
1152
1153   for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1154     fprintf(stderr, "    %-6s - %s\n",
1155             codecs[i].name,
1156             vpx_codec_iface_name(codecs[i].iface()));
1157
1158   exit(EXIT_FAILURE);
1159 }
1160
1161
1162 #define HIST_BAR_MAX 40
1163 struct hist_bucket {
1164   int low, high, count;
1165 };
1166
1167
1168 static int merge_hist_buckets(struct hist_bucket *bucket,
1169                               int *buckets_,
1170                               int max_buckets) {
1171   int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
1172   int buckets = *buckets_;
1173   int i;
1174
1175   /* Find the extrema for this list of buckets */
1176   big_bucket = small_bucket = 0;
1177   for (i = 0; i < buckets; i++) {
1178     if (bucket[i].count < bucket[small_bucket].count)
1179       small_bucket = i;
1180     if (bucket[i].count > bucket[big_bucket].count)
1181       big_bucket = i;
1182   }
1183
1184   /* If we have too many buckets, merge the smallest with an adjacent
1185    * bucket.
1186    */
1187   while (buckets > max_buckets) {
1188     int last_bucket = buckets - 1;
1189
1190     /* merge the small bucket with an adjacent one. */
1191     if (small_bucket == 0)
1192       merge_bucket = 1;
1193     else if (small_bucket == last_bucket)
1194       merge_bucket = last_bucket - 1;
1195     else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1196       merge_bucket = small_bucket - 1;
1197     else
1198       merge_bucket = small_bucket + 1;
1199
1200     assert(abs(merge_bucket - small_bucket) <= 1);
1201     assert(small_bucket < buckets);
1202     assert(big_bucket < buckets);
1203     assert(merge_bucket < buckets);
1204
1205     if (merge_bucket < small_bucket) {
1206       bucket[merge_bucket].high = bucket[small_bucket].high;
1207       bucket[merge_bucket].count += bucket[small_bucket].count;
1208     } else {
1209       bucket[small_bucket].high = bucket[merge_bucket].high;
1210       bucket[small_bucket].count += bucket[merge_bucket].count;
1211       merge_bucket = small_bucket;
1212     }
1213
1214     assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1215
1216     buckets--;
1217
1218     /* Remove the merge_bucket from the list, and find the new small
1219      * and big buckets while we're at it
1220      */
1221     big_bucket = small_bucket = 0;
1222     for (i = 0; i < buckets; i++) {
1223       if (i > merge_bucket)
1224         bucket[i] = bucket[i + 1];
1225
1226       if (bucket[i].count < bucket[small_bucket].count)
1227         small_bucket = i;
1228       if (bucket[i].count > bucket[big_bucket].count)
1229         big_bucket = i;
1230     }
1231
1232   }
1233
1234   *buckets_ = buckets;
1235   return bucket[big_bucket].count;
1236 }
1237
1238
1239 static void show_histogram(const struct hist_bucket *bucket,
1240                            int                       buckets,
1241                            int                       total,
1242                            int                       scale) {
1243   const char *pat1, *pat2;
1244   int i;
1245
1246   switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
1247     case 1:
1248     case 2:
1249       pat1 = "%4d %2s: ";
1250       pat2 = "%4d-%2d: ";
1251       break;
1252     case 3:
1253       pat1 = "%5d %3s: ";
1254       pat2 = "%5d-%3d: ";
1255       break;
1256     case 4:
1257       pat1 = "%6d %4s: ";
1258       pat2 = "%6d-%4d: ";
1259       break;
1260     case 5:
1261       pat1 = "%7d %5s: ";
1262       pat2 = "%7d-%5d: ";
1263       break;
1264     case 6:
1265       pat1 = "%8d %6s: ";
1266       pat2 = "%8d-%6d: ";
1267       break;
1268     case 7:
1269       pat1 = "%9d %7s: ";
1270       pat2 = "%9d-%7d: ";
1271       break;
1272     default:
1273       pat1 = "%12d %10s: ";
1274       pat2 = "%12d-%10d: ";
1275       break;
1276   }
1277
1278   for (i = 0; i < buckets; i++) {
1279     int len;
1280     int j;
1281     float pct;
1282
1283     pct = (float)(100.0 * bucket[i].count / total);
1284     len = HIST_BAR_MAX * bucket[i].count / scale;
1285     if (len < 1)
1286       len = 1;
1287     assert(len <= HIST_BAR_MAX);
1288
1289     if (bucket[i].low == bucket[i].high)
1290       fprintf(stderr, pat1, bucket[i].low, "");
1291     else
1292       fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1293
1294     for (j = 0; j < HIST_BAR_MAX; j++)
1295       fprintf(stderr, j < len ? "=" : " ");
1296     fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
1297   }
1298 }
1299
1300
1301 static void show_q_histogram(const int counts[64], int max_buckets) {
1302   struct hist_bucket bucket[64];
1303   int buckets = 0;
1304   int total = 0;
1305   int scale;
1306   int i;
1307
1308
1309   for (i = 0; i < 64; i++) {
1310     if (counts[i]) {
1311       bucket[buckets].low = bucket[buckets].high = i;
1312       bucket[buckets].count = counts[i];
1313       buckets++;
1314       total += counts[i];
1315     }
1316   }
1317
1318   fprintf(stderr, "\nQuantizer Selection:\n");
1319   scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1320   show_histogram(bucket, buckets, total, scale);
1321 }
1322
1323
1324 #define RATE_BINS (100)
1325 struct rate_hist {
1326   int64_t            *pts;
1327   int                *sz;
1328   int                 samples;
1329   int                 frames;
1330   struct hist_bucket  bucket[RATE_BINS];
1331   int                 total;
1332 };
1333
1334
1335 static void init_rate_histogram(struct rate_hist          *hist,
1336                                 const vpx_codec_enc_cfg_t *cfg,
1337                                 const vpx_rational_t      *fps) {
1338   int i;
1339
1340   /* Determine the number of samples in the buffer. Use the file's framerate
1341    * to determine the number of frames in rc_buf_sz milliseconds, with an
1342    * adjustment (5/4) to account for alt-refs
1343    */
1344   hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1345
1346   /* prevent division by zero */
1347   if (hist->samples == 0)
1348     hist->samples = 1;
1349
1350   hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1351   hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1352   for (i = 0; i < RATE_BINS; i++) {
1353     hist->bucket[i].low = INT_MAX;
1354     hist->bucket[i].high = 0;
1355     hist->bucket[i].count = 0;
1356   }
1357 }
1358
1359
1360 static void destroy_rate_histogram(struct rate_hist *hist) {
1361   free(hist->pts);
1362   free(hist->sz);
1363 }
1364
1365
1366 static void update_rate_histogram(struct rate_hist          *hist,
1367                                   const vpx_codec_enc_cfg_t *cfg,
1368                                   const vpx_codec_cx_pkt_t  *pkt) {
1369   int i, idx;
1370   int64_t now, then, sum_sz = 0, avg_bitrate;
1371
1372   now = pkt->data.frame.pts * 1000
1373         * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1374
1375   idx = hist->frames++ % hist->samples;
1376   hist->pts[idx] = now;
1377   hist->sz[idx] = (int)pkt->data.frame.sz;
1378
1379   if (now < cfg->rc_buf_initial_sz)
1380     return;
1381
1382   then = now;
1383
1384   /* Sum the size over the past rc_buf_sz ms */
1385   for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
1386     int i_idx = (i - 1) % hist->samples;
1387
1388     then = hist->pts[i_idx];
1389     if (now - then > cfg->rc_buf_sz)
1390       break;
1391     sum_sz += hist->sz[i_idx];
1392   }
1393
1394   if (now == then)
1395     return;
1396
1397   avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1398   idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
1399   if (idx < 0)
1400     idx = 0;
1401   if (idx > RATE_BINS - 1)
1402     idx = RATE_BINS - 1;
1403   if (hist->bucket[idx].low > avg_bitrate)
1404     hist->bucket[idx].low = (int)avg_bitrate;
1405   if (hist->bucket[idx].high < avg_bitrate)
1406     hist->bucket[idx].high = (int)avg_bitrate;
1407   hist->bucket[idx].count++;
1408   hist->total++;
1409 }
1410
1411
1412 static void show_rate_histogram(struct rate_hist          *hist,
1413                                 const vpx_codec_enc_cfg_t *cfg,
1414                                 int                        max_buckets) {
1415   int i, scale;
1416   int buckets = 0;
1417
1418   for (i = 0; i < RATE_BINS; i++) {
1419     if (hist->bucket[i].low == INT_MAX)
1420       continue;
1421     hist->bucket[buckets++] = hist->bucket[i];
1422   }
1423
1424   fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1425   scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1426   show_histogram(hist->bucket, buckets, hist->total, scale);
1427 }
1428
1429
1430 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
1431 {
1432   int match = 1;
1433   int i;
1434
1435   match &= (img1->fmt == img2->fmt);
1436   match &= (img1->w == img2->w);
1437   match &= (img1->h == img2->h);
1438
1439   for (i = 0; i < img1->d_h; i++)
1440     match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
1441                      img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
1442                      img1->d_w) == 0);
1443
1444   for (i = 0; i < img1->d_h/2; i++)
1445     match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
1446                      img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
1447                      (img1->d_w + 1) / 2) == 0);
1448
1449   for (i = 0; i < img1->d_h/2; i++)
1450     match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
1451                      img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
1452                      (img1->d_w + 1) / 2) == 0);
1453
1454   return match;
1455 }
1456
1457
1458 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1459 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1460
1461
1462 /* Configuration elements common to all streams */
1463 struct global_config {
1464   const struct codec_item  *codec;
1465   int                       passes;
1466   int                       pass;
1467   int                       usage;
1468   int                       deadline;
1469   int                       use_i420;
1470   int                       quiet;
1471   int                       verbose;
1472   int                       limit;
1473   int                       skip_frames;
1474   int                       show_psnr;
1475   int                       test_decode;
1476   int                       have_framerate;
1477   struct vpx_rational       framerate;
1478   int                       out_part;
1479   int                       debug;
1480   int                       show_q_hist_buckets;
1481   int                       show_rate_hist_buckets;
1482 };
1483
1484
1485 /* Per-stream configuration */
1486 struct stream_config {
1487   struct vpx_codec_enc_cfg  cfg;
1488   const char               *out_fn;
1489   const char               *stats_fn;
1490   stereo_format_t           stereo_fmt;
1491   int                       arg_ctrls[ARG_CTRL_CNT_MAX][2];
1492   int                       arg_ctrl_cnt;
1493   int                       write_webm;
1494   int                       have_kf_max_dist;
1495 };
1496
1497
1498 struct stream_state {
1499   int                       index;
1500   struct stream_state      *next;
1501   struct stream_config      config;
1502   FILE                     *file;
1503   struct rate_hist          rate_hist;
1504   EbmlGlobal                ebml;
1505   uint32_t                  hash;
1506   uint64_t                  psnr_sse_total;
1507   uint64_t                  psnr_samples_total;
1508   double                    psnr_totals[4];
1509   int                       psnr_count;
1510   int                       counts[64];
1511   vpx_codec_ctx_t           encoder;
1512   unsigned int              frames_out;
1513   uint64_t                  cx_time;
1514   size_t                    nbytes;
1515   stats_io_t                stats;
1516   vpx_codec_ctx_t           decoder;
1517   vpx_ref_frame_t           ref_enc;
1518   vpx_ref_frame_t           ref_dec;
1519   int                       mismatch_seen;
1520 };
1521
1522
1523 void validate_positive_rational(const char          *msg,
1524                                 struct vpx_rational *rat) {
1525   if (rat->den < 0) {
1526     rat->num *= -1;
1527     rat->den *= -1;
1528   }
1529
1530   if (rat->num < 0)
1531     die("Error: %s must be positive\n", msg);
1532
1533   if (!rat->den)
1534     die("Error: %s has zero denominator\n", msg);
1535 }
1536
1537
1538 static void parse_global_config(struct global_config *global, char **argv) {
1539   char       **argi, **argj;
1540   struct arg   arg;
1541
1542   /* Initialize default parameters */
1543   memset(global, 0, sizeof(*global));
1544   global->codec = codecs;
1545   global->passes = 1;
1546   global->use_i420 = 1;
1547
1548   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1549     arg.argv_step = 1;
1550
1551     if (arg_match(&arg, &codecarg, argi)) {
1552       int j, k = -1;
1553
1554       for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1555         if (!strcmp(codecs[j].name, arg.val))
1556           k = j;
1557
1558       if (k >= 0)
1559         global->codec = codecs + k;
1560       else
1561         die("Error: Unrecognized argument (%s) to --codec\n",
1562             arg.val);
1563
1564     } else if (arg_match(&arg, &passes, argi)) {
1565       global->passes = arg_parse_uint(&arg);
1566
1567       if (global->passes < 1 || global->passes > 2)
1568         die("Error: Invalid number of passes (%d)\n", global->passes);
1569     } else if (arg_match(&arg, &pass_arg, argi)) {
1570       global->pass = arg_parse_uint(&arg);
1571
1572       if (global->pass < 1 || global->pass > 2)
1573         die("Error: Invalid pass selected (%d)\n",
1574             global->pass);
1575     } else if (arg_match(&arg, &usage, argi))
1576       global->usage = arg_parse_uint(&arg);
1577     else if (arg_match(&arg, &deadline, argi))
1578       global->deadline = arg_parse_uint(&arg);
1579     else if (arg_match(&arg, &best_dl, argi))
1580       global->deadline = VPX_DL_BEST_QUALITY;
1581     else if (arg_match(&arg, &good_dl, argi))
1582       global->deadline = VPX_DL_GOOD_QUALITY;
1583     else if (arg_match(&arg, &rt_dl, argi))
1584       global->deadline = VPX_DL_REALTIME;
1585     else if (arg_match(&arg, &use_yv12, argi))
1586       global->use_i420 = 0;
1587     else if (arg_match(&arg, &use_i420, argi))
1588       global->use_i420 = 1;
1589     else if (arg_match(&arg, &quietarg, argi))
1590       global->quiet = 1;
1591     else if (arg_match(&arg, &verbosearg, argi))
1592       global->verbose = 1;
1593     else if (arg_match(&arg, &limit, argi))
1594       global->limit = arg_parse_uint(&arg);
1595     else if (arg_match(&arg, &skip, argi))
1596       global->skip_frames = arg_parse_uint(&arg);
1597     else if (arg_match(&arg, &psnrarg, argi))
1598       global->show_psnr = 1;
1599     else if (arg_match(&arg, &recontest, argi))
1600       global->test_decode = 1;
1601     else if (arg_match(&arg, &framerate, argi)) {
1602       global->framerate = arg_parse_rational(&arg);
1603       validate_positive_rational(arg.name, &global->framerate);
1604       global->have_framerate = 1;
1605     } else if (arg_match(&arg, &out_part, argi))
1606       global->out_part = 1;
1607     else if (arg_match(&arg, &debugmode, argi))
1608       global->debug = 1;
1609     else if (arg_match(&arg, &q_hist_n, argi))
1610       global->show_q_hist_buckets = arg_parse_uint(&arg);
1611     else if (arg_match(&arg, &rate_hist_n, argi))
1612       global->show_rate_hist_buckets = arg_parse_uint(&arg);
1613     else
1614       argj++;
1615   }
1616
1617   /* Validate global config */
1618
1619   if (global->pass) {
1620     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1621     if (global->pass > global->passes) {
1622       warn("Assuming --pass=%d implies --passes=%d\n",
1623            global->pass, global->pass);
1624       global->passes = global->pass;
1625     }
1626   }
1627 }
1628
1629
1630 void open_input_file(struct input_state *input) {
1631   unsigned int fourcc;
1632
1633   /* Parse certain options from the input file, if possible */
1634   input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1635                 : set_binary_mode(stdin);
1636
1637   if (!input->file)
1638     fatal("Failed to open input file");
1639
1640   /* For RAW input sources, these bytes will applied on the first frame
1641    *  in read_frame().
1642    */
1643   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1644   input->detect.position = 0;
1645
1646   if (input->detect.buf_read == 4
1647       && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1648     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0) {
1649       input->file_type = FILE_TYPE_Y4M;
1650       input->w = input->y4m.pic_w;
1651       input->h = input->y4m.pic_h;
1652       input->framerate.num = input->y4m.fps_n;
1653       input->framerate.den = input->y4m.fps_d;
1654       input->use_i420 = 0;
1655     } else
1656       fatal("Unsupported Y4M stream.");
1657   } else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
1658     input->file_type = FILE_TYPE_IVF;
1659     switch (fourcc) {
1660       case 0x32315659:
1661         input->use_i420 = 0;
1662         break;
1663       case 0x30323449:
1664         input->use_i420 = 1;
1665         break;
1666       default:
1667         fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1668     }
1669   } else {
1670     input->file_type = FILE_TYPE_RAW;
1671   }
1672 }
1673
1674
1675 static void close_input_file(struct input_state *input) {
1676   fclose(input->file);
1677   if (input->file_type == FILE_TYPE_Y4M)
1678     y4m_input_close(&input->y4m);
1679 }
1680
1681 static struct stream_state *new_stream(struct global_config *global,
1682                                        struct stream_state  *prev) {
1683   struct stream_state *stream;
1684
1685   stream = calloc(1, sizeof(*stream));
1686   if (!stream)
1687     fatal("Failed to allocate new stream.");
1688   if (prev) {
1689     memcpy(stream, prev, sizeof(*stream));
1690     stream->index++;
1691     prev->next = stream;
1692   } else {
1693     vpx_codec_err_t  res;
1694
1695     /* Populate encoder configuration */
1696     res = vpx_codec_enc_config_default(global->codec->iface(),
1697                                        &stream->config.cfg,
1698                                        global->usage);
1699     if (res)
1700       fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1701
1702     /* Change the default timebase to a high enough value so that the
1703      * encoder will always create strictly increasing timestamps.
1704      */
1705     stream->config.cfg.g_timebase.den = 1000;
1706
1707     /* Never use the library's default resolution, require it be parsed
1708      * from the file or set on the command line.
1709      */
1710     stream->config.cfg.g_w = 0;
1711     stream->config.cfg.g_h = 0;
1712
1713     /* Initialize remaining stream parameters */
1714     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1715     stream->config.write_webm = 1;
1716     stream->ebml.last_pts_ms = -1;
1717
1718     /* Allows removal of the application version from the EBML tags */
1719     stream->ebml.debug = global->debug;
1720   }
1721
1722   /* Output files must be specified for each stream */
1723   stream->config.out_fn = NULL;
1724
1725   stream->next = NULL;
1726   return stream;
1727 }
1728
1729
1730 static int parse_stream_params(struct global_config *global,
1731                                struct stream_state  *stream,
1732                                char **argv) {
1733   char                   **argi, **argj;
1734   struct arg               arg;
1735   static const arg_def_t **ctrl_args = no_args;
1736   static const int        *ctrl_args_map = NULL;
1737   struct stream_config    *config = &stream->config;
1738   int                      eos_mark_found = 0;
1739
1740   /* Handle codec specific options */
1741   if (global->codec->iface == vpx_codec_vp8_cx) {
1742     ctrl_args = vp8_args;
1743     ctrl_args_map = vp8_arg_ctrl_map;
1744   }
1745
1746   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1747     arg.argv_step = 1;
1748
1749     /* Once we've found an end-of-stream marker (--) we want to continue
1750      * shifting arguments but not consuming them.
1751      */
1752     if (eos_mark_found) {
1753       argj++;
1754       continue;
1755     } else if (!strcmp(*argj, "--")) {
1756       eos_mark_found = 1;
1757       continue;
1758     }
1759
1760     if (0);
1761     else if (arg_match(&arg, &outputfile, argi))
1762       config->out_fn = arg.val;
1763     else if (arg_match(&arg, &fpf_name, argi))
1764       config->stats_fn = arg.val;
1765     else if (arg_match(&arg, &use_ivf, argi))
1766       config->write_webm = 0;
1767     else if (arg_match(&arg, &threads, argi))
1768       config->cfg.g_threads = arg_parse_uint(&arg);
1769     else if (arg_match(&arg, &profile, argi))
1770       config->cfg.g_profile = arg_parse_uint(&arg);
1771     else if (arg_match(&arg, &width, argi))
1772       config->cfg.g_w = arg_parse_uint(&arg);
1773     else if (arg_match(&arg, &height, argi))
1774       config->cfg.g_h = arg_parse_uint(&arg);
1775     else if (arg_match(&arg, &stereo_mode, argi))
1776       config->stereo_fmt = arg_parse_enum_or_int(&arg);
1777     else if (arg_match(&arg, &timebase, argi)) {
1778       config->cfg.g_timebase = arg_parse_rational(&arg);
1779       validate_positive_rational(arg.name, &config->cfg.g_timebase);
1780     } else if (arg_match(&arg, &error_resilient, argi))
1781       config->cfg.g_error_resilient = arg_parse_uint(&arg);
1782     else if (arg_match(&arg, &lag_in_frames, argi))
1783       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1784     else if (arg_match(&arg, &dropframe_thresh, argi))
1785       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1786     else if (arg_match(&arg, &resize_allowed, argi))
1787       config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1788     else if (arg_match(&arg, &resize_up_thresh, argi))
1789       config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1790     else if (arg_match(&arg, &resize_down_thresh, argi))
1791       config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1792     else if (arg_match(&arg, &end_usage, argi))
1793       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1794     else if (arg_match(&arg, &target_bitrate, argi))
1795       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1796     else if (arg_match(&arg, &min_quantizer, argi))
1797       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1798     else if (arg_match(&arg, &max_quantizer, argi))
1799       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1800     else if (arg_match(&arg, &undershoot_pct, argi))
1801       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1802     else if (arg_match(&arg, &overshoot_pct, argi))
1803       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1804     else if (arg_match(&arg, &buf_sz, argi))
1805       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1806     else if (arg_match(&arg, &buf_initial_sz, argi))
1807       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1808     else if (arg_match(&arg, &buf_optimal_sz, argi))
1809       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1810     else if (arg_match(&arg, &bias_pct, argi)) {
1811       config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1812
1813       if (global->passes < 2)
1814         warn("option %s ignored in one-pass mode.\n", arg.name);
1815     } else if (arg_match(&arg, &minsection_pct, argi)) {
1816       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1817
1818       if (global->passes < 2)
1819         warn("option %s ignored in one-pass mode.\n", arg.name);
1820     } else if (arg_match(&arg, &maxsection_pct, argi)) {
1821       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1822
1823       if (global->passes < 2)
1824         warn("option %s ignored in one-pass mode.\n", arg.name);
1825     } else if (arg_match(&arg, &kf_min_dist, argi))
1826       config->cfg.kf_min_dist = arg_parse_uint(&arg);
1827     else if (arg_match(&arg, &kf_max_dist, argi)) {
1828       config->cfg.kf_max_dist = arg_parse_uint(&arg);
1829       config->have_kf_max_dist = 1;
1830     } else if (arg_match(&arg, &kf_disabled, argi))
1831       config->cfg.kf_mode = VPX_KF_DISABLED;
1832     else {
1833       int i, match = 0;
1834
1835       for (i = 0; ctrl_args[i]; i++) {
1836         if (arg_match(&arg, ctrl_args[i], argi)) {
1837           int j;
1838           match = 1;
1839
1840           /* Point either to the next free element or the first
1841           * instance of this control.
1842           */
1843           for (j = 0; j < config->arg_ctrl_cnt; j++)
1844             if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1845               break;
1846
1847           /* Update/insert */
1848           assert(j < ARG_CTRL_CNT_MAX);
1849           if (j < ARG_CTRL_CNT_MAX) {
1850             config->arg_ctrls[j][0] = ctrl_args_map[i];
1851             config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1852             if (j == config->arg_ctrl_cnt)
1853               config->arg_ctrl_cnt++;
1854           }
1855
1856         }
1857       }
1858
1859       if (!match)
1860         argj++;
1861     }
1862   }
1863
1864   return eos_mark_found;
1865 }
1866
1867
1868 #define FOREACH_STREAM(func)\
1869   do\
1870   {\
1871     struct stream_state  *stream;\
1872     \
1873     for(stream = streams; stream; stream = stream->next)\
1874       func;\
1875   }while(0)
1876
1877
1878 static void validate_stream_config(struct stream_state *stream) {
1879   struct stream_state *streami;
1880
1881   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1882     fatal("Stream %d: Specify stream dimensions with --width (-w) "
1883           " and --height (-h)", stream->index);
1884
1885   for (streami = stream; streami; streami = streami->next) {
1886     /* All streams require output files */
1887     if (!streami->config.out_fn)
1888       fatal("Stream %d: Output file is required (specify with -o)",
1889             streami->index);
1890
1891     /* Check for two streams outputting to the same file */
1892     if (streami != stream) {
1893       const char *a = stream->config.out_fn;
1894       const char *b = streami->config.out_fn;
1895       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1896         fatal("Stream %d: duplicate output file (from stream %d)",
1897               streami->index, stream->index);
1898     }
1899
1900     /* Check for two streams sharing a stats file. */
1901     if (streami != stream) {
1902       const char *a = stream->config.stats_fn;
1903       const char *b = streami->config.stats_fn;
1904       if (a && b && !strcmp(a, b))
1905         fatal("Stream %d: duplicate stats file (from stream %d)",
1906               streami->index, stream->index);
1907     }
1908   }
1909 }
1910
1911
1912 static void set_stream_dimensions(struct stream_state *stream,
1913                                   unsigned int w,
1914                                   unsigned int h) {
1915   if ((stream->config.cfg.g_w && stream->config.cfg.g_w != w)
1916       || (stream->config.cfg.g_h && stream->config.cfg.g_h != h))
1917     fatal("Stream %d: Resizing not yet supported", stream->index);
1918   stream->config.cfg.g_w = w;
1919   stream->config.cfg.g_h = h;
1920 }
1921
1922
1923 static void set_default_kf_interval(struct stream_state  *stream,
1924                                     struct global_config *global) {
1925   /* Use a max keyframe interval of 5 seconds, if none was
1926    * specified on the command line.
1927    */
1928   if (!stream->config.have_kf_max_dist) {
1929     double framerate = (double)global->framerate.num / global->framerate.den;
1930     if (framerate > 0.0)
1931       stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1932   }
1933 }
1934
1935
1936 static void show_stream_config(struct stream_state  *stream,
1937                                struct global_config *global,
1938                                struct input_state   *input) {
1939
1940 #define SHOW(field) \
1941   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
1942
1943   if (stream->index == 0) {
1944     fprintf(stderr, "Codec: %s\n",
1945             vpx_codec_iface_name(global->codec->iface()));
1946     fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
1947             input->use_i420 ? "I420" : "YV12");
1948   }
1949   if (stream->next || stream->index)
1950     fprintf(stderr, "\nStream Index: %d\n", stream->index);
1951   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1952   fprintf(stderr, "Encoder parameters:\n");
1953
1954   SHOW(g_usage);
1955   SHOW(g_threads);
1956   SHOW(g_profile);
1957   SHOW(g_w);
1958   SHOW(g_h);
1959   SHOW(g_timebase.num);
1960   SHOW(g_timebase.den);
1961   SHOW(g_error_resilient);
1962   SHOW(g_pass);
1963   SHOW(g_lag_in_frames);
1964   SHOW(rc_dropframe_thresh);
1965   SHOW(rc_resize_allowed);
1966   SHOW(rc_resize_up_thresh);
1967   SHOW(rc_resize_down_thresh);
1968   SHOW(rc_end_usage);
1969   SHOW(rc_target_bitrate);
1970   SHOW(rc_min_quantizer);
1971   SHOW(rc_max_quantizer);
1972   SHOW(rc_undershoot_pct);
1973   SHOW(rc_overshoot_pct);
1974   SHOW(rc_buf_sz);
1975   SHOW(rc_buf_initial_sz);
1976   SHOW(rc_buf_optimal_sz);
1977   SHOW(rc_2pass_vbr_bias_pct);
1978   SHOW(rc_2pass_vbr_minsection_pct);
1979   SHOW(rc_2pass_vbr_maxsection_pct);
1980   SHOW(kf_mode);
1981   SHOW(kf_min_dist);
1982   SHOW(kf_max_dist);
1983 }
1984
1985
1986 static void open_output_file(struct stream_state *stream,
1987                              struct global_config *global) {
1988   const char *fn = stream->config.out_fn;
1989
1990   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1991
1992   if (!stream->file)
1993     fatal("Failed to open output file");
1994
1995   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1996     fatal("WebM output to pipes not supported.");
1997
1998   if (stream->config.write_webm) {
1999     stream->ebml.stream = stream->file;
2000     write_webm_file_header(&stream->ebml, &stream->config.cfg,
2001                            &global->framerate,
2002                            stream->config.stereo_fmt);
2003   } else
2004     write_ivf_file_header(stream->file, &stream->config.cfg,
2005                           global->codec->fourcc, 0);
2006 }
2007
2008
2009 static void close_output_file(struct stream_state *stream,
2010                               unsigned int         fourcc) {
2011   if (stream->config.write_webm) {
2012     write_webm_file_footer(&stream->ebml, stream->hash);
2013     free(stream->ebml.cue_list);
2014     stream->ebml.cue_list = NULL;
2015   } else {
2016     if (!fseek(stream->file, 0, SEEK_SET))
2017       write_ivf_file_header(stream->file, &stream->config.cfg,
2018                             fourcc,
2019                             stream->frames_out);
2020   }
2021
2022   fclose(stream->file);
2023 }
2024
2025
2026 static void setup_pass(struct stream_state  *stream,
2027                        struct global_config *global,
2028                        int                   pass) {
2029   if (stream->config.stats_fn) {
2030     if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2031                          pass))
2032       fatal("Failed to open statistics store");
2033   } else {
2034     if (!stats_open_mem(&stream->stats, pass))
2035       fatal("Failed to open statistics store");
2036   }
2037
2038   stream->config.cfg.g_pass = global->passes == 2
2039                               ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
2040                             : VPX_RC_ONE_PASS;
2041   if (pass)
2042     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2043
2044   stream->cx_time = 0;
2045   stream->nbytes = 0;
2046   stream->frames_out = 0;
2047 }
2048
2049
2050 static void initialize_encoder(struct stream_state  *stream,
2051                                struct global_config *global) {
2052   int i;
2053   int flags = 0;
2054
2055   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2056   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2057
2058   /* Construct Encoder Context */
2059   vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
2060                      &stream->config.cfg, flags);
2061   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2062
2063   /* Note that we bypass the vpx_codec_control wrapper macro because
2064    * we're being clever to store the control IDs in an array. Real
2065    * applications will want to make use of the enumerations directly
2066    */
2067   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
2068     int ctrl = stream->config.arg_ctrls[i][0];
2069     int value = stream->config.arg_ctrls[i][1];
2070     if (vpx_codec_control_(&stream->encoder, ctrl, value))
2071       fprintf(stderr, "Error: Tried to set control %d = %d\n",
2072               ctrl, value);
2073
2074     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2075   }
2076
2077   if (global->test_decode) {
2078     int width, height;
2079
2080     vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
2081
2082     width = (stream->config.cfg.g_w + 15) & ~15;
2083     height = (stream->config.cfg.g_h + 15) & ~15;
2084     vpx_img_alloc(&stream->ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
2085     vpx_img_alloc(&stream->ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
2086     stream->ref_enc.frame_type = VP8_LAST_FRAME;
2087     stream->ref_dec.frame_type = VP8_LAST_FRAME;
2088   }
2089 }
2090
2091
2092 static void encode_frame(struct stream_state  *stream,
2093                          struct global_config *global,
2094                          struct vpx_image     *img,
2095                          unsigned int          frames_in) {
2096   vpx_codec_pts_t frame_start, next_frame_start;
2097   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2098   struct vpx_usec_timer timer;
2099
2100   frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2101                  * global->framerate.den)
2102                 / cfg->g_timebase.num / global->framerate.num;
2103   next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2104                       * global->framerate.den)
2105                      / cfg->g_timebase.num / global->framerate.num;
2106   vpx_usec_timer_start(&timer);
2107   vpx_codec_encode(&stream->encoder, img, frame_start,
2108                    (unsigned long)(next_frame_start - frame_start),
2109                    0, global->deadline);
2110   vpx_usec_timer_mark(&timer);
2111   stream->cx_time += vpx_usec_timer_elapsed(&timer);
2112   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2113                     stream->index);
2114 }
2115
2116
2117 static void update_quantizer_histogram(struct stream_state *stream) {
2118   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
2119     int q;
2120
2121     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2122     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2123     stream->counts[q]++;
2124   }
2125 }
2126
2127
2128 static void get_cx_data(struct stream_state  *stream,
2129                         struct global_config *global,
2130                         int                  *got_data) {
2131   const vpx_codec_cx_pkt_t *pkt;
2132   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2133   vpx_codec_iter_t iter = NULL;
2134
2135   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
2136     static size_t fsize = 0;
2137     static off_t ivf_header_pos = 0;
2138
2139     *got_data = 1;
2140
2141     switch (pkt->kind) {
2142       case VPX_CODEC_CX_FRAME_PKT:
2143         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2144           stream->frames_out++;
2145         }
2146         if (!global->quiet)
2147           fprintf(stderr, " %6luF",
2148                   (unsigned long)pkt->data.frame.sz);
2149
2150         update_rate_histogram(&stream->rate_hist, cfg, pkt);
2151         if (stream->config.write_webm) {
2152           /* Update the hash */
2153           if (!stream->ebml.debug)
2154             stream->hash = murmur(pkt->data.frame.buf,
2155                                   (int)pkt->data.frame.sz,
2156                                   stream->hash);
2157
2158           write_webm_block(&stream->ebml, cfg, pkt);
2159         } else {
2160           if (pkt->data.frame.partition_id <= 0) {
2161             ivf_header_pos = ftello(stream->file);
2162             fsize = pkt->data.frame.sz;
2163
2164             write_ivf_frame_header(stream->file, pkt);
2165           } else {
2166             fsize += pkt->data.frame.sz;
2167
2168             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2169               off_t currpos = ftello(stream->file);
2170               fseeko(stream->file, ivf_header_pos, SEEK_SET);
2171               write_ivf_frame_size(stream->file, fsize);
2172               fseeko(stream->file, currpos, SEEK_SET);
2173             }
2174           }
2175
2176           (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2177                         stream->file);
2178         }
2179         stream->nbytes += pkt->data.raw.sz;
2180
2181         if (global->test_decode) {
2182           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
2183                            pkt->data.frame.sz, NULL, 0);
2184           ctx_exit_on_error(&stream->decoder, "Failed to decode frame");
2185         }
2186         break;
2187       case VPX_CODEC_STATS_PKT:
2188         stream->frames_out++;
2189         fprintf(stderr, " %6luS",
2190                 (unsigned long)pkt->data.twopass_stats.sz);
2191         stats_write(&stream->stats,
2192                     pkt->data.twopass_stats.buf,
2193                     pkt->data.twopass_stats.sz);
2194         stream->nbytes += pkt->data.raw.sz;
2195         break;
2196       case VPX_CODEC_PSNR_PKT:
2197
2198         if (global->show_psnr) {
2199           int i;
2200
2201           stream->psnr_sse_total += pkt->data.psnr.sse[0];
2202           stream->psnr_samples_total += pkt->data.psnr.samples[0];
2203           for (i = 0; i < 4; i++) {
2204             if (!global->quiet)
2205               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
2206             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2207           }
2208           stream->psnr_count++;
2209         }
2210
2211         break;
2212       default:
2213         break;
2214     }
2215   }
2216 }
2217
2218
2219 static void show_psnr(struct stream_state  *stream) {
2220   int i;
2221   double ovpsnr;
2222
2223   if (!stream->psnr_count)
2224     return;
2225
2226   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2227   ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
2228                         (double)stream->psnr_sse_total);
2229   fprintf(stderr, " %.3f", ovpsnr);
2230
2231   for (i = 0; i < 4; i++) {
2232     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
2233   }
2234   fprintf(stderr, "\n");
2235 }
2236
2237
2238 float usec_to_fps(uint64_t usec, unsigned int frames) {
2239   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
2240 }
2241
2242
2243 static void test_decode(struct stream_state  *stream, unsigned int frames_in) {
2244   vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &stream->ref_enc);
2245   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
2246   vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &stream->ref_dec);
2247   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
2248
2249   if (!stream->mismatch_seen
2250       && !compare_img(&stream->ref_enc.img, &stream->ref_dec.img)) {
2251     /* TODO(jkoleszar): make fatal. */
2252     warn("Stream %d: Encode/decode mismatch on frame %d",
2253          stream->index, frames_in);
2254     stream->mismatch_seen = frames_in;
2255   }
2256 }
2257
2258 int main(int argc, const char **argv_) {
2259   int                    pass;
2260   vpx_image_t            raw;
2261   int                    frame_avail, got_data;
2262
2263   struct input_state       input = {0};
2264   struct global_config     global;
2265   struct stream_state     *streams = NULL;
2266   char                   **argv, **argi;
2267   unsigned long            cx_time = 0;
2268   int                      stream_cnt = 0;
2269
2270   exec_name = argv_[0];
2271
2272   if (argc < 3)
2273     usage_exit();
2274
2275   /* Setup default input stream settings */
2276   input.framerate.num = 30;
2277   input.framerate.den = 1;
2278   input.use_i420 = 1;
2279
2280   /* First parse the global configuration values, because we want to apply
2281    * other parameters on top of the default configuration provided by the
2282    * codec.
2283    */
2284   argv = argv_dup(argc - 1, argv_ + 1);
2285   parse_global_config(&global, argv);
2286
2287   {
2288     /* Now parse each stream's parameters. Using a local scope here
2289      * due to the use of 'stream' as loop variable in FOREACH_STREAM
2290      * loops
2291      */
2292     struct stream_state *stream = NULL;
2293
2294     do {
2295       stream = new_stream(&global, stream);
2296       stream_cnt++;
2297       if (!streams)
2298         streams = stream;
2299     } while (parse_stream_params(&global, stream, argv));
2300   }
2301
2302   /* Check for unrecognized options */
2303   for (argi = argv; *argi; argi++)
2304     if (argi[0][0] == '-' && argi[0][1])
2305       die("Error: Unrecognized option %s\n", *argi);
2306
2307   /* Handle non-option arguments */
2308   input.fn = argv[0];
2309
2310   if (!input.fn)
2311     usage_exit();
2312
2313   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2314     int frames_in = 0;
2315
2316     open_input_file(&input);
2317
2318     /* If the input file doesn't specify its w/h (raw files), try to get
2319      * the data from the first stream's configuration.
2320      */
2321     if (!input.w || !input.h)
2322       FOREACH_STREAM( {
2323       if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2324         input.w = stream->config.cfg.g_w;
2325         input.h = stream->config.cfg.g_h;
2326         break;
2327       }
2328     });
2329
2330     /* Update stream configurations from the input file's parameters */
2331     FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2332     FOREACH_STREAM(validate_stream_config(stream));
2333
2334     /* Ensure that --passes and --pass are consistent. If --pass is set and
2335      * --passes=2, ensure --fpf was set.
2336      */
2337     if (global.pass && global.passes == 2)
2338       FOREACH_STREAM( {
2339       if (!stream->config.stats_fn)
2340         die("Stream %d: Must specify --fpf when --pass=%d"
2341         " and --passes=2\n", stream->index, global.pass);
2342     });
2343
2344
2345     /* Use the frame rate from the file only if none was specified
2346      * on the command-line.
2347      */
2348     if (!global.have_framerate)
2349       global.framerate = input.framerate;
2350
2351     FOREACH_STREAM(set_default_kf_interval(stream, &global));
2352
2353     /* Show configuration */
2354     if (global.verbose && pass == 0)
2355       FOREACH_STREAM(show_stream_config(stream, &global, &input));
2356
2357     if (pass == (global.pass ? global.pass - 1 : 0)) {
2358       if (input.file_type == FILE_TYPE_Y4M)
2359         /*The Y4M reader does its own allocation.
2360           Just initialize this here to avoid problems if we never read any
2361            frames.*/
2362         memset(&raw, 0, sizeof(raw));
2363       else
2364         vpx_img_alloc(&raw,
2365                       input.use_i420 ? VPX_IMG_FMT_I420
2366                       : VPX_IMG_FMT_YV12,
2367                       input.w, input.h, 32);
2368
2369       FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2370                                          &stream->config.cfg,
2371                                          &global.framerate));
2372     }
2373
2374     FOREACH_STREAM(open_output_file(stream, &global));
2375     FOREACH_STREAM(setup_pass(stream, &global, pass));
2376     FOREACH_STREAM(initialize_encoder(stream, &global));
2377
2378     frame_avail = 1;
2379     got_data = 0;
2380
2381     while (frame_avail || got_data) {
2382       struct vpx_usec_timer timer;
2383
2384       if (!global.limit || frames_in < global.limit) {
2385         frame_avail = read_frame(&input, &raw);
2386
2387         if (frame_avail)
2388           frames_in++;
2389
2390         if (!global.quiet) {
2391           if (stream_cnt == 1)
2392             fprintf(stderr,
2393                     "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
2394                     pass + 1, global.passes, frames_in,
2395                     streams->frames_out, (int64_t)streams->nbytes);
2396           else
2397             fprintf(stderr,
2398                     "\rPass %d/%d frame %4d %7lu %s (%.2f fps)\033[K",
2399                     pass + 1, global.passes, frames_in,
2400                     cx_time > 9999999 ? cx_time / 1000 : cx_time,
2401                     cx_time > 9999999 ? "ms" : "us",
2402                     usec_to_fps(cx_time, frames_in));
2403         }
2404
2405       } else
2406         frame_avail = 0;
2407
2408       if (frames_in > global.skip_frames) {
2409         vpx_usec_timer_start(&timer);
2410         FOREACH_STREAM(encode_frame(stream, &global,
2411                                     frame_avail ? &raw : NULL,
2412                                     frames_in));
2413         vpx_usec_timer_mark(&timer);
2414         cx_time += (unsigned long)vpx_usec_timer_elapsed(&timer);
2415
2416         FOREACH_STREAM(update_quantizer_histogram(stream));
2417
2418         got_data = 0;
2419         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2420
2421         if (global.test_decode)
2422           FOREACH_STREAM(test_decode(stream, frames_in));
2423       }
2424
2425       fflush(stdout);
2426     }
2427
2428     if (stream_cnt > 1)
2429       fprintf(stderr, "\n");
2430
2431     if (!global.quiet)
2432       FOREACH_STREAM(fprintf(
2433                        stderr,
2434                        "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2435                        " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2436                        global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2437                        frames_in ? (unsigned long)(stream->nbytes * 8 / frames_in) : 0,
2438                        frames_in ? (int64_t)stream->nbytes * 8
2439                        * (int64_t)global.framerate.num / global.framerate.den
2440                        / frames_in
2441                        : 0,
2442                        stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2443                        stream->cx_time > 9999999 ? "ms" : "us",
2444                        usec_to_fps(stream->cx_time, frames_in));
2445                     );
2446
2447     if (global.show_psnr)
2448       FOREACH_STREAM(show_psnr(stream));
2449
2450     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2451
2452     if (global.test_decode) {
2453       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2454       FOREACH_STREAM(vpx_img_free(&stream->ref_enc.img));
2455       FOREACH_STREAM(vpx_img_free(&stream->ref_dec.img));
2456     }
2457
2458     close_input_file(&input);
2459
2460     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2461
2462     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2463
2464     if (global.pass)
2465       break;
2466   }
2467
2468   if (global.show_q_hist_buckets)
2469     FOREACH_STREAM(show_q_histogram(stream->counts,
2470                                     global.show_q_hist_buckets));
2471
2472   if (global.show_rate_hist_buckets)
2473     FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2474                                        &stream->config.cfg,
2475                                        global.show_rate_hist_buckets));
2476   FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2477
2478 #if CONFIG_INTERNAL_STATS
2479   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2480    * to match some existing utilities.
2481    */
2482   FOREACH_STREAM({
2483     FILE *f = fopen("opsnr.stt", "a");
2484     if (stream->mismatch_seen) {
2485       fprintf(f, "First mismatch occurred in frame %d\n",
2486               stream->mismatch_seen);
2487     } else {
2488       fprintf(f, "No mismatch detected in recon buffers\n");
2489     }
2490     fclose(f);
2491   });
2492 #endif
2493
2494   vpx_img_free(&raw);
2495   free(argv);
2496   free(streams);
2497   return EXIT_SUCCESS;
2498 }