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