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