WebM VP8 Codec SDK
vpxenc
00001 /*
00002  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
00003  *
00004  *  Use of this source code is governed by a BSD-style license
00005  *  that can be found in the LICENSE file in the root of the source
00006  *  tree. An additional intellectual property rights grant can be found
00007  *  in the file PATENTS.  All contributing project authors may
00008  *  be found in the AUTHORS file in the root of the source tree.
00009  */
00010 
00011 #include "vpx_config.h"
00012 
00013 #if defined(_WIN32) || defined(__OS2__) || !CONFIG_OS_SUPPORT
00014 #define USE_POSIX_MMAP 0
00015 #else
00016 #define USE_POSIX_MMAP 1
00017 #endif
00018 
00019 #include <stdio.h>
00020 #include <stdlib.h>
00021 #include <stdarg.h>
00022 #include <string.h>
00023 #include <limits.h>
00024 #include <assert.h>
00025 #include "vpx/vpx_encoder.h"
00026 #if CONFIG_DECODERS
00027 #include "vpx/vpx_decoder.h"
00028 #endif
00029 #if USE_POSIX_MMAP
00030 #include <sys/types.h>
00031 #include <sys/stat.h>
00032 #include <sys/mman.h>
00033 #include <fcntl.h>
00034 #include <unistd.h>
00035 #endif
00036 
00037 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
00038 #include "vpx/vp8cx.h"
00039 #endif
00040 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
00041 #include "vpx/vp8dx.h"
00042 #endif
00043 
00044 #include "vpx_ports/mem_ops.h"
00045 #include "vpx_ports/vpx_timer.h"
00046 #include "tools_common.h"
00047 #include "y4minput.h"
00048 #include "libmkv/EbmlWriter.h"
00049 #include "libmkv/EbmlIDs.h"
00050 #include "third_party/libyuv/include/libyuv/scale.h"
00051 
00052 /* Need special handling of these functions on Windows */
00053 #if defined(_MSC_VER)
00054 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
00055 typedef __int64 off_t;
00056 #define fseeko _fseeki64
00057 #define ftello _ftelli64
00058 #elif defined(_WIN32)
00059 /* MinGW defines off_t as long
00060    and uses f{seek,tell}o64/off64_t for large files */
00061 #define fseeko fseeko64
00062 #define ftello ftello64
00063 #define off_t off64_t
00064 #endif
00065 
00066 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
00067 
00068 /* We should use 32-bit file operations in WebM file format
00069  * when building ARM executable file (.axf) with RVCT */
00070 #if !CONFIG_OS_SUPPORT
00071 typedef long off_t;
00072 #define fseeko fseek
00073 #define ftello ftell
00074 #endif
00075 
00076 /* Swallow warnings about unused results of fread/fwrite */
00077 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
00078                          FILE *stream) {
00079   return fread(ptr, size, nmemb, stream);
00080 }
00081 #define fread wrap_fread
00082 
00083 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
00084                           FILE *stream) {
00085   return fwrite(ptr, size, nmemb, stream);
00086 }
00087 #define fwrite wrap_fwrite
00088 
00089 
00090 static const char *exec_name;
00091 
00092 #define VP8_FOURCC (0x30385056)
00093 #define VP9_FOURCC (0x30395056)
00094 static const struct codec_item {
00095   char const              *name;
00096   const vpx_codec_iface_t *(*iface)(void);
00097   const vpx_codec_iface_t *(*dx_iface)(void);
00098   unsigned int             fourcc;
00099 } codecs[] = {
00100 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
00101   {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
00102 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
00103   {"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
00104 #endif
00105 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
00106   {"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
00107 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
00108   {"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
00109 #endif
00110 };
00111 
00112 static void usage_exit();
00113 
00114 #define LOG_ERROR(label) do \
00115   {\
00116     const char *l=label;\
00117     va_list ap;\
00118     va_start(ap, fmt);\
00119     if(l)\
00120       fprintf(stderr, "%s: ", l);\
00121     vfprintf(stderr, fmt, ap);\
00122     fprintf(stderr, "\n");\
00123     va_end(ap);\
00124   } while(0)
00125 
00126 void die(const char *fmt, ...) {
00127   LOG_ERROR(NULL);
00128   usage_exit();
00129 }
00130 
00131 
00132 void fatal(const char *fmt, ...) {
00133   LOG_ERROR("Fatal");
00134   exit(EXIT_FAILURE);
00135 }
00136 
00137 
00138 void warn(const char *fmt, ...) {
00139   LOG_ERROR("Warning");
00140 }
00141 
00142 
00143 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
00144                                    const char *s, va_list ap) {
00145   if (ctx->err) {
00146     const char *detail = vpx_codec_error_detail(ctx);
00147 
00148     vfprintf(stderr, s, ap);
00149     fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
00150 
00151     if (detail)
00152       fprintf(stderr, "    %s\n", detail);
00153 
00154     if (fatal)
00155       exit(EXIT_FAILURE);
00156   }
00157 }
00158 
00159 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
00160   va_list ap;
00161 
00162   va_start(ap, s);
00163   warn_or_exit_on_errorv(ctx, 1, s, ap);
00164   va_end(ap);
00165 }
00166 
00167 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
00168                                   const char *s, ...) {
00169   va_list ap;
00170 
00171   va_start(ap, s);
00172   warn_or_exit_on_errorv(ctx, fatal, s, ap);
00173   va_end(ap);
00174 }
00175 
00176 /* This structure is used to abstract the different ways of handling
00177  * first pass statistics.
00178  */
00179 typedef struct {
00180   vpx_fixed_buf_t buf;
00181   int             pass;
00182   FILE           *file;
00183   char           *buf_ptr;
00184   size_t          buf_alloc_sz;
00185 } stats_io_t;
00186 
00187 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
00188   int res;
00189 
00190   stats->pass = pass;
00191 
00192   if (pass == 0) {
00193     stats->file = fopen(fpf, "wb");
00194     stats->buf.sz = 0;
00195     stats->buf.buf = NULL,
00196                res = (stats->file != NULL);
00197   } else {
00198 #if 0
00199 #elif USE_POSIX_MMAP
00200     struct stat stat_buf;
00201     int fd;
00202 
00203     fd = open(fpf, O_RDONLY);
00204     stats->file = fdopen(fd, "rb");
00205     fstat(fd, &stat_buf);
00206     stats->buf.sz = stat_buf.st_size;
00207     stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
00208                           fd, 0);
00209     res = (stats->buf.buf != NULL);
00210 #else
00211     size_t nbytes;
00212 
00213     stats->file = fopen(fpf, "rb");
00214 
00215     if (fseek(stats->file, 0, SEEK_END))
00216       fatal("First-pass stats file must be seekable!");
00217 
00218     stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
00219     rewind(stats->file);
00220 
00221     stats->buf.buf = malloc(stats->buf_alloc_sz);
00222 
00223     if (!stats->buf.buf)
00224       fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
00225             (unsigned long)stats->buf_alloc_sz);
00226 
00227     nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
00228     res = (nbytes == stats->buf.sz);
00229 #endif
00230   }
00231 
00232   return res;
00233 }
00234 
00235 int stats_open_mem(stats_io_t *stats, int pass) {
00236   int res;
00237   stats->pass = pass;
00238 
00239   if (!pass) {
00240     stats->buf.sz = 0;
00241     stats->buf_alloc_sz = 64 * 1024;
00242     stats->buf.buf = malloc(stats->buf_alloc_sz);
00243   }
00244 
00245   stats->buf_ptr = stats->buf.buf;
00246   res = (stats->buf.buf != NULL);
00247   return res;
00248 }
00249 
00250 
00251 void stats_close(stats_io_t *stats, int last_pass) {
00252   if (stats->file) {
00253     if (stats->pass == last_pass) {
00254 #if 0
00255 #elif USE_POSIX_MMAP
00256       munmap(stats->buf.buf, stats->buf.sz);
00257 #else
00258       free(stats->buf.buf);
00259 #endif
00260     }
00261 
00262     fclose(stats->file);
00263     stats->file = NULL;
00264   } else {
00265     if (stats->pass == last_pass)
00266       free(stats->buf.buf);
00267   }
00268 }
00269 
00270 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
00271   if (stats->file) {
00272     (void) fwrite(pkt, 1, len, stats->file);
00273   } else {
00274     if (stats->buf.sz + len > stats->buf_alloc_sz) {
00275       size_t  new_sz = stats->buf_alloc_sz + 64 * 1024;
00276       char   *new_ptr = realloc(stats->buf.buf, new_sz);
00277 
00278       if (new_ptr) {
00279         stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
00280         stats->buf.buf = new_ptr;
00281         stats->buf_alloc_sz = new_sz;
00282       } else
00283         fatal("Failed to realloc firstpass stats buffer.");
00284     }
00285 
00286     memcpy(stats->buf_ptr, pkt, len);
00287     stats->buf.sz += len;
00288     stats->buf_ptr += len;
00289   }
00290 }
00291 
00292 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
00293   return stats->buf;
00294 }
00295 
00296 /* Stereo 3D packed frame format */
00297 typedef enum stereo_format {
00298   STEREO_FORMAT_MONO       = 0,
00299   STEREO_FORMAT_LEFT_RIGHT = 1,
00300   STEREO_FORMAT_BOTTOM_TOP = 2,
00301   STEREO_FORMAT_TOP_BOTTOM = 3,
00302   STEREO_FORMAT_RIGHT_LEFT = 11
00303 } stereo_format_t;
00304 
00305 enum video_file_type {
00306   FILE_TYPE_RAW,
00307   FILE_TYPE_IVF,
00308   FILE_TYPE_Y4M
00309 };
00310 
00311 struct detect_buffer {
00312   char buf[4];
00313   size_t buf_read;
00314   size_t position;
00315 };
00316 
00317 
00318 struct input_state {
00319   char                 *fn;
00320   FILE                 *file;
00321   off_t                 length;
00322   y4m_input             y4m;
00323   struct detect_buffer  detect;
00324   enum video_file_type  file_type;
00325   unsigned int          w;
00326   unsigned int          h;
00327   struct vpx_rational   framerate;
00328   int                   use_i420;
00329 };
00330 
00331 
00332 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
00333 static int read_frame(struct input_state *input, vpx_image_t *img) {
00334   FILE *f = input->file;
00335   enum video_file_type file_type = input->file_type;
00336   y4m_input *y4m = &input->y4m;
00337   struct detect_buffer *detect = &input->detect;
00338   int plane = 0;
00339   int shortread = 0;
00340 
00341   if (file_type == FILE_TYPE_Y4M) {
00342     if (y4m_input_fetch_frame(y4m, f, img) < 1)
00343       return 0;
00344   } else {
00345     if (file_type == FILE_TYPE_IVF) {
00346       char junk[IVF_FRAME_HDR_SZ];
00347 
00348       /* Skip the frame header. We know how big the frame should be. See
00349        * write_ivf_frame_header() for documentation on the frame header
00350        * layout.
00351        */
00352       (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
00353     }
00354 
00355     for (plane = 0; plane < 3; plane++) {
00356       unsigned char *ptr;
00357       int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
00358       int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
00359       int r;
00360 
00361       /* Determine the correct plane based on the image format. The for-loop
00362        * always counts in Y,U,V order, but this may not match the order of
00363        * the data on disk.
00364        */
00365       switch (plane) {
00366         case 1:
00367           ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
00368           break;
00369         case 2:
00370           ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
00371           break;
00372         default:
00373           ptr = img->planes[plane];
00374       }
00375 
00376       for (r = 0; r < h; r++) {
00377         size_t needed = w;
00378         size_t buf_position = 0;
00379         const size_t left = detect->buf_read - detect->position;
00380         if (left > 0) {
00381           const size_t more = (left < needed) ? left : needed;
00382           memcpy(ptr, detect->buf + detect->position, more);
00383           buf_position = more;
00384           needed -= more;
00385           detect->position += more;
00386         }
00387         if (needed > 0) {
00388           shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
00389         }
00390 
00391         ptr += img->stride[plane];
00392       }
00393     }
00394   }
00395 
00396   return !shortread;
00397 }
00398 
00399 
00400 unsigned int file_is_y4m(FILE      *infile,
00401                          y4m_input *y4m,
00402                          char       detect[4]) {
00403   if (memcmp(detect, "YUV4", 4) == 0) {
00404     return 1;
00405   }
00406   return 0;
00407 }
00408 
00409 #define IVF_FILE_HDR_SZ (32)
00410 unsigned int file_is_ivf(struct input_state *input,
00411                          unsigned int *fourcc) {
00412   char raw_hdr[IVF_FILE_HDR_SZ];
00413   int is_ivf = 0;
00414   FILE *infile = input->file;
00415   unsigned int *width = &input->w;
00416   unsigned int *height = &input->h;
00417   struct detect_buffer *detect = &input->detect;
00418 
00419   if (memcmp(detect->buf, "DKIF", 4) != 0)
00420     return 0;
00421 
00422   /* See write_ivf_file_header() for more documentation on the file header
00423    * layout.
00424    */
00425   if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
00426       == IVF_FILE_HDR_SZ - 4) {
00427     {
00428       is_ivf = 1;
00429 
00430       if (mem_get_le16(raw_hdr + 4) != 0)
00431         warn("Unrecognized IVF version! This file may not decode "
00432              "properly.");
00433 
00434       *fourcc = mem_get_le32(raw_hdr + 8);
00435     }
00436   }
00437 
00438   if (is_ivf) {
00439     *width = mem_get_le16(raw_hdr + 12);
00440     *height = mem_get_le16(raw_hdr + 14);
00441     detect->position = 4;
00442   }
00443 
00444   return is_ivf;
00445 }
00446 
00447 
00448 static void write_ivf_file_header(FILE *outfile,
00449                                   const vpx_codec_enc_cfg_t *cfg,
00450                                   unsigned int fourcc,
00451                                   int frame_cnt) {
00452   char header[32];
00453 
00454   if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
00455     return;
00456 
00457   header[0] = 'D';
00458   header[1] = 'K';
00459   header[2] = 'I';
00460   header[3] = 'F';
00461   mem_put_le16(header + 4,  0);                 /* version */
00462   mem_put_le16(header + 6,  32);                /* headersize */
00463   mem_put_le32(header + 8,  fourcc);            /* headersize */
00464   mem_put_le16(header + 12, cfg->g_w);          /* width */
00465   mem_put_le16(header + 14, cfg->g_h);          /* height */
00466   mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
00467   mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
00468   mem_put_le32(header + 24, frame_cnt);         /* length */
00469   mem_put_le32(header + 28, 0);                 /* unused */
00470 
00471   (void) fwrite(header, 1, 32, outfile);
00472 }
00473 
00474 
00475 static void write_ivf_frame_header(FILE *outfile,
00476                                    const vpx_codec_cx_pkt_t *pkt) {
00477   char             header[12];
00478   vpx_codec_pts_t  pts;
00479 
00480   if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
00481     return;
00482 
00483   pts = pkt->data.frame.pts;
00484   mem_put_le32(header, (int)pkt->data.frame.sz);
00485   mem_put_le32(header + 4, pts & 0xFFFFFFFF);
00486   mem_put_le32(header + 8, pts >> 32);
00487 
00488   (void) fwrite(header, 1, 12, outfile);
00489 }
00490 
00491 static void write_ivf_frame_size(FILE *outfile, size_t size) {
00492   char             header[4];
00493   mem_put_le32(header, (int)size);
00494   (void) fwrite(header, 1, 4, outfile);
00495 }
00496 
00497 
00498 typedef off_t EbmlLoc;
00499 
00500 
00501 struct cue_entry {
00502   unsigned int time;
00503   uint64_t     loc;
00504 };
00505 
00506 
00507 struct EbmlGlobal {
00508   int debug;
00509 
00510   FILE    *stream;
00511   int64_t last_pts_ms;
00512   vpx_rational_t  framerate;
00513 
00514   /* These pointers are to the start of an element */
00515   off_t    position_reference;
00516   off_t    seek_info_pos;
00517   off_t    segment_info_pos;
00518   off_t    track_pos;
00519   off_t    cue_pos;
00520   off_t    cluster_pos;
00521 
00522   /* This pointer is to a specific element to be serialized */
00523   off_t    track_id_pos;
00524 
00525   /* These pointers are to the size field of the element */
00526   EbmlLoc  startSegment;
00527   EbmlLoc  startCluster;
00528 
00529   uint32_t cluster_timecode;
00530   int      cluster_open;
00531 
00532   struct cue_entry *cue_list;
00533   unsigned int      cues;
00534 
00535 };
00536 
00537 
00538 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
00539   (void) fwrite(buffer_in, 1, len, glob->stream);
00540 }
00541 
00542 #define WRITE_BUFFER(s) \
00543   for(i = len-1; i>=0; i--)\
00544   { \
00545     x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
00546     Ebml_Write(glob, &x, 1); \
00547   }
00548 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
00549   char x;
00550   int i;
00551 
00552   /* buffer_size:
00553    * 1 - int8_t;
00554    * 2 - int16_t;
00555    * 3 - int32_t;
00556    * 4 - int64_t;
00557    */
00558   switch (buffer_size) {
00559     case 1:
00560       WRITE_BUFFER(int8_t)
00561       break;
00562     case 2:
00563       WRITE_BUFFER(int16_t)
00564       break;
00565     case 4:
00566       WRITE_BUFFER(int32_t)
00567       break;
00568     case 8:
00569       WRITE_BUFFER(int64_t)
00570       break;
00571     default:
00572       break;
00573   }
00574 }
00575 #undef WRITE_BUFFER
00576 
00577 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
00578  * one, but not a 32 bit one.
00579  */
00580 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
00581   unsigned char sizeSerialized = 4 | 0x80;
00582   Ebml_WriteID(glob, class_id);
00583   Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
00584   Ebml_Serialize(glob, &ui, sizeof(ui), 4);
00585 }
00586 
00587 
00588 static void
00589 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
00590                      unsigned long class_id) {
00591   /* todo this is always taking 8 bytes, this may need later optimization */
00592   /* this is a key that says length unknown */
00593   uint64_t unknownLen = LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
00594 
00595   Ebml_WriteID(glob, class_id);
00596   *ebmlLoc = ftello(glob->stream);
00597   Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
00598 }
00599 
00600 static void
00601 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
00602   off_t pos;
00603   uint64_t size;
00604 
00605   /* Save the current stream pointer */
00606   pos = ftello(glob->stream);
00607 
00608   /* Calculate the size of this element */
00609   size = pos - *ebmlLoc - 8;
00610   size |= LITERALU64(0x01000000, 0x00000000);
00611 
00612   /* Seek back to the beginning of the element and write the new size */
00613   fseeko(glob->stream, *ebmlLoc, SEEK_SET);
00614   Ebml_Serialize(glob, &size, sizeof(size), 8);
00615 
00616   /* Reset the stream pointer */
00617   fseeko(glob->stream, pos, SEEK_SET);
00618 }
00619 
00620 
00621 static void
00622 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
00623   uint64_t offset = pos - ebml->position_reference;
00624   EbmlLoc start;
00625   Ebml_StartSubElement(ebml, &start, Seek);
00626   Ebml_SerializeBinary(ebml, SeekID, id);
00627   Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
00628   Ebml_EndSubElement(ebml, &start);
00629 }
00630 
00631 
00632 static void
00633 write_webm_seek_info(EbmlGlobal *ebml) {
00634 
00635   off_t pos;
00636 
00637   /* Save the current stream pointer */
00638   pos = ftello(ebml->stream);
00639 
00640   if (ebml->seek_info_pos)
00641     fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
00642   else
00643     ebml->seek_info_pos = pos;
00644 
00645   {
00646     EbmlLoc start;
00647 
00648     Ebml_StartSubElement(ebml, &start, SeekHead);
00649     write_webm_seek_element(ebml, Tracks, ebml->track_pos);
00650     write_webm_seek_element(ebml, Cues,   ebml->cue_pos);
00651     write_webm_seek_element(ebml, Info,   ebml->segment_info_pos);
00652     Ebml_EndSubElement(ebml, &start);
00653   }
00654   {
00655     /* segment info */
00656     EbmlLoc startInfo;
00657     uint64_t frame_time;
00658     char version_string[64];
00659 
00660     /* Assemble version string */
00661     if (ebml->debug)
00662       strcpy(version_string, "vpxenc");
00663     else {
00664       strcpy(version_string, "vpxenc ");
00665       strncat(version_string,
00666               vpx_codec_version_str(),
00667               sizeof(version_string) - 1 - strlen(version_string));
00668     }
00669 
00670     frame_time = (uint64_t)1000 * ebml->framerate.den
00671                  / ebml->framerate.num;
00672     ebml->segment_info_pos = ftello(ebml->stream);
00673     Ebml_StartSubElement(ebml, &startInfo, Info);
00674     Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
00675     Ebml_SerializeFloat(ebml, Segment_Duration,
00676                         (double)(ebml->last_pts_ms + frame_time));
00677     Ebml_SerializeString(ebml, 0x4D80, version_string);
00678     Ebml_SerializeString(ebml, 0x5741, version_string);
00679     Ebml_EndSubElement(ebml, &startInfo);
00680   }
00681 }
00682 
00683 
00684 static void
00685 write_webm_file_header(EbmlGlobal                *glob,
00686                        const vpx_codec_enc_cfg_t *cfg,
00687                        const struct vpx_rational *fps,
00688                        stereo_format_t            stereo_fmt,
00689                        unsigned int               fourcc) {
00690   {
00691     EbmlLoc start;
00692     Ebml_StartSubElement(glob, &start, EBML);
00693     Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
00694     Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
00695     Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
00696     Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
00697     Ebml_SerializeString(glob, DocType, "webm");
00698     Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
00699     Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
00700     Ebml_EndSubElement(glob, &start);
00701   }
00702   {
00703     Ebml_StartSubElement(glob, &glob->startSegment, Segment);
00704     glob->position_reference = ftello(glob->stream);
00705     glob->framerate = *fps;
00706     write_webm_seek_info(glob);
00707 
00708     {
00709       EbmlLoc trackStart;
00710       glob->track_pos = ftello(glob->stream);
00711       Ebml_StartSubElement(glob, &trackStart, Tracks);
00712       {
00713         unsigned int trackNumber = 1;
00714         uint64_t     trackID = 0;
00715 
00716         EbmlLoc start;
00717         Ebml_StartSubElement(glob, &start, TrackEntry);
00718         Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
00719         glob->track_id_pos = ftello(glob->stream);
00720         Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
00721         Ebml_SerializeUnsigned(glob, TrackType, 1);
00722         Ebml_SerializeString(glob, CodecID,
00723                              fourcc == VP8_FOURCC ? "V_VP8" : "V_VP9");
00724         {
00725           unsigned int pixelWidth = cfg->g_w;
00726           unsigned int pixelHeight = cfg->g_h;
00727           float        frameRate   = (float)fps->num / (float)fps->den;
00728 
00729           EbmlLoc videoStart;
00730           Ebml_StartSubElement(glob, &videoStart, Video);
00731           Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
00732           Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
00733           Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
00734           Ebml_SerializeFloat(glob, FrameRate, frameRate);
00735           Ebml_EndSubElement(glob, &videoStart);
00736         }
00737         Ebml_EndSubElement(glob, &start); /* Track Entry */
00738       }
00739       Ebml_EndSubElement(glob, &trackStart);
00740     }
00741     /* segment element is open */
00742   }
00743 }
00744 
00745 
00746 static void
00747 write_webm_block(EbmlGlobal                *glob,
00748                  const vpx_codec_enc_cfg_t *cfg,
00749                  const vpx_codec_cx_pkt_t  *pkt) {
00750   unsigned long  block_length;
00751   unsigned char  track_number;
00752   unsigned short block_timecode = 0;
00753   unsigned char  flags;
00754   int64_t        pts_ms;
00755   int            start_cluster = 0, is_keyframe;
00756 
00757   /* Calculate the PTS of this frame in milliseconds */
00758   pts_ms = pkt->data.frame.pts * 1000
00759            * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
00760   if (pts_ms <= glob->last_pts_ms)
00761     pts_ms = glob->last_pts_ms + 1;
00762   glob->last_pts_ms = pts_ms;
00763 
00764   /* Calculate the relative time of this block */
00765   if (pts_ms - glob->cluster_timecode > SHRT_MAX)
00766     start_cluster = 1;
00767   else
00768     block_timecode = (unsigned short)pts_ms - glob->cluster_timecode;
00769 
00770   is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
00771   if (start_cluster || is_keyframe) {
00772     if (glob->cluster_open)
00773       Ebml_EndSubElement(glob, &glob->startCluster);
00774 
00775     /* Open the new cluster */
00776     block_timecode = 0;
00777     glob->cluster_open = 1;
00778     glob->cluster_timecode = (uint32_t)pts_ms;
00779     glob->cluster_pos = ftello(glob->stream);
00780     Ebml_StartSubElement(glob, &glob->startCluster, Cluster); /* cluster */
00781     Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
00782 
00783     /* Save a cue point if this is a keyframe. */
00784     if (is_keyframe) {
00785       struct cue_entry *cue, *new_cue_list;
00786 
00787       new_cue_list = realloc(glob->cue_list,
00788                              (glob->cues + 1) * sizeof(struct cue_entry));
00789       if (new_cue_list)
00790         glob->cue_list = new_cue_list;
00791       else
00792         fatal("Failed to realloc cue list.");
00793 
00794       cue = &glob->cue_list[glob->cues];
00795       cue->time = glob->cluster_timecode;
00796       cue->loc = glob->cluster_pos;
00797       glob->cues++;
00798     }
00799   }
00800 
00801   /* Write the Simple Block */
00802   Ebml_WriteID(glob, SimpleBlock);
00803 
00804   block_length = (unsigned long)pkt->data.frame.sz + 4;
00805   block_length |= 0x10000000;
00806   Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
00807 
00808   track_number = 1;
00809   track_number |= 0x80;
00810   Ebml_Write(glob, &track_number, 1);
00811 
00812   Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
00813 
00814   flags = 0;
00815   if (is_keyframe)
00816     flags |= 0x80;
00817   if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
00818     flags |= 0x08;
00819   Ebml_Write(glob, &flags, 1);
00820 
00821   Ebml_Write(glob, pkt->data.frame.buf, (unsigned long)pkt->data.frame.sz);
00822 }
00823 
00824 
00825 static void
00826 write_webm_file_footer(EbmlGlobal *glob, long hash) {
00827 
00828   if (glob->cluster_open)
00829     Ebml_EndSubElement(glob, &glob->startCluster);
00830 
00831   {
00832     EbmlLoc start;
00833     unsigned int i;
00834 
00835     glob->cue_pos = ftello(glob->stream);
00836     Ebml_StartSubElement(glob, &start, Cues);
00837     for (i = 0; i < glob->cues; i++) {
00838       struct cue_entry *cue = &glob->cue_list[i];
00839       EbmlLoc start;
00840 
00841       Ebml_StartSubElement(glob, &start, CuePoint);
00842       {
00843         EbmlLoc start;
00844 
00845         Ebml_SerializeUnsigned(glob, CueTime, cue->time);
00846 
00847         Ebml_StartSubElement(glob, &start, CueTrackPositions);
00848         Ebml_SerializeUnsigned(glob, CueTrack, 1);
00849         Ebml_SerializeUnsigned64(glob, CueClusterPosition,
00850                                  cue->loc - glob->position_reference);
00851         Ebml_EndSubElement(glob, &start);
00852       }
00853       Ebml_EndSubElement(glob, &start);
00854     }
00855     Ebml_EndSubElement(glob, &start);
00856   }
00857 
00858   Ebml_EndSubElement(glob, &glob->startSegment);
00859 
00860   /* Patch up the seek info block */
00861   write_webm_seek_info(glob);
00862 
00863   /* Patch up the track id */
00864   fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
00865   Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
00866 
00867   fseeko(glob->stream, 0, SEEK_END);
00868 }
00869 
00870 
00871 /* Murmur hash derived from public domain reference implementation at
00872  *   http:// sites.google.com/site/murmurhash/
00873  */
00874 static unsigned int murmur(const void *key, int len, unsigned int seed) {
00875   const unsigned int m = 0x5bd1e995;
00876   const int r = 24;
00877 
00878   unsigned int h = seed ^ len;
00879 
00880   const unsigned char *data = (const unsigned char *)key;
00881 
00882   while (len >= 4) {
00883     unsigned int k;
00884 
00885     k  = data[0];
00886     k |= data[1] << 8;
00887     k |= data[2] << 16;
00888     k |= data[3] << 24;
00889 
00890     k *= m;
00891     k ^= k >> r;
00892     k *= m;
00893 
00894     h *= m;
00895     h ^= k;
00896 
00897     data += 4;
00898     len -= 4;
00899   }
00900 
00901   switch (len) {
00902     case 3:
00903       h ^= data[2] << 16;
00904     case 2:
00905       h ^= data[1] << 8;
00906     case 1:
00907       h ^= data[0];
00908       h *= m;
00909   };
00910 
00911   h ^= h >> 13;
00912   h *= m;
00913   h ^= h >> 15;
00914 
00915   return h;
00916 }
00917 
00918 #include "math.h"
00919 #define MAX_PSNR 100
00920 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
00921   double psnr;
00922 
00923   if ((double)Mse > 0.0)
00924     psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
00925   else
00926     psnr = MAX_PSNR;      /* Limit to prevent / 0 */
00927 
00928   if (psnr > MAX_PSNR)
00929     psnr = MAX_PSNR;
00930 
00931   return psnr;
00932 }
00933 
00934 
00935 #include "args.h"
00936 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
00937                                            "Debug mode (makes output deterministic)");
00938 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
00939                                             "Output filename");
00940 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
00941                                           "Input file is YV12 ");
00942 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
00943                                           "Input file is I420 (default)");
00944 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
00945                                           "Codec to use");
00946 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
00947                                                   "Number of passes (1/2)");
00948 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
00949                                                   "Pass to execute (1/2)");
00950 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
00951                                                   "First pass statistics file name");
00952 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
00953                                        "Stop encoding after n input frames");
00954 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
00955                                       "Skip the first n input frames");
00956 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
00957                                                   "Deadline per frame (usec)");
00958 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
00959                                                   "Use Best Quality Deadline");
00960 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
00961                                                   "Use Good Quality Deadline");
00962 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
00963                                                   "Use Realtime Quality Deadline");
00964 static const arg_def_t quietarg         = ARG_DEF("q", "quiet", 0,
00965                                                   "Do not print encode progress");
00966 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
00967                                                   "Show encoder parameters");
00968 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
00969                                                   "Show PSNR in status line");
00970 enum TestDecodeFatality {
00971   TEST_DECODE_OFF,
00972   TEST_DECODE_FATAL,
00973   TEST_DECODE_WARN,
00974 };
00975 static const struct arg_enum_list test_decode_enum[] = {
00976   {"off",   TEST_DECODE_OFF},
00977   {"fatal", TEST_DECODE_FATAL},
00978   {"warn",  TEST_DECODE_WARN},
00979   {NULL, 0}
00980 };
00981 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
00982                                                 "Test encode/decode mismatch",
00983                                                 test_decode_enum);
00984 static const arg_def_t framerate        = ARG_DEF(NULL, "fps", 1,
00985                                                   "Stream frame rate (rate/scale)");
00986 static const arg_def_t use_ivf          = ARG_DEF(NULL, "ivf", 0,
00987                                                   "Output IVF (default is WebM)");
00988 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
00989                                           "Makes encoder output partitions. Requires IVF output!");
00990 static const arg_def_t q_hist_n         = ARG_DEF(NULL, "q-hist", 1,
00991                                                   "Show quantizer histogram (n-buckets)");
00992 static const arg_def_t rate_hist_n         = ARG_DEF(NULL, "rate-hist", 1,
00993                                                      "Show rate histogram (n-buckets)");
00994 static const arg_def_t *main_args[] = {
00995   &debugmode,
00996   &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
00997   &deadline, &best_dl, &good_dl, &rt_dl,
00998   &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
00999   NULL
01000 };
01001 
01002 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
01003                                                   "Usage profile number to use");
01004 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
01005                                                   "Max number of threads to use");
01006 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
01007                                                   "Bitstream profile number to use");
01008 static const arg_def_t width            = ARG_DEF("w", "width", 1,
01009                                                   "Frame width");
01010 static const arg_def_t height           = ARG_DEF("h", "height", 1,
01011                                                   "Frame height");
01012 static const struct arg_enum_list stereo_mode_enum[] = {
01013   {"mono", STEREO_FORMAT_MONO},
01014   {"left-right", STEREO_FORMAT_LEFT_RIGHT},
01015   {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
01016   {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
01017   {"right-left", STEREO_FORMAT_RIGHT_LEFT},
01018   {NULL, 0}
01019 };
01020 static const arg_def_t stereo_mode      = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
01021                                                        "Stereo 3D video format", stereo_mode_enum);
01022 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
01023                                                   "Output timestamp precision (fractional seconds)");
01024 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
01025                                                   "Enable error resiliency features");
01026 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
01027                                                   "Max number of frames to lag");
01028 
01029 static const arg_def_t *global_args[] = {
01030   &use_yv12, &use_i420, &usage, &threads, &profile,
01031   &width, &height, &stereo_mode, &timebase, &framerate,
01032   &error_resilient,
01033   &lag_in_frames, NULL
01034 };
01035 
01036 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
01037                                                     "Temporal resampling threshold (buf %)");
01038 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
01039                                                     "Spatial resampling enabled (bool)");
01040 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
01041                                                     "Upscale threshold (buf %)");
01042 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
01043                                                     "Downscale threshold (buf %)");
01044 static const struct arg_enum_list end_usage_enum[] = {
01045   {"vbr", VPX_VBR},
01046   {"cbr", VPX_CBR},
01047   {"cq",  VPX_CQ},
01048   {NULL, 0}
01049 };
01050 static const arg_def_t end_usage          = ARG_DEF_ENUM(NULL, "end-usage", 1,
01051                                                          "Rate control mode", end_usage_enum);
01052 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
01053                                                     "Bitrate (kbps)");
01054 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
01055                                                     "Minimum (best) quantizer");
01056 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
01057                                                     "Maximum (worst) quantizer");
01058 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
01059                                                     "Datarate undershoot (min) target (%)");
01060 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
01061                                                     "Datarate overshoot (max) target (%)");
01062 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
01063                                                     "Client buffer size (ms)");
01064 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
01065                                                     "Client initial buffer size (ms)");
01066 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
01067                                                     "Client optimal buffer size (ms)");
01068 static const arg_def_t *rc_args[] = {
01069   &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
01070   &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
01071   &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
01072   NULL
01073 };
01074 
01075 
01076 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
01077                                           "CBR/VBR bias (0=CBR, 100=VBR)");
01078 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
01079                                                 "GOP min bitrate (% of target)");
01080 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
01081                                                 "GOP max bitrate (% of target)");
01082 static const arg_def_t *rc_twopass_args[] = {
01083   &bias_pct, &minsection_pct, &maxsection_pct, NULL
01084 };
01085 
01086 
01087 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
01088                                              "Minimum keyframe interval (frames)");
01089 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
01090                                              "Maximum keyframe interval (frames)");
01091 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
01092                                              "Disable keyframe placement");
01093 static const arg_def_t *kf_args[] = {
01094   &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
01095 };
01096 
01097 
01098 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
01099                                             "Noise sensitivity (frames to blur)");
01100 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
01101                                            "Filter sharpness (0-7)");
01102 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
01103                                                "Motion detection threshold");
01104 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
01105                                           "CPU Used (-16..16)");
01106 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
01107                                      "Number of token partitions to use, log2");
01108 static const arg_def_t tile_cols = ARG_DEF(NULL, "tile-columns", 1,
01109                                          "Number of tile columns to use, log2");
01110 static const arg_def_t tile_rows = ARG_DEF(NULL, "tile-rows", 1,
01111                                            "Number of tile rows to use, log2");
01112 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
01113                                              "Enable automatic alt reference frames");
01114 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
01115                                                 "AltRef Max Frames");
01116 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
01117                                                "AltRef Strength");
01118 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
01119                                            "AltRef Type");
01120 static const struct arg_enum_list tuning_enum[] = {
01121   {"psnr", VP8_TUNE_PSNR},
01122   {"ssim", VP8_TUNE_SSIM},
01123   {NULL, 0}
01124 };
01125 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
01126                                                 "Material to favor", tuning_enum);
01127 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
01128                                           "Constrained Quality Level");
01129 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
01130                                                     "Max I-frame bitrate (pct)");
01131 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
01132 #if CONFIG_VP9_ENCODER
01133 static const arg_def_t frame_parallel_decoding  = ARG_DEF(
01134     NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
01135 #endif
01136 
01137 #if CONFIG_VP8_ENCODER
01138 static const arg_def_t *vp8_args[] = {
01139   &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
01140   &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
01141   &tune_ssim, &cq_level, &max_intra_rate_pct,
01142   NULL
01143 };
01144 static const int vp8_arg_ctrl_map[] = {
01145   VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
01146   VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
01147   VP8E_SET_TOKEN_PARTITIONS,
01148   VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
01149   VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
01150   0
01151 };
01152 #endif
01153 
01154 #if CONFIG_VP9_ENCODER
01155 static const arg_def_t *vp9_args[] = {
01156   &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
01157   &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
01158   &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
01159   &frame_parallel_decoding,
01160   NULL
01161 };
01162 static const int vp9_arg_ctrl_map[] = {
01163   VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
01164   VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
01165   VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
01166   VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
01167   VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
01168   VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING,
01169   0
01170 };
01171 #endif
01172 
01173 static const arg_def_t *no_args[] = { NULL };
01174 
01175 static void usage_exit() {
01176   int i;
01177 
01178   fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
01179           exec_name);
01180 
01181   fprintf(stderr, "\nOptions:\n");
01182   arg_show_usage(stdout, main_args);
01183   fprintf(stderr, "\nEncoder Global Options:\n");
01184   arg_show_usage(stdout, global_args);
01185   fprintf(stderr, "\nRate Control Options:\n");
01186   arg_show_usage(stdout, rc_args);
01187   fprintf(stderr, "\nTwopass Rate Control Options:\n");
01188   arg_show_usage(stdout, rc_twopass_args);
01189   fprintf(stderr, "\nKeyframe Placement Options:\n");
01190   arg_show_usage(stdout, kf_args);
01191 #if CONFIG_VP8_ENCODER
01192   fprintf(stderr, "\nVP8 Specific Options:\n");
01193   arg_show_usage(stdout, vp8_args);
01194 #endif
01195 #if CONFIG_VP9_ENCODER
01196   fprintf(stderr, "\nVP9 Specific Options:\n");
01197   arg_show_usage(stdout, vp9_args);
01198 #endif
01199   fprintf(stderr, "\nStream timebase (--timebase):\n"
01200           "  The desired precision of timestamps in the output, expressed\n"
01201           "  in fractional seconds. Default is 1/1000.\n");
01202   fprintf(stderr, "\n"
01203           "Included encoders:\n"
01204           "\n");
01205 
01206   for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
01207     fprintf(stderr, "    %-6s - %s\n",
01208             codecs[i].name,
01209             vpx_codec_iface_name(codecs[i].iface()));
01210 
01211   exit(EXIT_FAILURE);
01212 }
01213 
01214 
01215 #define HIST_BAR_MAX 40
01216 struct hist_bucket {
01217   int low, high, count;
01218 };
01219 
01220 
01221 static int merge_hist_buckets(struct hist_bucket *bucket,
01222                               int *buckets_,
01223                               int max_buckets) {
01224   int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
01225   int buckets = *buckets_;
01226   int i;
01227 
01228   /* Find the extrema for this list of buckets */
01229   big_bucket = small_bucket = 0;
01230   for (i = 0; i < buckets; i++) {
01231     if (bucket[i].count < bucket[small_bucket].count)
01232       small_bucket = i;
01233     if (bucket[i].count > bucket[big_bucket].count)
01234       big_bucket = i;
01235   }
01236 
01237   /* If we have too many buckets, merge the smallest with an adjacent
01238    * bucket.
01239    */
01240   while (buckets > max_buckets) {
01241     int last_bucket = buckets - 1;
01242 
01243     /* merge the small bucket with an adjacent one. */
01244     if (small_bucket == 0)
01245       merge_bucket = 1;
01246     else if (small_bucket == last_bucket)
01247       merge_bucket = last_bucket - 1;
01248     else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
01249       merge_bucket = small_bucket - 1;
01250     else
01251       merge_bucket = small_bucket + 1;
01252 
01253     assert(abs(merge_bucket - small_bucket) <= 1);
01254     assert(small_bucket < buckets);
01255     assert(big_bucket < buckets);
01256     assert(merge_bucket < buckets);
01257 
01258     if (merge_bucket < small_bucket) {
01259       bucket[merge_bucket].high = bucket[small_bucket].high;
01260       bucket[merge_bucket].count += bucket[small_bucket].count;
01261     } else {
01262       bucket[small_bucket].high = bucket[merge_bucket].high;
01263       bucket[small_bucket].count += bucket[merge_bucket].count;
01264       merge_bucket = small_bucket;
01265     }
01266 
01267     assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
01268 
01269     buckets--;
01270 
01271     /* Remove the merge_bucket from the list, and find the new small
01272      * and big buckets while we're at it
01273      */
01274     big_bucket = small_bucket = 0;
01275     for (i = 0; i < buckets; i++) {
01276       if (i > merge_bucket)
01277         bucket[i] = bucket[i + 1];
01278 
01279       if (bucket[i].count < bucket[small_bucket].count)
01280         small_bucket = i;
01281       if (bucket[i].count > bucket[big_bucket].count)
01282         big_bucket = i;
01283     }
01284 
01285   }
01286 
01287   *buckets_ = buckets;
01288   return bucket[big_bucket].count;
01289 }
01290 
01291 
01292 static void show_histogram(const struct hist_bucket *bucket,
01293                            int                       buckets,
01294                            int                       total,
01295                            int                       scale) {
01296   const char *pat1, *pat2;
01297   int i;
01298 
01299   switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
01300     case 1:
01301     case 2:
01302       pat1 = "%4d %2s: ";
01303       pat2 = "%4d-%2d: ";
01304       break;
01305     case 3:
01306       pat1 = "%5d %3s: ";
01307       pat2 = "%5d-%3d: ";
01308       break;
01309     case 4:
01310       pat1 = "%6d %4s: ";
01311       pat2 = "%6d-%4d: ";
01312       break;
01313     case 5:
01314       pat1 = "%7d %5s: ";
01315       pat2 = "%7d-%5d: ";
01316       break;
01317     case 6:
01318       pat1 = "%8d %6s: ";
01319       pat2 = "%8d-%6d: ";
01320       break;
01321     case 7:
01322       pat1 = "%9d %7s: ";
01323       pat2 = "%9d-%7d: ";
01324       break;
01325     default:
01326       pat1 = "%12d %10s: ";
01327       pat2 = "%12d-%10d: ";
01328       break;
01329   }
01330 
01331   for (i = 0; i < buckets; i++) {
01332     int len;
01333     int j;
01334     float pct;
01335 
01336     pct = (float)(100.0 * bucket[i].count / total);
01337     len = HIST_BAR_MAX * bucket[i].count / scale;
01338     if (len < 1)
01339       len = 1;
01340     assert(len <= HIST_BAR_MAX);
01341 
01342     if (bucket[i].low == bucket[i].high)
01343       fprintf(stderr, pat1, bucket[i].low, "");
01344     else
01345       fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
01346 
01347     for (j = 0; j < HIST_BAR_MAX; j++)
01348       fprintf(stderr, j < len ? "=" : " ");
01349     fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
01350   }
01351 }
01352 
01353 
01354 static void show_q_histogram(const int counts[64], int max_buckets) {
01355   struct hist_bucket bucket[64];
01356   int buckets = 0;
01357   int total = 0;
01358   int scale;
01359   int i;
01360 
01361 
01362   for (i = 0; i < 64; i++) {
01363     if (counts[i]) {
01364       bucket[buckets].low = bucket[buckets].high = i;
01365       bucket[buckets].count = counts[i];
01366       buckets++;
01367       total += counts[i];
01368     }
01369   }
01370 
01371   fprintf(stderr, "\nQuantizer Selection:\n");
01372   scale = merge_hist_buckets(bucket, &buckets, max_buckets);
01373   show_histogram(bucket, buckets, total, scale);
01374 }
01375 
01376 
01377 #define RATE_BINS (100)
01378 struct rate_hist {
01379   int64_t            *pts;
01380   int                *sz;
01381   int                 samples;
01382   int                 frames;
01383   struct hist_bucket  bucket[RATE_BINS];
01384   int                 total;
01385 };
01386 
01387 
01388 static void init_rate_histogram(struct rate_hist          *hist,
01389                                 const vpx_codec_enc_cfg_t *cfg,
01390                                 const vpx_rational_t      *fps) {
01391   int i;
01392 
01393   /* Determine the number of samples in the buffer. Use the file's framerate
01394    * to determine the number of frames in rc_buf_sz milliseconds, with an
01395    * adjustment (5/4) to account for alt-refs
01396    */
01397   hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
01398 
01399   /* prevent division by zero */
01400   if (hist->samples == 0)
01401     hist->samples = 1;
01402 
01403   hist->pts = calloc(hist->samples, sizeof(*hist->pts));
01404   hist->sz = calloc(hist->samples, sizeof(*hist->sz));
01405   for (i = 0; i < RATE_BINS; i++) {
01406     hist->bucket[i].low = INT_MAX;
01407     hist->bucket[i].high = 0;
01408     hist->bucket[i].count = 0;
01409   }
01410 }
01411 
01412 
01413 static void destroy_rate_histogram(struct rate_hist *hist) {
01414   free(hist->pts);
01415   free(hist->sz);
01416 }
01417 
01418 
01419 static void update_rate_histogram(struct rate_hist          *hist,
01420                                   const vpx_codec_enc_cfg_t *cfg,
01421                                   const vpx_codec_cx_pkt_t  *pkt) {
01422   int i, idx;
01423   int64_t now, then, sum_sz = 0, avg_bitrate;
01424 
01425   now = pkt->data.frame.pts * 1000
01426         * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
01427 
01428   idx = hist->frames++ % hist->samples;
01429   hist->pts[idx] = now;
01430   hist->sz[idx] = (int)pkt->data.frame.sz;
01431 
01432   if (now < cfg->rc_buf_initial_sz)
01433     return;
01434 
01435   then = now;
01436 
01437   /* Sum the size over the past rc_buf_sz ms */
01438   for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
01439     int i_idx = (i - 1) % hist->samples;
01440 
01441     then = hist->pts[i_idx];
01442     if (now - then > cfg->rc_buf_sz)
01443       break;
01444     sum_sz += hist->sz[i_idx];
01445   }
01446 
01447   if (now == then)
01448     return;
01449 
01450   avg_bitrate = sum_sz * 8 * 1000 / (now - then);
01451   idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
01452   if (idx < 0)
01453     idx = 0;
01454   if (idx > RATE_BINS - 1)
01455     idx = RATE_BINS - 1;
01456   if (hist->bucket[idx].low > avg_bitrate)
01457     hist->bucket[idx].low = (int)avg_bitrate;
01458   if (hist->bucket[idx].high < avg_bitrate)
01459     hist->bucket[idx].high = (int)avg_bitrate;
01460   hist->bucket[idx].count++;
01461   hist->total++;
01462 }
01463 
01464 
01465 static void show_rate_histogram(struct rate_hist          *hist,
01466                                 const vpx_codec_enc_cfg_t *cfg,
01467                                 int                        max_buckets) {
01468   int i, scale;
01469   int buckets = 0;
01470 
01471   for (i = 0; i < RATE_BINS; i++) {
01472     if (hist->bucket[i].low == INT_MAX)
01473       continue;
01474     hist->bucket[buckets++] = hist->bucket[i];
01475   }
01476 
01477   fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
01478   scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
01479   show_histogram(hist->bucket, buckets, hist->total, scale);
01480 }
01481 
01482 #define mmin(a, b)  ((a) < (b) ? (a) : (b))
01483 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
01484                           int yloc[2], int uloc[2], int vloc[2]) {
01485   const unsigned int bsize = 64;
01486   const unsigned int bsize2 = bsize >> 1;
01487   unsigned int match = 1;
01488   unsigned int i, j;
01489   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
01490   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
01491     for (j = 0; match && j < img1->d_w; j += bsize) {
01492       int k, l;
01493       int si = mmin(i + bsize, img1->d_h) - i;
01494       int sj = mmin(j + bsize, img1->d_w) - j;
01495       for (k = 0; match && k < si; k++)
01496         for (l = 0; match && l < sj; l++) {
01497           if (*(img1->planes[VPX_PLANE_Y] +
01498                 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
01499               *(img2->planes[VPX_PLANE_Y] +
01500                 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
01501             yloc[0] = i + k;
01502             yloc[1] = j + l;
01503             yloc[2] = *(img1->planes[VPX_PLANE_Y] +
01504                         (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
01505             yloc[3] = *(img2->planes[VPX_PLANE_Y] +
01506                         (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
01507             match = 0;
01508             break;
01509           }
01510         }
01511     }
01512   }
01513   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
01514   for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i += bsize2) {
01515     for (j = 0; j < match && (img1->d_w + 1) / 2; j += bsize2) {
01516       int k, l;
01517       int si = mmin(i + bsize2, (img1->d_h + 1) / 2) - i;
01518       int sj = mmin(j + bsize2, (img1->d_w + 1) / 2) - j;
01519       for (k = 0; match && k < si; k++)
01520         for (l = 0; match && l < sj; l++) {
01521           if (*(img1->planes[VPX_PLANE_U] +
01522                 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
01523               *(img2->planes[VPX_PLANE_U] +
01524                 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
01525             uloc[0] = i + k;
01526             uloc[1] = j + l;
01527             uloc[2] = *(img1->planes[VPX_PLANE_U] +
01528                         (i + k) * img1->stride[VPX_PLANE_U] + j + l);
01529             uloc[3] = *(img2->planes[VPX_PLANE_U] +
01530                         (i + k) * img2->stride[VPX_PLANE_V] + j + l);
01531             match = 0;
01532             break;
01533           }
01534         }
01535     }
01536   }
01537   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
01538   for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i += bsize2) {
01539     for (j = 0; j < match && (img1->d_w + 1) / 2; j += bsize2) {
01540       int k, l;
01541       int si = mmin(i + bsize2, (img1->d_h + 1) / 2) - i;
01542       int sj = mmin(j + bsize2, (img1->d_w + 1) / 2) - j;
01543       for (k = 0; match && k < si; k++)
01544         for (l = 0; match && l < sj; l++) {
01545           if (*(img1->planes[VPX_PLANE_V] +
01546                 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
01547               *(img2->planes[VPX_PLANE_V] +
01548                 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
01549             vloc[0] = i + k;
01550             vloc[1] = j + l;
01551             vloc[2] = *(img1->planes[VPX_PLANE_V] +
01552                         (i + k) * img1->stride[VPX_PLANE_V] + j + l);
01553             vloc[3] = *(img2->planes[VPX_PLANE_V] +
01554                         (i + k) * img2->stride[VPX_PLANE_V] + j + l);
01555             match = 0;
01556             break;
01557           }
01558         }
01559     }
01560   }
01561 }
01562 
01563 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
01564 {
01565   int match = 1;
01566   unsigned int i;
01567 
01568   match &= (img1->fmt == img2->fmt);
01569   match &= (img1->w == img2->w);
01570   match &= (img1->h == img2->h);
01571 
01572   for (i = 0; i < img1->d_h; i++)
01573     match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
01574                      img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
01575                      img1->d_w) == 0);
01576 
01577   for (i = 0; i < img1->d_h/2; i++)
01578     match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
01579                      img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
01580                      (img1->d_w + 1) / 2) == 0);
01581 
01582   for (i = 0; i < img1->d_h/2; i++)
01583     match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
01584                      img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
01585                      (img1->d_w + 1) / 2) == 0);
01586 
01587   return match;
01588 }
01589 
01590 
01591 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
01592 #define MAX(x,y) ((x)>(y)?(x):(y))
01593 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
01594 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
01595 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
01596 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
01597 #else
01598 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
01599                              NELEMENTS(vp9_arg_ctrl_map))
01600 #endif
01601 
01602 /* Configuration elements common to all streams */
01603 struct global_config {
01604   const struct codec_item  *codec;
01605   int                       passes;
01606   int                       pass;
01607   int                       usage;
01608   int                       deadline;
01609   int                       use_i420;
01610   int                       quiet;
01611   int                       verbose;
01612   int                       limit;
01613   int                       skip_frames;
01614   int                       show_psnr;
01615   enum TestDecodeFatality   test_decode;
01616   int                       have_framerate;
01617   struct vpx_rational       framerate;
01618   int                       out_part;
01619   int                       debug;
01620   int                       show_q_hist_buckets;
01621   int                       show_rate_hist_buckets;
01622 };
01623 
01624 
01625 /* Per-stream configuration */
01626 struct stream_config {
01627   struct vpx_codec_enc_cfg  cfg;
01628   const char               *out_fn;
01629   const char               *stats_fn;
01630   stereo_format_t           stereo_fmt;
01631   int                       arg_ctrls[ARG_CTRL_CNT_MAX][2];
01632   int                       arg_ctrl_cnt;
01633   int                       write_webm;
01634   int                       have_kf_max_dist;
01635 };
01636 
01637 
01638 struct stream_state {
01639   int                       index;
01640   struct stream_state      *next;
01641   struct stream_config      config;
01642   FILE                     *file;
01643   struct rate_hist          rate_hist;
01644   EbmlGlobal                ebml;
01645   uint32_t                  hash;
01646   uint64_t                  psnr_sse_total;
01647   uint64_t                  psnr_samples_total;
01648   double                    psnr_totals[4];
01649   int                       psnr_count;
01650   int                       counts[64];
01651   vpx_codec_ctx_t           encoder;
01652   unsigned int              frames_out;
01653   uint64_t                  cx_time;
01654   size_t                    nbytes;
01655   stats_io_t                stats;
01656   struct vpx_image         *img;
01657   vpx_codec_ctx_t           decoder;
01658   int                       mismatch_seen;
01659 };
01660 
01661 
01662 void validate_positive_rational(const char          *msg,
01663                                 struct vpx_rational *rat) {
01664   if (rat->den < 0) {
01665     rat->num *= -1;
01666     rat->den *= -1;
01667   }
01668 
01669   if (rat->num < 0)
01670     die("Error: %s must be positive\n", msg);
01671 
01672   if (!rat->den)
01673     die("Error: %s has zero denominator\n", msg);
01674 }
01675 
01676 
01677 static void parse_global_config(struct global_config *global, char **argv) {
01678   char       **argi, **argj;
01679   struct arg   arg;
01680 
01681   /* Initialize default parameters */
01682   memset(global, 0, sizeof(*global));
01683   global->codec = codecs;
01684   global->passes = 1;
01685   global->use_i420 = 1;
01686 
01687   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
01688     arg.argv_step = 1;
01689 
01690     if (arg_match(&arg, &codecarg, argi)) {
01691       int j, k = -1;
01692 
01693       for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
01694         if (!strcmp(codecs[j].name, arg.val))
01695           k = j;
01696 
01697       if (k >= 0)
01698         global->codec = codecs + k;
01699       else
01700         die("Error: Unrecognized argument (%s) to --codec\n",
01701             arg.val);
01702 
01703     } else if (arg_match(&arg, &passes, argi)) {
01704       global->passes = arg_parse_uint(&arg);
01705 
01706       if (global->passes < 1 || global->passes > 2)
01707         die("Error: Invalid number of passes (%d)\n", global->passes);
01708     } else if (arg_match(&arg, &pass_arg, argi)) {
01709       global->pass = arg_parse_uint(&arg);
01710 
01711       if (global->pass < 1 || global->pass > 2)
01712         die("Error: Invalid pass selected (%d)\n",
01713             global->pass);
01714     } else if (arg_match(&arg, &usage, argi))
01715       global->usage = arg_parse_uint(&arg);
01716     else if (arg_match(&arg, &deadline, argi))
01717       global->deadline = arg_parse_uint(&arg);
01718     else if (arg_match(&arg, &best_dl, argi))
01719       global->deadline = VPX_DL_BEST_QUALITY;
01720     else if (arg_match(&arg, &good_dl, argi))
01721       global->deadline = VPX_DL_GOOD_QUALITY;
01722     else if (arg_match(&arg, &rt_dl, argi))
01723       global->deadline = VPX_DL_REALTIME;
01724     else if (arg_match(&arg, &use_yv12, argi))
01725       global->use_i420 = 0;
01726     else if (arg_match(&arg, &use_i420, argi))
01727       global->use_i420 = 1;
01728     else if (arg_match(&arg, &quietarg, argi))
01729       global->quiet = 1;
01730     else if (arg_match(&arg, &verbosearg, argi))
01731       global->verbose = 1;
01732     else if (arg_match(&arg, &limit, argi))
01733       global->limit = arg_parse_uint(&arg);
01734     else if (arg_match(&arg, &skip, argi))
01735       global->skip_frames = arg_parse_uint(&arg);
01736     else if (arg_match(&arg, &psnrarg, argi))
01737       global->show_psnr = 1;
01738     else if (arg_match(&arg, &recontest, argi))
01739       global->test_decode = arg_parse_enum_or_int(&arg);
01740     else if (arg_match(&arg, &framerate, argi)) {
01741       global->framerate = arg_parse_rational(&arg);
01742       validate_positive_rational(arg.name, &global->framerate);
01743       global->have_framerate = 1;
01744     } else if (arg_match(&arg, &out_part, argi))
01745       global->out_part = 1;
01746     else if (arg_match(&arg, &debugmode, argi))
01747       global->debug = 1;
01748     else if (arg_match(&arg, &q_hist_n, argi))
01749       global->show_q_hist_buckets = arg_parse_uint(&arg);
01750     else if (arg_match(&arg, &rate_hist_n, argi))
01751       global->show_rate_hist_buckets = arg_parse_uint(&arg);
01752     else
01753       argj++;
01754   }
01755 
01756   /* Validate global config */
01757 
01758   if (global->pass) {
01759     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
01760     if (global->pass > global->passes) {
01761       warn("Assuming --pass=%d implies --passes=%d\n",
01762            global->pass, global->pass);
01763       global->passes = global->pass;
01764     }
01765   }
01766 }
01767 
01768 
01769 void open_input_file(struct input_state *input) {
01770   unsigned int fourcc;
01771 
01772   /* Parse certain options from the input file, if possible */
01773   input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
01774                 : set_binary_mode(stdin);
01775 
01776   if (!input->file)
01777     fatal("Failed to open input file");
01778 
01779   if (!fseeko(input->file, 0, SEEK_END)) {
01780     /* Input file is seekable. Figure out how long it is, so we can get
01781      * progress info.
01782      */
01783     input->length = ftello(input->file);
01784     rewind(input->file);
01785   }
01786 
01787   /* For RAW input sources, these bytes will applied on the first frame
01788    *  in read_frame().
01789    */
01790   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
01791   input->detect.position = 0;
01792 
01793   if (input->detect.buf_read == 4
01794       && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
01795     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0) {
01796       input->file_type = FILE_TYPE_Y4M;
01797       input->w = input->y4m.pic_w;
01798       input->h = input->y4m.pic_h;
01799       input->framerate.num = input->y4m.fps_n;
01800       input->framerate.den = input->y4m.fps_d;
01801       input->use_i420 = 0;
01802     } else
01803       fatal("Unsupported Y4M stream.");
01804   } else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
01805     input->file_type = FILE_TYPE_IVF;
01806     switch (fourcc) {
01807       case 0x32315659:
01808         input->use_i420 = 0;
01809         break;
01810       case 0x30323449:
01811         input->use_i420 = 1;
01812         break;
01813       default:
01814         fatal("Unsupported fourcc (%08x) in IVF", fourcc);
01815     }
01816   } else {
01817     input->file_type = FILE_TYPE_RAW;
01818   }
01819 }
01820 
01821 
01822 static void close_input_file(struct input_state *input) {
01823   fclose(input->file);
01824   if (input->file_type == FILE_TYPE_Y4M)
01825     y4m_input_close(&input->y4m);
01826 }
01827 
01828 static struct stream_state *new_stream(struct global_config *global,
01829                                        struct stream_state  *prev) {
01830   struct stream_state *stream;
01831 
01832   stream = calloc(1, sizeof(*stream));
01833   if (!stream)
01834     fatal("Failed to allocate new stream.");
01835   if (prev) {
01836     memcpy(stream, prev, sizeof(*stream));
01837     stream->index++;
01838     prev->next = stream;
01839   } else {
01840     vpx_codec_err_t  res;
01841 
01842     /* Populate encoder configuration */
01843     res = vpx_codec_enc_config_default(global->codec->iface(),
01844                                        &stream->config.cfg,
01845                                        global->usage);
01846     if (res)
01847       fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
01848 
01849     /* Change the default timebase to a high enough value so that the
01850      * encoder will always create strictly increasing timestamps.
01851      */
01852     stream->config.cfg.g_timebase.den = 1000;
01853 
01854     /* Never use the library's default resolution, require it be parsed
01855      * from the file or set on the command line.
01856      */
01857     stream->config.cfg.g_w = 0;
01858     stream->config.cfg.g_h = 0;
01859 
01860     /* Initialize remaining stream parameters */
01861     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
01862     stream->config.write_webm = 1;
01863     stream->ebml.last_pts_ms = -1;
01864 
01865     /* Allows removal of the application version from the EBML tags */
01866     stream->ebml.debug = global->debug;
01867   }
01868 
01869   /* Output files must be specified for each stream */
01870   stream->config.out_fn = NULL;
01871 
01872   stream->next = NULL;
01873   return stream;
01874 }
01875 
01876 
01877 static int parse_stream_params(struct global_config *global,
01878                                struct stream_state  *stream,
01879                                char **argv) {
01880   char                   **argi, **argj;
01881   struct arg               arg;
01882   static const arg_def_t **ctrl_args = no_args;
01883   static const int        *ctrl_args_map = NULL;
01884   struct stream_config    *config = &stream->config;
01885   int                      eos_mark_found = 0;
01886 
01887   /* Handle codec specific options */
01888   if (0) {
01889 #if CONFIG_VP8_ENCODER
01890   } else if (global->codec->iface == vpx_codec_vp8_cx) {
01891     ctrl_args = vp8_args;
01892     ctrl_args_map = vp8_arg_ctrl_map;
01893 #endif
01894 #if CONFIG_VP9_ENCODER
01895   } else if (global->codec->iface == vpx_codec_vp9_cx) {
01896     ctrl_args = vp9_args;
01897     ctrl_args_map = vp9_arg_ctrl_map;
01898 #endif
01899   }
01900 
01901   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
01902     arg.argv_step = 1;
01903 
01904     /* Once we've found an end-of-stream marker (--) we want to continue
01905      * shifting arguments but not consuming them.
01906      */
01907     if (eos_mark_found) {
01908       argj++;
01909       continue;
01910     } else if (!strcmp(*argj, "--")) {
01911       eos_mark_found = 1;
01912       continue;
01913     }
01914 
01915     if (0);
01916     else if (arg_match(&arg, &outputfile, argi))
01917       config->out_fn = arg.val;
01918     else if (arg_match(&arg, &fpf_name, argi))
01919       config->stats_fn = arg.val;
01920     else if (arg_match(&arg, &use_ivf, argi))
01921       config->write_webm = 0;
01922     else if (arg_match(&arg, &threads, argi))
01923       config->cfg.g_threads = arg_parse_uint(&arg);
01924     else if (arg_match(&arg, &profile, argi))
01925       config->cfg.g_profile = arg_parse_uint(&arg);
01926     else if (arg_match(&arg, &width, argi))
01927       config->cfg.g_w = arg_parse_uint(&arg);
01928     else if (arg_match(&arg, &height, argi))
01929       config->cfg.g_h = arg_parse_uint(&arg);
01930     else if (arg_match(&arg, &stereo_mode, argi))
01931       config->stereo_fmt = arg_parse_enum_or_int(&arg);
01932     else if (arg_match(&arg, &timebase, argi)) {
01933       config->cfg.g_timebase = arg_parse_rational(&arg);
01934       validate_positive_rational(arg.name, &config->cfg.g_timebase);
01935     } else if (arg_match(&arg, &error_resilient, argi))
01936       config->cfg.g_error_resilient = arg_parse_uint(&arg);
01937     else if (arg_match(&arg, &lag_in_frames, argi))
01938       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
01939     else if (arg_match(&arg, &dropframe_thresh, argi))
01940       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
01941     else if (arg_match(&arg, &resize_allowed, argi))
01942       config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
01943     else if (arg_match(&arg, &resize_up_thresh, argi))
01944       config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
01945     else if (arg_match(&arg, &resize_down_thresh, argi))
01946       config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
01947     else if (arg_match(&arg, &end_usage, argi))
01948       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
01949     else if (arg_match(&arg, &target_bitrate, argi))
01950       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
01951     else if (arg_match(&arg, &min_quantizer, argi))
01952       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
01953     else if (arg_match(&arg, &max_quantizer, argi))
01954       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
01955     else if (arg_match(&arg, &undershoot_pct, argi))
01956       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
01957     else if (arg_match(&arg, &overshoot_pct, argi))
01958       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
01959     else if (arg_match(&arg, &buf_sz, argi))
01960       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
01961     else if (arg_match(&arg, &buf_initial_sz, argi))
01962       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
01963     else if (arg_match(&arg, &buf_optimal_sz, argi))
01964       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
01965     else if (arg_match(&arg, &bias_pct, argi)) {
01966       config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
01967 
01968       if (global->passes < 2)
01969         warn("option %s ignored in one-pass mode.\n", arg.name);
01970     } else if (arg_match(&arg, &minsection_pct, argi)) {
01971       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
01972 
01973       if (global->passes < 2)
01974         warn("option %s ignored in one-pass mode.\n", arg.name);
01975     } else if (arg_match(&arg, &maxsection_pct, argi)) {
01976       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
01977 
01978       if (global->passes < 2)
01979         warn("option %s ignored in one-pass mode.\n", arg.name);
01980     } else if (arg_match(&arg, &kf_min_dist, argi))
01981       config->cfg.kf_min_dist = arg_parse_uint(&arg);
01982     else if (arg_match(&arg, &kf_max_dist, argi)) {
01983       config->cfg.kf_max_dist = arg_parse_uint(&arg);
01984       config->have_kf_max_dist = 1;
01985     } else if (arg_match(&arg, &kf_disabled, argi))
01986       config->cfg.kf_mode = VPX_KF_DISABLED;
01987     else {
01988       int i, match = 0;
01989 
01990       for (i = 0; ctrl_args[i]; i++) {
01991         if (arg_match(&arg, ctrl_args[i], argi)) {
01992           int j;
01993           match = 1;
01994 
01995           /* Point either to the next free element or the first
01996           * instance of this control.
01997           */
01998           for (j = 0; j < config->arg_ctrl_cnt; j++)
01999             if (config->arg_ctrls[j][0] == ctrl_args_map[i])
02000               break;
02001 
02002           /* Update/insert */
02003           assert(j < ARG_CTRL_CNT_MAX);
02004           if (j < ARG_CTRL_CNT_MAX) {
02005             config->arg_ctrls[j][0] = ctrl_args_map[i];
02006             config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
02007             if (j == config->arg_ctrl_cnt)
02008               config->arg_ctrl_cnt++;
02009           }
02010 
02011         }
02012       }
02013 
02014       if (!match)
02015         argj++;
02016     }
02017   }
02018 
02019   return eos_mark_found;
02020 }
02021 
02022 
02023 #define FOREACH_STREAM(func)\
02024   do\
02025   {\
02026     struct stream_state  *stream;\
02027     \
02028     for(stream = streams; stream; stream = stream->next)\
02029       func;\
02030   }while(0)
02031 
02032 
02033 static void validate_stream_config(struct stream_state *stream) {
02034   struct stream_state *streami;
02035 
02036   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
02037     fatal("Stream %d: Specify stream dimensions with --width (-w) "
02038           " and --height (-h)", stream->index);
02039 
02040   for (streami = stream; streami; streami = streami->next) {
02041     /* All streams require output files */
02042     if (!streami->config.out_fn)
02043       fatal("Stream %d: Output file is required (specify with -o)",
02044             streami->index);
02045 
02046     /* Check for two streams outputting to the same file */
02047     if (streami != stream) {
02048       const char *a = stream->config.out_fn;
02049       const char *b = streami->config.out_fn;
02050       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
02051         fatal("Stream %d: duplicate output file (from stream %d)",
02052               streami->index, stream->index);
02053     }
02054 
02055     /* Check for two streams sharing a stats file. */
02056     if (streami != stream) {
02057       const char *a = stream->config.stats_fn;
02058       const char *b = streami->config.stats_fn;
02059       if (a && b && !strcmp(a, b))
02060         fatal("Stream %d: duplicate stats file (from stream %d)",
02061               streami->index, stream->index);
02062     }
02063   }
02064 }
02065 
02066 
02067 static void set_stream_dimensions(struct stream_state *stream,
02068                                   unsigned int w,
02069                                   unsigned int h) {
02070   if (!stream->config.cfg.g_w) {
02071     if (!stream->config.cfg.g_h)
02072       stream->config.cfg.g_w = w;
02073     else
02074       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
02075   }
02076   if (!stream->config.cfg.g_h) {
02077     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
02078   }
02079 }
02080 
02081 
02082 static void set_default_kf_interval(struct stream_state  *stream,
02083                                     struct global_config *global) {
02084   /* Use a max keyframe interval of 5 seconds, if none was
02085    * specified on the command line.
02086    */
02087   if (!stream->config.have_kf_max_dist) {
02088     double framerate = (double)global->framerate.num / global->framerate.den;
02089     if (framerate > 0.0)
02090       stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
02091   }
02092 }
02093 
02094 
02095 static void show_stream_config(struct stream_state  *stream,
02096                                struct global_config *global,
02097                                struct input_state   *input) {
02098 
02099 #define SHOW(field) \
02100   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
02101 
02102   if (stream->index == 0) {
02103     fprintf(stderr, "Codec: %s\n",
02104             vpx_codec_iface_name(global->codec->iface()));
02105     fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
02106             input->use_i420 ? "I420" : "YV12");
02107   }
02108   if (stream->next || stream->index)
02109     fprintf(stderr, "\nStream Index: %d\n", stream->index);
02110   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
02111   fprintf(stderr, "Encoder parameters:\n");
02112 
02113   SHOW(g_usage);
02114   SHOW(g_threads);
02115   SHOW(g_profile);
02116   SHOW(g_w);
02117   SHOW(g_h);
02118   SHOW(g_timebase.num);
02119   SHOW(g_timebase.den);
02120   SHOW(g_error_resilient);
02121   SHOW(g_pass);
02122   SHOW(g_lag_in_frames);
02123   SHOW(rc_dropframe_thresh);
02124   SHOW(rc_resize_allowed);
02125   SHOW(rc_resize_up_thresh);
02126   SHOW(rc_resize_down_thresh);
02127   SHOW(rc_end_usage);
02128   SHOW(rc_target_bitrate);
02129   SHOW(rc_min_quantizer);
02130   SHOW(rc_max_quantizer);
02131   SHOW(rc_undershoot_pct);
02132   SHOW(rc_overshoot_pct);
02133   SHOW(rc_buf_sz);
02134   SHOW(rc_buf_initial_sz);
02135   SHOW(rc_buf_optimal_sz);
02136   SHOW(rc_2pass_vbr_bias_pct);
02137   SHOW(rc_2pass_vbr_minsection_pct);
02138   SHOW(rc_2pass_vbr_maxsection_pct);
02139   SHOW(kf_mode);
02140   SHOW(kf_min_dist);
02141   SHOW(kf_max_dist);
02142 }
02143 
02144 
02145 static void open_output_file(struct stream_state *stream,
02146                              struct global_config *global) {
02147   const char *fn = stream->config.out_fn;
02148 
02149   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
02150 
02151   if (!stream->file)
02152     fatal("Failed to open output file");
02153 
02154   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
02155     fatal("WebM output to pipes not supported.");
02156 
02157   if (stream->config.write_webm) {
02158     stream->ebml.stream = stream->file;
02159     write_webm_file_header(&stream->ebml, &stream->config.cfg,
02160                            &global->framerate,
02161                            stream->config.stereo_fmt,
02162                            global->codec->fourcc);
02163   } else
02164     write_ivf_file_header(stream->file, &stream->config.cfg,
02165                           global->codec->fourcc, 0);
02166 }
02167 
02168 
02169 static void close_output_file(struct stream_state *stream,
02170                               unsigned int         fourcc) {
02171   if (stream->config.write_webm) {
02172     write_webm_file_footer(&stream->ebml, stream->hash);
02173     free(stream->ebml.cue_list);
02174     stream->ebml.cue_list = NULL;
02175   } else {
02176     if (!fseek(stream->file, 0, SEEK_SET))
02177       write_ivf_file_header(stream->file, &stream->config.cfg,
02178                             fourcc,
02179                             stream->frames_out);
02180   }
02181 
02182   fclose(stream->file);
02183 }
02184 
02185 
02186 static void setup_pass(struct stream_state  *stream,
02187                        struct global_config *global,
02188                        int                   pass) {
02189   if (stream->config.stats_fn) {
02190     if (!stats_open_file(&stream->stats, stream->config.stats_fn,
02191                          pass))
02192       fatal("Failed to open statistics store");
02193   } else {
02194     if (!stats_open_mem(&stream->stats, pass))
02195       fatal("Failed to open statistics store");
02196   }
02197 
02198   stream->config.cfg.g_pass = global->passes == 2
02199                               ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
02200                             : VPX_RC_ONE_PASS;
02201   if (pass)
02202     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
02203 
02204   stream->cx_time = 0;
02205   stream->nbytes = 0;
02206   stream->frames_out = 0;
02207 }
02208 
02209 
02210 static void initialize_encoder(struct stream_state  *stream,
02211                                struct global_config *global) {
02212   int i;
02213   int flags = 0;
02214 
02215   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
02216   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
02217 
02218   /* Construct Encoder Context */
02219   vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
02220                      &stream->config.cfg, flags);
02221   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
02222 
02223   /* Note that we bypass the vpx_codec_control wrapper macro because
02224    * we're being clever to store the control IDs in an array. Real
02225    * applications will want to make use of the enumerations directly
02226    */
02227   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
02228     int ctrl = stream->config.arg_ctrls[i][0];
02229     int value = stream->config.arg_ctrls[i][1];
02230     if (vpx_codec_control_(&stream->encoder, ctrl, value))
02231       fprintf(stderr, "Error: Tried to set control %d = %d\n",
02232               ctrl, value);
02233 
02234     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
02235   }
02236 
02237 #if CONFIG_DECODERS
02238   if (global->test_decode != TEST_DECODE_OFF) {
02239     vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
02240   }
02241 #endif
02242 }
02243 
02244 
02245 static void encode_frame(struct stream_state  *stream,
02246                          struct global_config *global,
02247                          struct vpx_image     *img,
02248                          unsigned int          frames_in) {
02249   vpx_codec_pts_t frame_start, next_frame_start;
02250   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
02251   struct vpx_usec_timer timer;
02252 
02253   frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
02254                  * global->framerate.den)
02255                 / cfg->g_timebase.num / global->framerate.num;
02256   next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
02257                       * global->framerate.den)
02258                      / cfg->g_timebase.num / global->framerate.num;
02259 
02260   /* Scale if necessary */
02261   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
02262     if (!stream->img)
02263       stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
02264                                   cfg->g_w, cfg->g_h, 16);
02265     I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
02266               img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
02267               img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
02268               img->d_w, img->d_h,
02269               stream->img->planes[VPX_PLANE_Y],
02270               stream->img->stride[VPX_PLANE_Y],
02271               stream->img->planes[VPX_PLANE_U],
02272               stream->img->stride[VPX_PLANE_U],
02273               stream->img->planes[VPX_PLANE_V],
02274               stream->img->stride[VPX_PLANE_V],
02275               stream->img->d_w, stream->img->d_h,
02276               kFilterBox);
02277 
02278     img = stream->img;
02279   }
02280 
02281   vpx_usec_timer_start(&timer);
02282   vpx_codec_encode(&stream->encoder, img, frame_start,
02283                    (unsigned long)(next_frame_start - frame_start),
02284                    0, global->deadline);
02285   vpx_usec_timer_mark(&timer);
02286   stream->cx_time += vpx_usec_timer_elapsed(&timer);
02287   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
02288                     stream->index);
02289 }
02290 
02291 
02292 static void update_quantizer_histogram(struct stream_state *stream) {
02293   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
02294     int q;
02295 
02296     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
02297     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
02298     stream->counts[q]++;
02299   }
02300 }
02301 
02302 
02303 static void get_cx_data(struct stream_state  *stream,
02304                         struct global_config *global,
02305                         int                  *got_data) {
02306   const vpx_codec_cx_pkt_t *pkt;
02307   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
02308   vpx_codec_iter_t iter = NULL;
02309 
02310   *got_data = 0;
02311   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
02312     static size_t fsize = 0;
02313     static off_t ivf_header_pos = 0;
02314 
02315     switch (pkt->kind) {
02316       case VPX_CODEC_CX_FRAME_PKT:
02317         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
02318           stream->frames_out++;
02319         }
02320         if (!global->quiet)
02321           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
02322 
02323         update_rate_histogram(&stream->rate_hist, cfg, pkt);
02324         if (stream->config.write_webm) {
02325           /* Update the hash */
02326           if (!stream->ebml.debug)
02327             stream->hash = murmur(pkt->data.frame.buf,
02328                                   (int)pkt->data.frame.sz,
02329                                   stream->hash);
02330 
02331           write_webm_block(&stream->ebml, cfg, pkt);
02332         } else {
02333           if (pkt->data.frame.partition_id <= 0) {
02334             ivf_header_pos = ftello(stream->file);
02335             fsize = pkt->data.frame.sz;
02336 
02337             write_ivf_frame_header(stream->file, pkt);
02338           } else {
02339             fsize += pkt->data.frame.sz;
02340 
02341             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
02342               off_t currpos = ftello(stream->file);
02343               fseeko(stream->file, ivf_header_pos, SEEK_SET);
02344               write_ivf_frame_size(stream->file, fsize);
02345               fseeko(stream->file, currpos, SEEK_SET);
02346             }
02347           }
02348 
02349           (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
02350                         stream->file);
02351         }
02352         stream->nbytes += pkt->data.raw.sz;
02353 
02354         *got_data = 1;
02355 #if CONFIG_DECODERS
02356         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
02357           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
02358                            pkt->data.frame.sz, NULL, 0);
02359           if (stream->decoder.err) {
02360             warn_or_exit_on_error(&stream->decoder,
02361                                   global->test_decode == TEST_DECODE_FATAL,
02362                                   "Failed to decode frame %d in stream %d",
02363                                   stream->frames_out + 1, stream->index);
02364             stream->mismatch_seen = stream->frames_out + 1;
02365           }
02366         }
02367 #endif
02368         break;
02369       case VPX_CODEC_STATS_PKT:
02370         stream->frames_out++;
02371         stats_write(&stream->stats,
02372                     pkt->data.twopass_stats.buf,
02373                     pkt->data.twopass_stats.sz);
02374         stream->nbytes += pkt->data.raw.sz;
02375         break;
02376       case VPX_CODEC_PSNR_PKT:
02377 
02378         if (global->show_psnr) {
02379           int i;
02380 
02381           stream->psnr_sse_total += pkt->data.psnr.sse[0];
02382           stream->psnr_samples_total += pkt->data.psnr.samples[0];
02383           for (i = 0; i < 4; i++) {
02384             if (!global->quiet)
02385               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
02386             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
02387           }
02388           stream->psnr_count++;
02389         }
02390 
02391         break;
02392       default:
02393         break;
02394     }
02395   }
02396 }
02397 
02398 
02399 static void show_psnr(struct stream_state  *stream) {
02400   int i;
02401   double ovpsnr;
02402 
02403   if (!stream->psnr_count)
02404     return;
02405 
02406   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
02407   ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
02408                         (double)stream->psnr_sse_total);
02409   fprintf(stderr, " %.3f", ovpsnr);
02410 
02411   for (i = 0; i < 4; i++) {
02412     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
02413   }
02414   fprintf(stderr, "\n");
02415 }
02416 
02417 
02418 static float usec_to_fps(uint64_t usec, unsigned int frames) {
02419   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
02420 }
02421 
02422 
02423 static void test_decode(struct stream_state  *stream,
02424                         enum TestDecodeFatality fatal,
02425                         const struct codec_item *codec) {
02426   vpx_image_t enc_img, dec_img;
02427 
02428   if (stream->mismatch_seen)
02429     return;
02430 
02431   /* Get the internal reference frame */
02432   if (codec->fourcc == VP8_FOURCC) {
02433     struct vpx_ref_frame ref_enc, ref_dec;
02434     int width, height;
02435 
02436     width = (stream->config.cfg.g_w + 15) & ~15;
02437     height = (stream->config.cfg.g_h + 15) & ~15;
02438     vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
02439     enc_img = ref_enc.img;
02440     vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
02441     dec_img = ref_dec.img;
02442 
02443     ref_enc.frame_type = VP8_LAST_FRAME;
02444     ref_dec.frame_type = VP8_LAST_FRAME;
02445     vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
02446     vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
02447   } else {
02448     struct vp9_ref_frame ref;
02449 
02450     ref.idx = 0;
02451     vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
02452     enc_img = ref.img;
02453     vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
02454     dec_img = ref.img;
02455   }
02456   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
02457   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
02458 
02459   if (!compare_img(&enc_img, &dec_img)) {
02460     int y[4], u[4], v[4];
02461     find_mismatch(&enc_img, &dec_img, y, u, v);
02462     stream->decoder.err = 1;
02463     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
02464                           "Stream %d: Encode/decode mismatch on frame %d at"
02465                           " Y[%d, %d] {%d/%d},"
02466                           " U[%d, %d] {%d/%d},"
02467                           " V[%d, %d] {%d/%d}",
02468                           stream->index, stream->frames_out,
02469                           y[0], y[1], y[2], y[3],
02470                           u[0], u[1], u[2], u[3],
02471                           v[0], v[1], v[2], v[3]);
02472     stream->mismatch_seen = stream->frames_out;
02473   }
02474 
02475   vpx_img_free(&enc_img);
02476   vpx_img_free(&dec_img);
02477 }
02478 
02479 
02480 static void print_time(const char *label, int64_t etl) {
02481   int hours, mins, secs;
02482 
02483   if (etl >= 0) {
02484     hours = etl / 3600;
02485     etl -= hours * 3600;
02486     mins = etl / 60;
02487     etl -= mins * 60;
02488     secs = etl;
02489 
02490     fprintf(stderr, "[%3s %2d:%02d:%02d] ",
02491             label, hours, mins, secs);
02492   } else {
02493     fprintf(stderr, "[%3s  unknown] ", label);
02494   }
02495 }
02496 
02497 int main(int argc, const char **argv_) {
02498   int                    pass;
02499   vpx_image_t            raw;
02500   int                    frame_avail, got_data;
02501 
02502   struct input_state       input = {0};
02503   struct global_config     global;
02504   struct stream_state     *streams = NULL;
02505   char                   **argv, **argi;
02506   uint64_t                 cx_time = 0;
02507   int                      stream_cnt = 0;
02508   int                      res = 0;
02509 
02510   exec_name = argv_[0];
02511 
02512   if (argc < 3)
02513     usage_exit();
02514 
02515   /* Setup default input stream settings */
02516   input.framerate.num = 30;
02517   input.framerate.den = 1;
02518   input.use_i420 = 1;
02519 
02520   /* First parse the global configuration values, because we want to apply
02521    * other parameters on top of the default configuration provided by the
02522    * codec.
02523    */
02524   argv = argv_dup(argc - 1, argv_ + 1);
02525   parse_global_config(&global, argv);
02526 
02527   {
02528     /* Now parse each stream's parameters. Using a local scope here
02529      * due to the use of 'stream' as loop variable in FOREACH_STREAM
02530      * loops
02531      */
02532     struct stream_state *stream = NULL;
02533 
02534     do {
02535       stream = new_stream(&global, stream);
02536       stream_cnt++;
02537       if (!streams)
02538         streams = stream;
02539     } while (parse_stream_params(&global, stream, argv));
02540   }
02541 
02542   /* Check for unrecognized options */
02543   for (argi = argv; *argi; argi++)
02544     if (argi[0][0] == '-' && argi[0][1])
02545       die("Error: Unrecognized option %s\n", *argi);
02546 
02547   /* Handle non-option arguments */
02548   input.fn = argv[0];
02549 
02550   if (!input.fn)
02551     usage_exit();
02552 
02553   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
02554     int frames_in = 0, seen_frames = 0;
02555     int64_t estimated_time_left = -1;
02556     int64_t average_rate = -1;
02557     off_t lagged_count = 0;
02558 
02559     open_input_file(&input);
02560 
02561     /* If the input file doesn't specify its w/h (raw files), try to get
02562      * the data from the first stream's configuration.
02563      */
02564     if (!input.w || !input.h)
02565       FOREACH_STREAM( {
02566       if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
02567         input.w = stream->config.cfg.g_w;
02568         input.h = stream->config.cfg.g_h;
02569         break;
02570       }
02571     });
02572 
02573     /* Update stream configurations from the input file's parameters */
02574     if (!input.w || !input.h)
02575       fatal("Specify stream dimensions with --width (-w) "
02576             " and --height (-h)");
02577     FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
02578     FOREACH_STREAM(validate_stream_config(stream));
02579 
02580     /* Ensure that --passes and --pass are consistent. If --pass is set and
02581      * --passes=2, ensure --fpf was set.
02582      */
02583     if (global.pass && global.passes == 2)
02584       FOREACH_STREAM( {
02585       if (!stream->config.stats_fn)
02586         die("Stream %d: Must specify --fpf when --pass=%d"
02587         " and --passes=2\n", stream->index, global.pass);
02588     });
02589 
02590     /* Use the frame rate from the file only if none was specified
02591      * on the command-line.
02592      */
02593     if (!global.have_framerate)
02594       global.framerate = input.framerate;
02595 
02596     FOREACH_STREAM(set_default_kf_interval(stream, &global));
02597 
02598     /* Show configuration */
02599     if (global.verbose && pass == 0)
02600       FOREACH_STREAM(show_stream_config(stream, &global, &input));
02601 
02602     if (pass == (global.pass ? global.pass - 1 : 0)) {
02603       if (input.file_type == FILE_TYPE_Y4M)
02604         /*The Y4M reader does its own allocation.
02605           Just initialize this here to avoid problems if we never read any
02606            frames.*/
02607         memset(&raw, 0, sizeof(raw));
02608       else
02609         vpx_img_alloc(&raw,
02610                       input.use_i420 ? VPX_IMG_FMT_I420
02611                       : VPX_IMG_FMT_YV12,
02612                       input.w, input.h, 32);
02613 
02614       FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
02615                                          &stream->config.cfg,
02616                                          &global.framerate));
02617     }
02618 
02619     FOREACH_STREAM(open_output_file(stream, &global));
02620     FOREACH_STREAM(setup_pass(stream, &global, pass));
02621     FOREACH_STREAM(initialize_encoder(stream, &global));
02622 
02623     frame_avail = 1;
02624     got_data = 0;
02625 
02626     while (frame_avail || got_data) {
02627       struct vpx_usec_timer timer;
02628 
02629       if (!global.limit || frames_in < global.limit) {
02630         frame_avail = read_frame(&input, &raw);
02631 
02632         if (frame_avail)
02633           frames_in++;
02634         seen_frames = frames_in > global.skip_frames ?
02635                           frames_in - global.skip_frames : 0;
02636 
02637         if (!global.quiet) {
02638           float fps = usec_to_fps(cx_time, seen_frames);
02639           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
02640 
02641           if (stream_cnt == 1)
02642             fprintf(stderr,
02643                     "frame %4d/%-4d %7"PRId64"B ",
02644                     frames_in, streams->frames_out, (int64_t)streams->nbytes);
02645           else
02646             fprintf(stderr, "frame %4d ", frames_in);
02647 
02648           fprintf(stderr, "%7"PRId64" %s %.2f %s ",
02649                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
02650                   cx_time > 9999999 ? "ms" : "us",
02651                   fps >= 1.0 ? fps : 1000.0 / fps,
02652                   fps >= 1.0 ? "fps" : "ms/f");
02653           print_time("ETA", estimated_time_left);
02654           fprintf(stderr, "\033[K");
02655         }
02656 
02657       } else
02658         frame_avail = 0;
02659 
02660       if (frames_in > global.skip_frames) {
02661         vpx_usec_timer_start(&timer);
02662         FOREACH_STREAM(encode_frame(stream, &global,
02663                                     frame_avail ? &raw : NULL,
02664                                     frames_in));
02665         vpx_usec_timer_mark(&timer);
02666         cx_time += vpx_usec_timer_elapsed(&timer);
02667 
02668         FOREACH_STREAM(update_quantizer_histogram(stream));
02669 
02670         got_data = 0;
02671         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
02672 
02673         if (!got_data && input.length && !streams->frames_out) {
02674           lagged_count = global.limit ? seen_frames : ftello(input.file);
02675         } else if (input.length) {
02676           int64_t remaining;
02677           int64_t rate;
02678 
02679           if (global.limit) {
02680             int frame_in_lagged = (seen_frames - lagged_count) * 1000;
02681 
02682             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
02683             remaining = 1000 * (global.limit - global.skip_frames
02684                                 - seen_frames + lagged_count);
02685           } else {
02686             off_t input_pos = ftello(input.file);
02687             off_t input_pos_lagged = input_pos - lagged_count;
02688             int64_t limit = input.length;
02689 
02690             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
02691             remaining = limit - input_pos + lagged_count;
02692           }
02693 
02694           average_rate = (average_rate <= 0)
02695               ? rate
02696               : (average_rate * 7 + rate) / 8;
02697           estimated_time_left = average_rate ? remaining / average_rate : -1;
02698         }
02699 
02700         if (got_data && global.test_decode != TEST_DECODE_OFF)
02701           FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
02702       }
02703 
02704       fflush(stdout);
02705     }
02706 
02707     if (stream_cnt > 1)
02708       fprintf(stderr, "\n");
02709 
02710     if (!global.quiet)
02711       FOREACH_STREAM(fprintf(
02712                        stderr,
02713                        "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
02714                        " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
02715                        global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
02716                        seen_frames ? (unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
02717                        seen_frames ? (int64_t)stream->nbytes * 8
02718                        * (int64_t)global.framerate.num / global.framerate.den
02719                        / seen_frames
02720                        : 0,
02721                        stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
02722                        stream->cx_time > 9999999 ? "ms" : "us",
02723                        usec_to_fps(stream->cx_time, seen_frames));
02724                     );
02725 
02726     if (global.show_psnr)
02727       FOREACH_STREAM(show_psnr(stream));
02728 
02729     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
02730 
02731     if (global.test_decode != TEST_DECODE_OFF) {
02732       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
02733     }
02734 
02735     close_input_file(&input);
02736 
02737     if (global.test_decode == TEST_DECODE_FATAL) {
02738       FOREACH_STREAM(res |= stream->mismatch_seen);
02739     }
02740     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
02741 
02742     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
02743 
02744     if (global.pass)
02745       break;
02746   }
02747 
02748   if (global.show_q_hist_buckets)
02749     FOREACH_STREAM(show_q_histogram(stream->counts,
02750                                     global.show_q_hist_buckets));
02751 
02752   if (global.show_rate_hist_buckets)
02753     FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
02754                                        &stream->config.cfg,
02755                                        global.show_rate_hist_buckets));
02756   FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
02757 
02758 #if CONFIG_INTERNAL_STATS
02759   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
02760    * to match some existing utilities.
02761    */
02762   FOREACH_STREAM({
02763     FILE *f = fopen("opsnr.stt", "a");
02764     if (stream->mismatch_seen) {
02765       fprintf(f, "First mismatch occurred in frame %d\n",
02766               stream->mismatch_seen);
02767     } else {
02768       fprintf(f, "No mismatch detected in recon buffers\n");
02769     }
02770     fclose(f);
02771   });
02772 #endif
02773 
02774   vpx_img_free(&raw);
02775   free(argv);
02776   free(streams);
02777   return res ? EXIT_FAILURE : EXIT_SUCCESS;
02778 }