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 "./vpxenc.h"
00012 #include "./vpx_config.h"
00013 
00014 #include <assert.h>
00015 #include <limits.h>
00016 #include <math.h>
00017 #include <stdarg.h>
00018 #include <stdio.h>
00019 #include <stdlib.h>
00020 #include <string.h>
00021 
00022 #if CONFIG_LIBYUV
00023 #include "third_party/libyuv/include/libyuv/scale.h"
00024 #endif
00025 
00026 #include "vpx/vpx_encoder.h"
00027 #if CONFIG_DECODERS
00028 #include "vpx/vpx_decoder.h"
00029 #endif
00030 
00031 #include "./args.h"
00032 #include "./ivfenc.h"
00033 #include "./tools_common.h"
00034 
00035 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
00036 #include "vpx/vp8cx.h"
00037 #endif
00038 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
00039 #include "vpx/vp8dx.h"
00040 #endif
00041 
00042 #include "vpx/vpx_integer.h"
00043 #include "vpx_ports/mem_ops.h"
00044 #include "vpx_ports/vpx_timer.h"
00045 #include "./rate_hist.h"
00046 #include "./vpxstats.h"
00047 #include "./warnings.h"
00048 #if CONFIG_WEBM_IO
00049 #include "./webmenc.h"
00050 #endif
00051 #include "./y4minput.h"
00052 
00053 /* Swallow warnings about unused results of fread/fwrite */
00054 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
00055   return fread(ptr, size, nmemb, stream);
00056 }
00057 #define fread wrap_fread
00058 
00059 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
00060                           FILE *stream) {
00061   return fwrite(ptr, size, nmemb, stream);
00062 }
00063 #define fwrite wrap_fwrite
00064 
00065 static const char *exec_name;
00066 
00067 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
00068                                    const char *s, va_list ap) {
00069   if (ctx->err) {
00070     const char *detail = vpx_codec_error_detail(ctx);
00071 
00072     vfprintf(stderr, s, ap);
00073     fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
00074 
00075     if (detail) fprintf(stderr, "    %s\n", detail);
00076 
00077     if (fatal) exit(EXIT_FAILURE);
00078   }
00079 }
00080 
00081 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
00082   va_list ap;
00083 
00084   va_start(ap, s);
00085   warn_or_exit_on_errorv(ctx, 1, s, ap);
00086   va_end(ap);
00087 }
00088 
00089 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
00090                                   const char *s, ...) {
00091   va_list ap;
00092 
00093   va_start(ap, s);
00094   warn_or_exit_on_errorv(ctx, fatal, s, ap);
00095   va_end(ap);
00096 }
00097 
00098 static int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
00099   FILE *f = input_ctx->file;
00100   y4m_input *y4m = &input_ctx->y4m;
00101   int shortread = 0;
00102 
00103   if (input_ctx->file_type == FILE_TYPE_Y4M) {
00104     if (y4m_input_fetch_frame(y4m, f, img) < 1) return 0;
00105   } else {
00106     shortread = read_yuv_frame(input_ctx, img);
00107   }
00108 
00109   return !shortread;
00110 }
00111 
00112 static int file_is_y4m(const char detect[4]) {
00113   if (memcmp(detect, "YUV4", 4) == 0) {
00114     return 1;
00115   }
00116   return 0;
00117 }
00118 
00119 static int fourcc_is_ivf(const char detect[4]) {
00120   if (memcmp(detect, "DKIF", 4) == 0) {
00121     return 1;
00122   }
00123   return 0;
00124 }
00125 
00126 static const arg_def_t debugmode =
00127     ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
00128 static const arg_def_t outputfile =
00129     ARG_DEF("o", "output", 1, "Output filename");
00130 static const arg_def_t use_yv12 =
00131     ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
00132 static const arg_def_t use_i420 =
00133     ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
00134 static const arg_def_t use_i422 =
00135     ARG_DEF(NULL, "i422", 0, "Input file is I422");
00136 static const arg_def_t use_i444 =
00137     ARG_DEF(NULL, "i444", 0, "Input file is I444");
00138 static const arg_def_t use_i440 =
00139     ARG_DEF(NULL, "i440", 0, "Input file is I440");
00140 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
00141 static const arg_def_t passes =
00142     ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
00143 static const arg_def_t pass_arg =
00144     ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
00145 static const arg_def_t fpf_name =
00146     ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
00147 #if CONFIG_FP_MB_STATS
00148 static const arg_def_t fpmbf_name =
00149     ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
00150 #endif
00151 static const arg_def_t limit =
00152     ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
00153 static const arg_def_t skip =
00154     ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
00155 static const arg_def_t deadline =
00156     ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
00157 static const arg_def_t best_dl =
00158     ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
00159 static const arg_def_t good_dl =
00160     ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
00161 static const arg_def_t rt_dl =
00162     ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
00163 static const arg_def_t quietarg =
00164     ARG_DEF("q", "quiet", 0, "Do not print encode progress");
00165 static const arg_def_t verbosearg =
00166     ARG_DEF("v", "verbose", 0, "Show encoder parameters");
00167 static const arg_def_t psnrarg =
00168     ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
00169 
00170 static const struct arg_enum_list test_decode_enum[] = {
00171   { "off", TEST_DECODE_OFF },
00172   { "fatal", TEST_DECODE_FATAL },
00173   { "warn", TEST_DECODE_WARN },
00174   { NULL, 0 }
00175 };
00176 static const arg_def_t recontest = ARG_DEF_ENUM(
00177     NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
00178 static const arg_def_t framerate =
00179     ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
00180 static const arg_def_t use_webm =
00181     ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
00182 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
00183 static const arg_def_t out_part =
00184     ARG_DEF("P", "output-partitions", 0,
00185             "Makes encoder output partitions. Requires IVF output!");
00186 static const arg_def_t q_hist_n =
00187     ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
00188 static const arg_def_t rate_hist_n =
00189     ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
00190 static const arg_def_t disable_warnings =
00191     ARG_DEF(NULL, "disable-warnings", 0,
00192             "Disable warnings about potentially incorrect encode settings.");
00193 static const arg_def_t disable_warning_prompt =
00194     ARG_DEF("y", "disable-warning-prompt", 0,
00195             "Display warnings, but do not prompt user to continue.");
00196 
00197 #if CONFIG_VP9_HIGHBITDEPTH
00198 static const arg_def_t test16bitinternalarg = ARG_DEF(
00199     NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
00200 #endif
00201 
00202 static const arg_def_t *main_args[] = { &debugmode,
00203                                         &outputfile,
00204                                         &codecarg,
00205                                         &passes,
00206                                         &pass_arg,
00207                                         &fpf_name,
00208                                         &limit,
00209                                         &skip,
00210                                         &deadline,
00211                                         &best_dl,
00212                                         &good_dl,
00213                                         &rt_dl,
00214                                         &quietarg,
00215                                         &verbosearg,
00216                                         &psnrarg,
00217                                         &use_webm,
00218                                         &use_ivf,
00219                                         &out_part,
00220                                         &q_hist_n,
00221                                         &rate_hist_n,
00222                                         &disable_warnings,
00223                                         &disable_warning_prompt,
00224                                         &recontest,
00225                                         NULL };
00226 
00227 static const arg_def_t usage =
00228     ARG_DEF("u", "usage", 1, "Usage profile number to use");
00229 static const arg_def_t threads =
00230     ARG_DEF("t", "threads", 1, "Max number of threads to use");
00231 static const arg_def_t profile =
00232     ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
00233 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
00234 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
00235 #if CONFIG_WEBM_IO
00236 static const struct arg_enum_list stereo_mode_enum[] = {
00237   { "mono", STEREO_FORMAT_MONO },
00238   { "left-right", STEREO_FORMAT_LEFT_RIGHT },
00239   { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
00240   { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
00241   { "right-left", STEREO_FORMAT_RIGHT_LEFT },
00242   { NULL, 0 }
00243 };
00244 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
00245     NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
00246 #endif
00247 static const arg_def_t timebase = ARG_DEF(
00248     NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
00249 static const arg_def_t error_resilient =
00250     ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
00251 static const arg_def_t lag_in_frames =
00252     ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
00253 
00254 static const arg_def_t *global_args[] = { &use_yv12,
00255                                           &use_i420,
00256                                           &use_i422,
00257                                           &use_i444,
00258                                           &use_i440,
00259                                           &usage,
00260                                           &threads,
00261                                           &profile,
00262                                           &width,
00263                                           &height,
00264 #if CONFIG_WEBM_IO
00265                                           &stereo_mode,
00266 #endif
00267                                           &timebase,
00268                                           &framerate,
00269                                           &error_resilient,
00270 #if CONFIG_VP9_HIGHBITDEPTH
00271                                           &test16bitinternalarg,
00272 #endif
00273                                           &lag_in_frames,
00274                                           NULL };
00275 
00276 static const arg_def_t dropframe_thresh =
00277     ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
00278 static const arg_def_t resize_allowed =
00279     ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
00280 static const arg_def_t resize_width =
00281     ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
00282 static const arg_def_t resize_height =
00283     ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
00284 static const arg_def_t resize_up_thresh =
00285     ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
00286 static const arg_def_t resize_down_thresh =
00287     ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
00288 static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
00289                                                        { "cbr", VPX_CBR },
00290                                                        { "cq", VPX_CQ },
00291                                                        { "q", VPX_Q },
00292                                                        { NULL, 0 } };
00293 static const arg_def_t end_usage =
00294     ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
00295 static const arg_def_t target_bitrate =
00296     ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
00297 static const arg_def_t min_quantizer =
00298     ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
00299 static const arg_def_t max_quantizer =
00300     ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
00301 static const arg_def_t undershoot_pct =
00302     ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
00303 static const arg_def_t overshoot_pct =
00304     ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
00305 static const arg_def_t buf_sz =
00306     ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
00307 static const arg_def_t buf_initial_sz =
00308     ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
00309 static const arg_def_t buf_optimal_sz =
00310     ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
00311 static const arg_def_t *rc_args[] = {
00312   &dropframe_thresh, &resize_allowed,     &resize_width,   &resize_height,
00313   &resize_up_thresh, &resize_down_thresh, &end_usage,      &target_bitrate,
00314   &min_quantizer,    &max_quantizer,      &undershoot_pct, &overshoot_pct,
00315   &buf_sz,           &buf_initial_sz,     &buf_optimal_sz, NULL
00316 };
00317 
00318 static const arg_def_t bias_pct =
00319     ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
00320 static const arg_def_t minsection_pct =
00321     ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
00322 static const arg_def_t maxsection_pct =
00323     ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
00324 static const arg_def_t *rc_twopass_args[] = { &bias_pct, &minsection_pct,
00325                                               &maxsection_pct, NULL };
00326 
00327 static const arg_def_t kf_min_dist =
00328     ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
00329 static const arg_def_t kf_max_dist =
00330     ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
00331 static const arg_def_t kf_disabled =
00332     ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
00333 static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
00334                                       NULL };
00335 
00336 static const arg_def_t noise_sens =
00337     ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
00338 static const arg_def_t sharpness =
00339     ARG_DEF(NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
00340 static const arg_def_t static_thresh =
00341     ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
00342 static const arg_def_t auto_altref =
00343     ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
00344 static const arg_def_t arnr_maxframes =
00345     ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
00346 static const arg_def_t arnr_strength =
00347     ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
00348 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1, "AltRef type");
00349 static const struct arg_enum_list tuning_enum[] = {
00350   { "psnr", VP8_TUNE_PSNR }, { "ssim", VP8_TUNE_SSIM }, { NULL, 0 }
00351 };
00352 static const arg_def_t tune_ssim =
00353     ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
00354 static const arg_def_t cq_level =
00355     ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
00356 static const arg_def_t max_intra_rate_pct =
00357     ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
00358 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
00359     NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
00360 
00361 #if CONFIG_VP8_ENCODER
00362 static const arg_def_t cpu_used_vp8 =
00363     ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
00364 static const arg_def_t token_parts =
00365     ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
00366 static const arg_def_t screen_content_mode =
00367     ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
00368 static const arg_def_t *vp8_args[] = { &cpu_used_vp8,
00369                                        &auto_altref,
00370                                        &noise_sens,
00371                                        &sharpness,
00372                                        &static_thresh,
00373                                        &token_parts,
00374                                        &arnr_maxframes,
00375                                        &arnr_strength,
00376                                        &arnr_type,
00377                                        &tune_ssim,
00378                                        &cq_level,
00379                                        &max_intra_rate_pct,
00380                                        &gf_cbr_boost_pct,
00381                                        &screen_content_mode,
00382                                        NULL };
00383 static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
00384                                         VP8E_SET_ENABLEAUTOALTREF,
00385                                         VP8E_SET_NOISE_SENSITIVITY,
00386                                         VP8E_SET_SHARPNESS,
00387                                         VP8E_SET_STATIC_THRESHOLD,
00388                                         VP8E_SET_TOKEN_PARTITIONS,
00389                                         VP8E_SET_ARNR_MAXFRAMES,
00390                                         VP8E_SET_ARNR_STRENGTH,
00391                                         VP8E_SET_ARNR_TYPE,
00392                                         VP8E_SET_TUNING,
00393                                         VP8E_SET_CQ_LEVEL,
00394                                         VP8E_SET_MAX_INTRA_BITRATE_PCT,
00395                                         VP8E_SET_GF_CBR_BOOST_PCT,
00396                                         VP8E_SET_SCREEN_CONTENT_MODE,
00397                                         0 };
00398 #endif
00399 
00400 #if CONFIG_VP9_ENCODER
00401 static const arg_def_t cpu_used_vp9 =
00402     ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-8..8)");
00403 static const arg_def_t tile_cols =
00404     ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
00405 static const arg_def_t tile_rows =
00406     ARG_DEF(NULL, "tile-rows", 1,
00407             "Number of tile rows to use, log2 (set to 0 while threads > 1)");
00408 static const arg_def_t lossless =
00409     ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
00410 static const arg_def_t frame_parallel_decoding = ARG_DEF(
00411     NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
00412 static const arg_def_t aq_mode = ARG_DEF(
00413     NULL, "aq-mode", 1,
00414     "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
00415     "3: cyclic refresh, 4: equator360)");
00416 static const arg_def_t alt_ref_aq = ARG_DEF(NULL, "alt-ref-aq", 1,
00417                                             "Special adaptive quantization for "
00418                                             "the alternate reference frames.");
00419 static const arg_def_t frame_periodic_boost =
00420     ARG_DEF(NULL, "frame-boost", 1,
00421             "Enable frame periodic boost (0: off (default), 1: on)");
00422 static const arg_def_t max_inter_rate_pct =
00423     ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
00424 static const arg_def_t min_gf_interval = ARG_DEF(
00425     NULL, "min-gf-interval", 1,
00426     "min gf/arf frame interval (default 0, indicating in-built behavior)");
00427 static const arg_def_t max_gf_interval = ARG_DEF(
00428     NULL, "max-gf-interval", 1,
00429     "max gf/arf frame interval (default 0, indicating in-built behavior)");
00430 
00431 static const struct arg_enum_list color_space_enum[] = {
00432   { "unknown", VPX_CS_UNKNOWN },
00433   { "bt601", VPX_CS_BT_601 },
00434   { "bt709", VPX_CS_BT_709 },
00435   { "smpte170", VPX_CS_SMPTE_170 },
00436   { "smpte240", VPX_CS_SMPTE_240 },
00437   { "bt2020", VPX_CS_BT_2020 },
00438   { "reserved", VPX_CS_RESERVED },
00439   { "sRGB", VPX_CS_SRGB },
00440   { NULL, 0 }
00441 };
00442 
00443 static const arg_def_t input_color_space =
00444     ARG_DEF_ENUM(NULL, "color-space", 1, "The color space of input content:",
00445                  color_space_enum);
00446 
00447 #if CONFIG_VP9_HIGHBITDEPTH
00448 static const struct arg_enum_list bitdepth_enum[] = {
00449   { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
00450 };
00451 
00452 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
00453     "b", "bit-depth", 1,
00454     "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
00455     bitdepth_enum);
00456 static const arg_def_t inbitdeptharg =
00457     ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
00458 #endif
00459 
00460 static const struct arg_enum_list tune_content_enum[] = {
00461   { "default", VP9E_CONTENT_DEFAULT },
00462   { "screen", VP9E_CONTENT_SCREEN },
00463   { NULL, 0 }
00464 };
00465 
00466 static const arg_def_t tune_content = ARG_DEF_ENUM(
00467     NULL, "tune-content", 1, "Tune content type", tune_content_enum);
00468 
00469 static const arg_def_t target_level = ARG_DEF(
00470     NULL, "target-level", 1,
00471     "Target level (255: off (default); 0: only keep level stats; 10: level 1.0;"
00472     " 11: level 1.1; ... 62: level 6.2)");
00473 #endif
00474 
00475 #if CONFIG_VP9_ENCODER
00476 static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
00477                                        &auto_altref,
00478                                        &sharpness,
00479                                        &static_thresh,
00480                                        &tile_cols,
00481                                        &tile_rows,
00482                                        &arnr_maxframes,
00483                                        &arnr_strength,
00484                                        &arnr_type,
00485                                        &tune_ssim,
00486                                        &cq_level,
00487                                        &max_intra_rate_pct,
00488                                        &max_inter_rate_pct,
00489                                        &gf_cbr_boost_pct,
00490                                        &lossless,
00491                                        &frame_parallel_decoding,
00492                                        &aq_mode,
00493                                        &alt_ref_aq,
00494                                        &frame_periodic_boost,
00495                                        &noise_sens,
00496                                        &tune_content,
00497                                        &input_color_space,
00498                                        &min_gf_interval,
00499                                        &max_gf_interval,
00500                                        &target_level,
00501 #if CONFIG_VP9_HIGHBITDEPTH
00502                                        &bitdeptharg,
00503                                        &inbitdeptharg,
00504 #endif  // CONFIG_VP9_HIGHBITDEPTH
00505                                        NULL };
00506 static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
00507                                         VP8E_SET_ENABLEAUTOALTREF,
00508                                         VP8E_SET_SHARPNESS,
00509                                         VP8E_SET_STATIC_THRESHOLD,
00510                                         VP9E_SET_TILE_COLUMNS,
00511                                         VP9E_SET_TILE_ROWS,
00512                                         VP8E_SET_ARNR_MAXFRAMES,
00513                                         VP8E_SET_ARNR_STRENGTH,
00514                                         VP8E_SET_ARNR_TYPE,
00515                                         VP8E_SET_TUNING,
00516                                         VP8E_SET_CQ_LEVEL,
00517                                         VP8E_SET_MAX_INTRA_BITRATE_PCT,
00518                                         VP9E_SET_MAX_INTER_BITRATE_PCT,
00519                                         VP9E_SET_GF_CBR_BOOST_PCT,
00520                                         VP9E_SET_LOSSLESS,
00521                                         VP9E_SET_FRAME_PARALLEL_DECODING,
00522                                         VP9E_SET_AQ_MODE,
00523                                         VP9E_SET_ALT_REF_AQ,
00524                                         VP9E_SET_FRAME_PERIODIC_BOOST,
00525                                         VP9E_SET_NOISE_SENSITIVITY,
00526                                         VP9E_SET_TUNE_CONTENT,
00527                                         VP9E_SET_COLOR_SPACE,
00528                                         VP9E_SET_MIN_GF_INTERVAL,
00529                                         VP9E_SET_MAX_GF_INTERVAL,
00530                                         VP9E_SET_TARGET_LEVEL,
00531                                         0 };
00532 #endif
00533 
00534 static const arg_def_t *no_args[] = { NULL };
00535 
00536 void usage_exit(void) {
00537   int i;
00538   const int num_encoder = get_vpx_encoder_count();
00539 
00540   fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
00541           exec_name);
00542 
00543   fprintf(stderr, "\nOptions:\n");
00544   arg_show_usage(stderr, main_args);
00545   fprintf(stderr, "\nEncoder Global Options:\n");
00546   arg_show_usage(stderr, global_args);
00547   fprintf(stderr, "\nRate Control Options:\n");
00548   arg_show_usage(stderr, rc_args);
00549   fprintf(stderr, "\nTwopass Rate Control Options:\n");
00550   arg_show_usage(stderr, rc_twopass_args);
00551   fprintf(stderr, "\nKeyframe Placement Options:\n");
00552   arg_show_usage(stderr, kf_args);
00553 #if CONFIG_VP8_ENCODER
00554   fprintf(stderr, "\nVP8 Specific Options:\n");
00555   arg_show_usage(stderr, vp8_args);
00556 #endif
00557 #if CONFIG_VP9_ENCODER
00558   fprintf(stderr, "\nVP9 Specific Options:\n");
00559   arg_show_usage(stderr, vp9_args);
00560 #endif
00561   fprintf(stderr,
00562           "\nStream timebase (--timebase):\n"
00563           "  The desired precision of timestamps in the output, expressed\n"
00564           "  in fractional seconds. Default is 1/1000.\n");
00565   fprintf(stderr, "\nIncluded encoders:\n\n");
00566 
00567   for (i = 0; i < num_encoder; ++i) {
00568     const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
00569     const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
00570     fprintf(stderr, "    %-6s - %s %s\n", encoder->name,
00571             vpx_codec_iface_name(encoder->codec_interface()), defstr);
00572   }
00573   fprintf(stderr, "\n        ");
00574   fprintf(stderr, "Use --codec to switch to a non-default encoder.\n\n");
00575 
00576   exit(EXIT_FAILURE);
00577 }
00578 
00579 #define mmin(a, b) ((a) < (b) ? (a) : (b))
00580 
00581 #if CONFIG_VP9_HIGHBITDEPTH
00582 static void find_mismatch_high(const vpx_image_t *const img1,
00583                                const vpx_image_t *const img2, int yloc[4],
00584                                int uloc[4], int vloc[4]) {
00585   uint16_t *plane1, *plane2;
00586   uint32_t stride1, stride2;
00587   const uint32_t bsize = 64;
00588   const uint32_t bsizey = bsize >> img1->y_chroma_shift;
00589   const uint32_t bsizex = bsize >> img1->x_chroma_shift;
00590   const uint32_t c_w =
00591       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
00592   const uint32_t c_h =
00593       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
00594   int match = 1;
00595   uint32_t i, j;
00596   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
00597   plane1 = (uint16_t *)img1->planes[VPX_PLANE_Y];
00598   plane2 = (uint16_t *)img2->planes[VPX_PLANE_Y];
00599   stride1 = img1->stride[VPX_PLANE_Y] / 2;
00600   stride2 = img2->stride[VPX_PLANE_Y] / 2;
00601   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
00602     for (j = 0; match && j < img1->d_w; j += bsize) {
00603       int k, l;
00604       const int si = mmin(i + bsize, img1->d_h) - i;
00605       const int sj = mmin(j + bsize, img1->d_w) - j;
00606       for (k = 0; match && k < si; ++k) {
00607         for (l = 0; match && l < sj; ++l) {
00608           if (*(plane1 + (i + k) * stride1 + j + l) !=
00609               *(plane2 + (i + k) * stride2 + j + l)) {
00610             yloc[0] = i + k;
00611             yloc[1] = j + l;
00612             yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
00613             yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
00614             match = 0;
00615             break;
00616           }
00617         }
00618       }
00619     }
00620   }
00621 
00622   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
00623   plane1 = (uint16_t *)img1->planes[VPX_PLANE_U];
00624   plane2 = (uint16_t *)img2->planes[VPX_PLANE_U];
00625   stride1 = img1->stride[VPX_PLANE_U] / 2;
00626   stride2 = img2->stride[VPX_PLANE_U] / 2;
00627   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
00628     for (j = 0; match && j < c_w; j += bsizex) {
00629       int k, l;
00630       const int si = mmin(i + bsizey, c_h - i);
00631       const int sj = mmin(j + bsizex, c_w - j);
00632       for (k = 0; match && k < si; ++k) {
00633         for (l = 0; match && l < sj; ++l) {
00634           if (*(plane1 + (i + k) * stride1 + j + l) !=
00635               *(plane2 + (i + k) * stride2 + j + l)) {
00636             uloc[0] = i + k;
00637             uloc[1] = j + l;
00638             uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
00639             uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
00640             match = 0;
00641             break;
00642           }
00643         }
00644       }
00645     }
00646   }
00647 
00648   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
00649   plane1 = (uint16_t *)img1->planes[VPX_PLANE_V];
00650   plane2 = (uint16_t *)img2->planes[VPX_PLANE_V];
00651   stride1 = img1->stride[VPX_PLANE_V] / 2;
00652   stride2 = img2->stride[VPX_PLANE_V] / 2;
00653   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
00654     for (j = 0; match && j < c_w; j += bsizex) {
00655       int k, l;
00656       const int si = mmin(i + bsizey, c_h - i);
00657       const int sj = mmin(j + bsizex, c_w - j);
00658       for (k = 0; match && k < si; ++k) {
00659         for (l = 0; match && l < sj; ++l) {
00660           if (*(plane1 + (i + k) * stride1 + j + l) !=
00661               *(plane2 + (i + k) * stride2 + j + l)) {
00662             vloc[0] = i + k;
00663             vloc[1] = j + l;
00664             vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
00665             vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
00666             match = 0;
00667             break;
00668           }
00669         }
00670       }
00671     }
00672   }
00673 }
00674 #endif
00675 
00676 static void find_mismatch(const vpx_image_t *const img1,
00677                           const vpx_image_t *const img2, int yloc[4],
00678                           int uloc[4], int vloc[4]) {
00679   const uint32_t bsize = 64;
00680   const uint32_t bsizey = bsize >> img1->y_chroma_shift;
00681   const uint32_t bsizex = bsize >> img1->x_chroma_shift;
00682   const uint32_t c_w =
00683       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
00684   const uint32_t c_h =
00685       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
00686   int match = 1;
00687   uint32_t i, j;
00688   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
00689   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
00690     for (j = 0; match && j < img1->d_w; j += bsize) {
00691       int k, l;
00692       const int si = mmin(i + bsize, img1->d_h) - i;
00693       const int sj = mmin(j + bsize, img1->d_w) - j;
00694       for (k = 0; match && k < si; ++k) {
00695         for (l = 0; match && l < sj; ++l) {
00696           if (*(img1->planes[VPX_PLANE_Y] +
00697                 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
00698               *(img2->planes[VPX_PLANE_Y] +
00699                 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
00700             yloc[0] = i + k;
00701             yloc[1] = j + l;
00702             yloc[2] = *(img1->planes[VPX_PLANE_Y] +
00703                         (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
00704             yloc[3] = *(img2->planes[VPX_PLANE_Y] +
00705                         (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
00706             match = 0;
00707             break;
00708           }
00709         }
00710       }
00711     }
00712   }
00713 
00714   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
00715   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
00716     for (j = 0; match && j < c_w; j += bsizex) {
00717       int k, l;
00718       const int si = mmin(i + bsizey, c_h - i);
00719       const int sj = mmin(j + bsizex, c_w - j);
00720       for (k = 0; match && k < si; ++k) {
00721         for (l = 0; match && l < sj; ++l) {
00722           if (*(img1->planes[VPX_PLANE_U] +
00723                 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
00724               *(img2->planes[VPX_PLANE_U] +
00725                 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
00726             uloc[0] = i + k;
00727             uloc[1] = j + l;
00728             uloc[2] = *(img1->planes[VPX_PLANE_U] +
00729                         (i + k) * img1->stride[VPX_PLANE_U] + j + l);
00730             uloc[3] = *(img2->planes[VPX_PLANE_U] +
00731                         (i + k) * img2->stride[VPX_PLANE_U] + j + l);
00732             match = 0;
00733             break;
00734           }
00735         }
00736       }
00737     }
00738   }
00739   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
00740   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
00741     for (j = 0; match && j < c_w; j += bsizex) {
00742       int k, l;
00743       const int si = mmin(i + bsizey, c_h - i);
00744       const int sj = mmin(j + bsizex, c_w - j);
00745       for (k = 0; match && k < si; ++k) {
00746         for (l = 0; match && l < sj; ++l) {
00747           if (*(img1->planes[VPX_PLANE_V] +
00748                 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
00749               *(img2->planes[VPX_PLANE_V] +
00750                 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
00751             vloc[0] = i + k;
00752             vloc[1] = j + l;
00753             vloc[2] = *(img1->planes[VPX_PLANE_V] +
00754                         (i + k) * img1->stride[VPX_PLANE_V] + j + l);
00755             vloc[3] = *(img2->planes[VPX_PLANE_V] +
00756                         (i + k) * img2->stride[VPX_PLANE_V] + j + l);
00757             match = 0;
00758             break;
00759           }
00760         }
00761       }
00762     }
00763   }
00764 }
00765 
00766 static int compare_img(const vpx_image_t *const img1,
00767                        const vpx_image_t *const img2) {
00768   uint32_t l_w = img1->d_w;
00769   uint32_t c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
00770   const uint32_t c_h =
00771       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
00772   uint32_t i;
00773   int match = 1;
00774 
00775   match &= (img1->fmt == img2->fmt);
00776   match &= (img1->d_w == img2->d_w);
00777   match &= (img1->d_h == img2->d_h);
00778 #if CONFIG_VP9_HIGHBITDEPTH
00779   if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
00780     l_w *= 2;
00781     c_w *= 2;
00782   }
00783 #endif
00784 
00785   for (i = 0; i < img1->d_h; ++i)
00786     match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
00787                      img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
00788                      l_w) == 0);
00789 
00790   for (i = 0; i < c_h; ++i)
00791     match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
00792                      img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
00793                      c_w) == 0);
00794 
00795   for (i = 0; i < c_h; ++i)
00796     match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
00797                      img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
00798                      c_w) == 0);
00799 
00800   return match;
00801 }
00802 
00803 #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
00804 #if CONFIG_VP9_ENCODER
00805 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
00806 #else
00807 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
00808 #endif
00809 
00810 #if !CONFIG_WEBM_IO
00811 typedef int stereo_format_t;
00812 struct WebmOutputContext {
00813   int debug;
00814 };
00815 #endif
00816 
00817 /* Per-stream configuration */
00818 struct stream_config {
00819   struct vpx_codec_enc_cfg cfg;
00820   const char *out_fn;
00821   const char *stats_fn;
00822 #if CONFIG_FP_MB_STATS
00823   const char *fpmb_stats_fn;
00824 #endif
00825   stereo_format_t stereo_fmt;
00826   int arg_ctrls[ARG_CTRL_CNT_MAX][2];
00827   int arg_ctrl_cnt;
00828   int write_webm;
00829 #if CONFIG_VP9_HIGHBITDEPTH
00830   // whether to use 16bit internal buffers
00831   int use_16bit_internal;
00832 #endif
00833 };
00834 
00835 struct stream_state {
00836   int index;
00837   struct stream_state *next;
00838   struct stream_config config;
00839   FILE *file;
00840   struct rate_hist *rate_hist;
00841   struct WebmOutputContext webm_ctx;
00842   uint64_t psnr_sse_total;
00843   uint64_t psnr_samples_total;
00844   double psnr_totals[4];
00845   int psnr_count;
00846   int counts[64];
00847   vpx_codec_ctx_t encoder;
00848   unsigned int frames_out;
00849   uint64_t cx_time;
00850   size_t nbytes;
00851   stats_io_t stats;
00852 #if CONFIG_FP_MB_STATS
00853   stats_io_t fpmb_stats;
00854 #endif
00855   struct vpx_image *img;
00856   vpx_codec_ctx_t decoder;
00857   int mismatch_seen;
00858 };
00859 
00860 static void validate_positive_rational(const char *msg,
00861                                        struct vpx_rational *rat) {
00862   if (rat->den < 0) {
00863     rat->num *= -1;
00864     rat->den *= -1;
00865   }
00866 
00867   if (rat->num < 0) die("Error: %s must be positive\n", msg);
00868 
00869   if (!rat->den) die("Error: %s has zero denominator\n", msg);
00870 }
00871 
00872 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
00873   char **argi, **argj;
00874   struct arg arg;
00875   const int num_encoder = get_vpx_encoder_count();
00876 
00877   if (num_encoder < 1) die("Error: no valid encoder available\n");
00878 
00879   /* Initialize default parameters */
00880   memset(global, 0, sizeof(*global));
00881   global->codec = get_vpx_encoder_by_index(num_encoder - 1);
00882   global->passes = 0;
00883   global->color_type = I420;
00884   /* Assign default deadline to good quality */
00885   global->deadline = VPX_DL_GOOD_QUALITY;
00886 
00887   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
00888     arg.argv_step = 1;
00889 
00890     if (arg_match(&arg, &codecarg, argi)) {
00891       global->codec = get_vpx_encoder_by_name(arg.val);
00892       if (!global->codec)
00893         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
00894     } else if (arg_match(&arg, &passes, argi)) {
00895       global->passes = arg_parse_uint(&arg);
00896 
00897       if (global->passes < 1 || global->passes > 2)
00898         die("Error: Invalid number of passes (%d)\n", global->passes);
00899     } else if (arg_match(&arg, &pass_arg, argi)) {
00900       global->pass = arg_parse_uint(&arg);
00901 
00902       if (global->pass < 1 || global->pass > 2)
00903         die("Error: Invalid pass selected (%d)\n", global->pass);
00904     } else if (arg_match(&arg, &usage, argi))
00905       global->usage = arg_parse_uint(&arg);
00906     else if (arg_match(&arg, &deadline, argi))
00907       global->deadline = arg_parse_uint(&arg);
00908     else if (arg_match(&arg, &best_dl, argi))
00909       global->deadline = VPX_DL_BEST_QUALITY;
00910     else if (arg_match(&arg, &good_dl, argi))
00911       global->deadline = VPX_DL_GOOD_QUALITY;
00912     else if (arg_match(&arg, &rt_dl, argi))
00913       global->deadline = VPX_DL_REALTIME;
00914     else if (arg_match(&arg, &use_yv12, argi))
00915       global->color_type = YV12;
00916     else if (arg_match(&arg, &use_i420, argi))
00917       global->color_type = I420;
00918     else if (arg_match(&arg, &use_i422, argi))
00919       global->color_type = I422;
00920     else if (arg_match(&arg, &use_i444, argi))
00921       global->color_type = I444;
00922     else if (arg_match(&arg, &use_i440, argi))
00923       global->color_type = I440;
00924     else if (arg_match(&arg, &quietarg, argi))
00925       global->quiet = 1;
00926     else if (arg_match(&arg, &verbosearg, argi))
00927       global->verbose = 1;
00928     else if (arg_match(&arg, &limit, argi))
00929       global->limit = arg_parse_uint(&arg);
00930     else if (arg_match(&arg, &skip, argi))
00931       global->skip_frames = arg_parse_uint(&arg);
00932     else if (arg_match(&arg, &psnrarg, argi))
00933       global->show_psnr = 1;
00934     else if (arg_match(&arg, &recontest, argi))
00935       global->test_decode = arg_parse_enum_or_int(&arg);
00936     else if (arg_match(&arg, &framerate, argi)) {
00937       global->framerate = arg_parse_rational(&arg);
00938       validate_positive_rational(arg.name, &global->framerate);
00939       global->have_framerate = 1;
00940     } else if (arg_match(&arg, &out_part, argi))
00941       global->out_part = 1;
00942     else if (arg_match(&arg, &debugmode, argi))
00943       global->debug = 1;
00944     else if (arg_match(&arg, &q_hist_n, argi))
00945       global->show_q_hist_buckets = arg_parse_uint(&arg);
00946     else if (arg_match(&arg, &rate_hist_n, argi))
00947       global->show_rate_hist_buckets = arg_parse_uint(&arg);
00948     else if (arg_match(&arg, &disable_warnings, argi))
00949       global->disable_warnings = 1;
00950     else if (arg_match(&arg, &disable_warning_prompt, argi))
00951       global->disable_warning_prompt = 1;
00952     else
00953       argj++;
00954   }
00955 
00956   if (global->pass) {
00957     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
00958     if (global->pass > global->passes) {
00959       warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
00960            global->pass);
00961       global->passes = global->pass;
00962     }
00963   }
00964   /* Validate global config */
00965   if (global->passes == 0) {
00966 #if CONFIG_VP9_ENCODER
00967     // Make default VP9 passes = 2 until there is a better quality 1-pass
00968     // encoder
00969     if (global->codec != NULL && global->codec->name != NULL)
00970       global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
00971                         global->deadline != VPX_DL_REALTIME)
00972                            ? 2
00973                            : 1;
00974 #else
00975     global->passes = 1;
00976 #endif
00977   }
00978 
00979   if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
00980     warn("Enforcing one-pass encoding in realtime mode\n");
00981     global->passes = 1;
00982   }
00983 }
00984 
00985 static void open_input_file(struct VpxInputContext *input) {
00986   /* Parse certain options from the input file, if possible */
00987   input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
00988                                              : set_binary_mode(stdin);
00989 
00990   if (!input->file) fatal("Failed to open input file");
00991 
00992   if (!fseeko(input->file, 0, SEEK_END)) {
00993     /* Input file is seekable. Figure out how long it is, so we can get
00994      * progress info.
00995      */
00996     input->length = ftello(input->file);
00997     rewind(input->file);
00998   }
00999 
01000   /* Default to 1:1 pixel aspect ratio. */
01001   input->pixel_aspect_ratio.numerator = 1;
01002   input->pixel_aspect_ratio.denominator = 1;
01003 
01004   /* For RAW input sources, these bytes will applied on the first frame
01005    *  in read_frame().
01006    */
01007   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
01008   input->detect.position = 0;
01009 
01010   if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
01011     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
01012                        input->only_i420) >= 0) {
01013       input->file_type = FILE_TYPE_Y4M;
01014       input->width = input->y4m.pic_w;
01015       input->height = input->y4m.pic_h;
01016       input->pixel_aspect_ratio.numerator = input->y4m.par_n;
01017       input->pixel_aspect_ratio.denominator = input->y4m.par_d;
01018       input->framerate.numerator = input->y4m.fps_n;
01019       input->framerate.denominator = input->y4m.fps_d;
01020       input->fmt = input->y4m.vpx_fmt;
01021       input->bit_depth = input->y4m.bit_depth;
01022     } else
01023       fatal("Unsupported Y4M stream.");
01024   } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
01025     fatal("IVF is not supported as input.");
01026   } else {
01027     input->file_type = FILE_TYPE_RAW;
01028   }
01029 }
01030 
01031 static void close_input_file(struct VpxInputContext *input) {
01032   fclose(input->file);
01033   if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
01034 }
01035 
01036 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
01037                                        struct stream_state *prev) {
01038   struct stream_state *stream;
01039 
01040   stream = calloc(1, sizeof(*stream));
01041   if (stream == NULL) {
01042     fatal("Failed to allocate new stream.");
01043   }
01044 
01045   if (prev) {
01046     memcpy(stream, prev, sizeof(*stream));
01047     stream->index++;
01048     prev->next = stream;
01049   } else {
01050     vpx_codec_err_t res;
01051 
01052     /* Populate encoder configuration */
01053     res = vpx_codec_enc_config_default(global->codec->codec_interface(),
01054                                        &stream->config.cfg, global->usage);
01055     if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
01056 
01057     /* Change the default timebase to a high enough value so that the
01058      * encoder will always create strictly increasing timestamps.
01059      */
01060     stream->config.cfg.g_timebase.den = 1000;
01061 
01062     /* Never use the library's default resolution, require it be parsed
01063      * from the file or set on the command line.
01064      */
01065     stream->config.cfg.g_w = 0;
01066     stream->config.cfg.g_h = 0;
01067 
01068     /* Initialize remaining stream parameters */
01069     stream->config.write_webm = 1;
01070 #if CONFIG_WEBM_IO
01071     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
01072     stream->webm_ctx.last_pts_ns = -1;
01073     stream->webm_ctx.writer = NULL;
01074     stream->webm_ctx.segment = NULL;
01075 #endif
01076 
01077     /* Allows removal of the application version from the EBML tags */
01078     stream->webm_ctx.debug = global->debug;
01079 
01080     /* Default lag_in_frames is 0 in realtime mode CBR mode*/
01081     if (global->deadline == VPX_DL_REALTIME &&
01082         stream->config.cfg.rc_end_usage == 1)
01083       stream->config.cfg.g_lag_in_frames = 0;
01084   }
01085 
01086   /* Output files must be specified for each stream */
01087   stream->config.out_fn = NULL;
01088 
01089   stream->next = NULL;
01090   return stream;
01091 }
01092 
01093 static int parse_stream_params(struct VpxEncoderConfig *global,
01094                                struct stream_state *stream, char **argv) {
01095   char **argi, **argj;
01096   struct arg arg;
01097   static const arg_def_t **ctrl_args = no_args;
01098   static const int *ctrl_args_map = NULL;
01099   struct stream_config *config = &stream->config;
01100   int eos_mark_found = 0;
01101 #if CONFIG_VP9_HIGHBITDEPTH
01102   int test_16bit_internal = 0;
01103 #endif
01104 
01105   // Handle codec specific options
01106   if (0) {
01107 #if CONFIG_VP8_ENCODER
01108   } else if (strcmp(global->codec->name, "vp8") == 0) {
01109     ctrl_args = vp8_args;
01110     ctrl_args_map = vp8_arg_ctrl_map;
01111 #endif
01112 #if CONFIG_VP9_ENCODER
01113   } else if (strcmp(global->codec->name, "vp9") == 0) {
01114     ctrl_args = vp9_args;
01115     ctrl_args_map = vp9_arg_ctrl_map;
01116 #endif
01117   }
01118 
01119   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
01120     arg.argv_step = 1;
01121 
01122     /* Once we've found an end-of-stream marker (--) we want to continue
01123      * shifting arguments but not consuming them.
01124      */
01125     if (eos_mark_found) {
01126       argj++;
01127       continue;
01128     } else if (!strcmp(*argj, "--")) {
01129       eos_mark_found = 1;
01130       continue;
01131     }
01132 
01133     if (arg_match(&arg, &outputfile, argi)) {
01134       config->out_fn = arg.val;
01135     } else if (arg_match(&arg, &fpf_name, argi)) {
01136       config->stats_fn = arg.val;
01137 #if CONFIG_FP_MB_STATS
01138     } else if (arg_match(&arg, &fpmbf_name, argi)) {
01139       config->fpmb_stats_fn = arg.val;
01140 #endif
01141     } else if (arg_match(&arg, &use_webm, argi)) {
01142 #if CONFIG_WEBM_IO
01143       config->write_webm = 1;
01144 #else
01145       die("Error: --webm specified but webm is disabled.");
01146 #endif
01147     } else if (arg_match(&arg, &use_ivf, argi)) {
01148       config->write_webm = 0;
01149     } else if (arg_match(&arg, &threads, argi)) {
01150       config->cfg.g_threads = arg_parse_uint(&arg);
01151     } else if (arg_match(&arg, &profile, argi)) {
01152       config->cfg.g_profile = arg_parse_uint(&arg);
01153     } else if (arg_match(&arg, &width, argi)) {
01154       config->cfg.g_w = arg_parse_uint(&arg);
01155     } else if (arg_match(&arg, &height, argi)) {
01156       config->cfg.g_h = arg_parse_uint(&arg);
01157 #if CONFIG_VP9_HIGHBITDEPTH
01158     } else if (arg_match(&arg, &bitdeptharg, argi)) {
01159       config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
01160     } else if (arg_match(&arg, &inbitdeptharg, argi)) {
01161       config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
01162 #endif
01163 #if CONFIG_WEBM_IO
01164     } else if (arg_match(&arg, &stereo_mode, argi)) {
01165       config->stereo_fmt = arg_parse_enum_or_int(&arg);
01166 #endif
01167     } else if (arg_match(&arg, &timebase, argi)) {
01168       config->cfg.g_timebase = arg_parse_rational(&arg);
01169       validate_positive_rational(arg.name, &config->cfg.g_timebase);
01170     } else if (arg_match(&arg, &error_resilient, argi)) {
01171       config->cfg.g_error_resilient = arg_parse_uint(&arg);
01172     } else if (arg_match(&arg, &end_usage, argi)) {
01173       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
01174     } else if (arg_match(&arg, &lag_in_frames, argi)) {
01175       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
01176       if (global->deadline == VPX_DL_REALTIME &&
01177           config->cfg.rc_end_usage == VPX_CBR &&
01178           config->cfg.g_lag_in_frames != 0) {
01179         warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
01180         config->cfg.g_lag_in_frames = 0;
01181       }
01182     } else if (arg_match(&arg, &dropframe_thresh, argi)) {
01183       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
01184     } else if (arg_match(&arg, &resize_allowed, argi)) {
01185       config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
01186     } else if (arg_match(&arg, &resize_width, argi)) {
01187       config->cfg.rc_scaled_width = arg_parse_uint(&arg);
01188     } else if (arg_match(&arg, &resize_height, argi)) {
01189       config->cfg.rc_scaled_height = arg_parse_uint(&arg);
01190     } else if (arg_match(&arg, &resize_up_thresh, argi)) {
01191       config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
01192     } else if (arg_match(&arg, &resize_down_thresh, argi)) {
01193       config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
01194     } else if (arg_match(&arg, &end_usage, argi)) {
01195       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
01196     } else if (arg_match(&arg, &target_bitrate, argi)) {
01197       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
01198     } else if (arg_match(&arg, &min_quantizer, argi)) {
01199       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
01200     } else if (arg_match(&arg, &max_quantizer, argi)) {
01201       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
01202     } else if (arg_match(&arg, &undershoot_pct, argi)) {
01203       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
01204     } else if (arg_match(&arg, &overshoot_pct, argi)) {
01205       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
01206     } else if (arg_match(&arg, &buf_sz, argi)) {
01207       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
01208     } else if (arg_match(&arg, &buf_initial_sz, argi)) {
01209       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
01210     } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
01211       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
01212     } else if (arg_match(&arg, &bias_pct, argi)) {
01213       config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
01214       if (global->passes < 2)
01215         warn("option %s ignored in one-pass mode.\n", arg.name);
01216     } else if (arg_match(&arg, &minsection_pct, argi)) {
01217       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
01218 
01219       if (global->passes < 2)
01220         warn("option %s ignored in one-pass mode.\n", arg.name);
01221     } else if (arg_match(&arg, &maxsection_pct, argi)) {
01222       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
01223 
01224       if (global->passes < 2)
01225         warn("option %s ignored in one-pass mode.\n", arg.name);
01226     } else if (arg_match(&arg, &kf_min_dist, argi)) {
01227       config->cfg.kf_min_dist = arg_parse_uint(&arg);
01228     } else if (arg_match(&arg, &kf_max_dist, argi)) {
01229       config->cfg.kf_max_dist = arg_parse_uint(&arg);
01230     } else if (arg_match(&arg, &kf_disabled, argi)) {
01231       config->cfg.kf_mode = VPX_KF_DISABLED;
01232 #if CONFIG_VP9_HIGHBITDEPTH
01233     } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
01234       if (strcmp(global->codec->name, "vp9") == 0) {
01235         test_16bit_internal = 1;
01236       }
01237 #endif
01238     } else {
01239       int i, match = 0;
01240       for (i = 0; ctrl_args[i]; i++) {
01241         if (arg_match(&arg, ctrl_args[i], argi)) {
01242           int j;
01243           match = 1;
01244 
01245           /* Point either to the next free element or the first
01246           * instance of this control.
01247           */
01248           for (j = 0; j < config->arg_ctrl_cnt; j++)
01249             if (ctrl_args_map != NULL &&
01250                 config->arg_ctrls[j][0] == ctrl_args_map[i])
01251               break;
01252 
01253           /* Update/insert */
01254           assert(j < (int)ARG_CTRL_CNT_MAX);
01255           if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
01256             config->arg_ctrls[j][0] = ctrl_args_map[i];
01257             config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
01258             if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
01259           }
01260         }
01261       }
01262       if (!match) argj++;
01263     }
01264   }
01265 #if CONFIG_VP9_HIGHBITDEPTH
01266   if (strcmp(global->codec->name, "vp9") == 0) {
01267     config->use_16bit_internal =
01268         test_16bit_internal | (config->cfg.g_profile > 1);
01269   }
01270 #endif
01271   return eos_mark_found;
01272 }
01273 
01274 #define FOREACH_STREAM(func)                                \
01275   do {                                                      \
01276     struct stream_state *stream;                            \
01277     for (stream = streams; stream; stream = stream->next) { \
01278       func;                                                 \
01279     }                                                       \
01280   } while (0)
01281 
01282 static void validate_stream_config(const struct stream_state *stream,
01283                                    const struct VpxEncoderConfig *global) {
01284   const struct stream_state *streami;
01285   (void)global;
01286 
01287   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
01288     fatal(
01289         "Stream %d: Specify stream dimensions with --width (-w) "
01290         " and --height (-h)",
01291         stream->index);
01292 
01293   // Check that the codec bit depth is greater than the input bit depth.
01294   if (stream->config.cfg.g_input_bit_depth >
01295       (unsigned int)stream->config.cfg.g_bit_depth) {
01296     fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
01297           stream->index, (int)stream->config.cfg.g_bit_depth,
01298           stream->config.cfg.g_input_bit_depth);
01299   }
01300 
01301   for (streami = stream; streami; streami = streami->next) {
01302     /* All streams require output files */
01303     if (!streami->config.out_fn)
01304       fatal("Stream %d: Output file is required (specify with -o)",
01305             streami->index);
01306 
01307     /* Check for two streams outputting to the same file */
01308     if (streami != stream) {
01309       const char *a = stream->config.out_fn;
01310       const char *b = streami->config.out_fn;
01311       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
01312         fatal("Stream %d: duplicate output file (from stream %d)",
01313               streami->index, stream->index);
01314     }
01315 
01316     /* Check for two streams sharing a stats file. */
01317     if (streami != stream) {
01318       const char *a = stream->config.stats_fn;
01319       const char *b = streami->config.stats_fn;
01320       if (a && b && !strcmp(a, b))
01321         fatal("Stream %d: duplicate stats file (from stream %d)",
01322               streami->index, stream->index);
01323     }
01324 
01325 #if CONFIG_FP_MB_STATS
01326     /* Check for two streams sharing a mb stats file. */
01327     if (streami != stream) {
01328       const char *a = stream->config.fpmb_stats_fn;
01329       const char *b = streami->config.fpmb_stats_fn;
01330       if (a && b && !strcmp(a, b))
01331         fatal("Stream %d: duplicate mb stats file (from stream %d)",
01332               streami->index, stream->index);
01333     }
01334 #endif
01335   }
01336 }
01337 
01338 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
01339                                   unsigned int h) {
01340   if (!stream->config.cfg.g_w) {
01341     if (!stream->config.cfg.g_h)
01342       stream->config.cfg.g_w = w;
01343     else
01344       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
01345   }
01346   if (!stream->config.cfg.g_h) {
01347     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
01348   }
01349 }
01350 
01351 static const char *file_type_to_string(enum VideoFileType t) {
01352   switch (t) {
01353     case FILE_TYPE_RAW: return "RAW";
01354     case FILE_TYPE_Y4M: return "Y4M";
01355     default: return "Other";
01356   }
01357 }
01358 
01359 static const char *image_format_to_string(vpx_img_fmt_t f) {
01360   switch (f) {
01361     case VPX_IMG_FMT_I420: return "I420";
01362     case VPX_IMG_FMT_I422: return "I422";
01363     case VPX_IMG_FMT_I444: return "I444";
01364     case VPX_IMG_FMT_I440: return "I440";
01365     case VPX_IMG_FMT_YV12: return "YV12";
01366     case VPX_IMG_FMT_I42016: return "I42016";
01367     case VPX_IMG_FMT_I42216: return "I42216";
01368     case VPX_IMG_FMT_I44416: return "I44416";
01369     case VPX_IMG_FMT_I44016: return "I44016";
01370     default: return "Other";
01371   }
01372 }
01373 
01374 static void show_stream_config(struct stream_state *stream,
01375                                struct VpxEncoderConfig *global,
01376                                struct VpxInputContext *input) {
01377 #define SHOW(field) \
01378   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
01379 
01380   if (stream->index == 0) {
01381     fprintf(stderr, "Codec: %s\n",
01382             vpx_codec_iface_name(global->codec->codec_interface()));
01383     fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
01384             input->filename, file_type_to_string(input->file_type),
01385             image_format_to_string(input->fmt));
01386   }
01387   if (stream->next || stream->index)
01388     fprintf(stderr, "\nStream Index: %d\n", stream->index);
01389   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
01390   fprintf(stderr, "Encoder parameters:\n");
01391 
01392   SHOW(g_usage);
01393   SHOW(g_threads);
01394   SHOW(g_profile);
01395   SHOW(g_w);
01396   SHOW(g_h);
01397   SHOW(g_bit_depth);
01398   SHOW(g_input_bit_depth);
01399   SHOW(g_timebase.num);
01400   SHOW(g_timebase.den);
01401   SHOW(g_error_resilient);
01402   SHOW(g_pass);
01403   SHOW(g_lag_in_frames);
01404   SHOW(rc_dropframe_thresh);
01405   SHOW(rc_resize_allowed);
01406   SHOW(rc_scaled_width);
01407   SHOW(rc_scaled_height);
01408   SHOW(rc_resize_up_thresh);
01409   SHOW(rc_resize_down_thresh);
01410   SHOW(rc_end_usage);
01411   SHOW(rc_target_bitrate);
01412   SHOW(rc_min_quantizer);
01413   SHOW(rc_max_quantizer);
01414   SHOW(rc_undershoot_pct);
01415   SHOW(rc_overshoot_pct);
01416   SHOW(rc_buf_sz);
01417   SHOW(rc_buf_initial_sz);
01418   SHOW(rc_buf_optimal_sz);
01419   SHOW(rc_2pass_vbr_bias_pct);
01420   SHOW(rc_2pass_vbr_minsection_pct);
01421   SHOW(rc_2pass_vbr_maxsection_pct);
01422   SHOW(kf_mode);
01423   SHOW(kf_min_dist);
01424   SHOW(kf_max_dist);
01425 }
01426 
01427 static void open_output_file(struct stream_state *stream,
01428                              struct VpxEncoderConfig *global,
01429                              const struct VpxRational *pixel_aspect_ratio) {
01430   const char *fn = stream->config.out_fn;
01431   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
01432 
01433   if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
01434 
01435   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
01436 
01437   if (!stream->file) fatal("Failed to open output file");
01438 
01439   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
01440     fatal("WebM output to pipes not supported.");
01441 
01442 #if CONFIG_WEBM_IO
01443   if (stream->config.write_webm) {
01444     stream->webm_ctx.stream = stream->file;
01445     write_webm_file_header(&stream->webm_ctx, cfg, stream->config.stereo_fmt,
01446                            global->codec->fourcc, pixel_aspect_ratio);
01447   }
01448 #else
01449   (void)pixel_aspect_ratio;
01450 #endif
01451 
01452   if (!stream->config.write_webm) {
01453     ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
01454   }
01455 }
01456 
01457 static void close_output_file(struct stream_state *stream,
01458                               unsigned int fourcc) {
01459   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
01460 
01461   if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
01462 
01463 #if CONFIG_WEBM_IO
01464   if (stream->config.write_webm) {
01465     write_webm_file_footer(&stream->webm_ctx);
01466   }
01467 #endif
01468 
01469   if (!stream->config.write_webm) {
01470     if (!fseek(stream->file, 0, SEEK_SET))
01471       ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
01472                             stream->frames_out);
01473   }
01474 
01475   fclose(stream->file);
01476 }
01477 
01478 static void setup_pass(struct stream_state *stream,
01479                        struct VpxEncoderConfig *global, int pass) {
01480   if (stream->config.stats_fn) {
01481     if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
01482       fatal("Failed to open statistics store");
01483   } else {
01484     if (!stats_open_mem(&stream->stats, pass))
01485       fatal("Failed to open statistics store");
01486   }
01487 
01488 #if CONFIG_FP_MB_STATS
01489   if (stream->config.fpmb_stats_fn) {
01490     if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
01491                          pass))
01492       fatal("Failed to open mb statistics store");
01493   } else {
01494     if (!stats_open_mem(&stream->fpmb_stats, pass))
01495       fatal("Failed to open mb statistics store");
01496   }
01497 #endif
01498 
01499   stream->config.cfg.g_pass = global->passes == 2
01500                                   ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
01501                                   : VPX_RC_ONE_PASS;
01502   if (pass) {
01503     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
01504 #if CONFIG_FP_MB_STATS
01505     stream->config.cfg.rc_firstpass_mb_stats_in =
01506         stats_get(&stream->fpmb_stats);
01507 #endif
01508   }
01509 
01510   stream->cx_time = 0;
01511   stream->nbytes = 0;
01512   stream->frames_out = 0;
01513 }
01514 
01515 static void initialize_encoder(struct stream_state *stream,
01516                                struct VpxEncoderConfig *global) {
01517   int i;
01518   int flags = 0;
01519 
01520   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
01521   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
01522 #if CONFIG_VP9_HIGHBITDEPTH
01523   flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
01524 #endif
01525 
01526   /* Construct Encoder Context */
01527   vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
01528                      &stream->config.cfg, flags);
01529   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
01530 
01531   /* Note that we bypass the vpx_codec_control wrapper macro because
01532    * we're being clever to store the control IDs in an array. Real
01533    * applications will want to make use of the enumerations directly
01534    */
01535   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
01536     int ctrl = stream->config.arg_ctrls[i][0];
01537     int value = stream->config.arg_ctrls[i][1];
01538     if (vpx_codec_control_(&stream->encoder, ctrl, value))
01539       fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
01540 
01541     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
01542   }
01543 
01544 #if CONFIG_DECODERS
01545   if (global->test_decode != TEST_DECODE_OFF) {
01546     const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
01547     vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
01548   }
01549 #endif
01550 }
01551 
01552 static void encode_frame(struct stream_state *stream,
01553                          struct VpxEncoderConfig *global, struct vpx_image *img,
01554                          unsigned int frames_in) {
01555   vpx_codec_pts_t frame_start, next_frame_start;
01556   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
01557   struct vpx_usec_timer timer;
01558 
01559   frame_start =
01560       (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
01561       cfg->g_timebase.num / global->framerate.num;
01562   next_frame_start =
01563       (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
01564       cfg->g_timebase.num / global->framerate.num;
01565 
01566 /* Scale if necessary */
01567 #if CONFIG_VP9_HIGHBITDEPTH
01568   if (img) {
01569     if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
01570         (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
01571       if (img->fmt != VPX_IMG_FMT_I42016) {
01572         fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
01573         exit(EXIT_FAILURE);
01574       }
01575 #if CONFIG_LIBYUV
01576       if (!stream->img) {
01577         stream->img =
01578             vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
01579       }
01580       I420Scale_16(
01581           (uint16 *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
01582           (uint16 *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
01583           (uint16 *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
01584           img->d_w, img->d_h, (uint16 *)stream->img->planes[VPX_PLANE_Y],
01585           stream->img->stride[VPX_PLANE_Y] / 2,
01586           (uint16 *)stream->img->planes[VPX_PLANE_U],
01587           stream->img->stride[VPX_PLANE_U] / 2,
01588           (uint16 *)stream->img->planes[VPX_PLANE_V],
01589           stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
01590           stream->img->d_h, kFilterBox);
01591       img = stream->img;
01592 #else
01593       stream->encoder.err = 1;
01594       ctx_exit_on_error(&stream->encoder,
01595                         "Stream %d: Failed to encode frame.\n"
01596                         "Scaling disabled in this configuration. \n"
01597                         "To enable, configure with --enable-libyuv\n",
01598                         stream->index);
01599 #endif
01600     }
01601   }
01602 #endif
01603   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
01604     if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
01605       fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
01606       exit(EXIT_FAILURE);
01607     }
01608 #if CONFIG_LIBYUV
01609     if (!stream->img)
01610       stream->img =
01611           vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
01612     I420Scale(
01613         img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
01614         img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
01615         img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
01616         stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
01617         stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
01618         stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
01619         stream->img->d_w, stream->img->d_h, kFilterBox);
01620     img = stream->img;
01621 #else
01622     stream->encoder.err = 1;
01623     ctx_exit_on_error(&stream->encoder,
01624                       "Stream %d: Failed to encode frame.\n"
01625                       "Scaling disabled in this configuration. \n"
01626                       "To enable, configure with --enable-libyuv\n",
01627                       stream->index);
01628 #endif
01629   }
01630 
01631   vpx_usec_timer_start(&timer);
01632   vpx_codec_encode(&stream->encoder, img, frame_start,
01633                    (unsigned long)(next_frame_start - frame_start), 0,
01634                    global->deadline);
01635   vpx_usec_timer_mark(&timer);
01636   stream->cx_time += vpx_usec_timer_elapsed(&timer);
01637   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
01638                     stream->index);
01639 }
01640 
01641 static void update_quantizer_histogram(struct stream_state *stream) {
01642   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
01643     int q;
01644 
01645     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
01646     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
01647     stream->counts[q]++;
01648   }
01649 }
01650 
01651 static void get_cx_data(struct stream_state *stream,
01652                         struct VpxEncoderConfig *global, int *got_data) {
01653   const vpx_codec_cx_pkt_t *pkt;
01654   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
01655   vpx_codec_iter_t iter = NULL;
01656 
01657   *got_data = 0;
01658   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
01659     static size_t fsize = 0;
01660     static int64_t ivf_header_pos = 0;
01661 
01662     switch (pkt->kind) {
01663       case VPX_CODEC_CX_FRAME_PKT:
01664         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
01665           stream->frames_out++;
01666         }
01667         if (!global->quiet)
01668           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
01669 
01670         update_rate_histogram(stream->rate_hist, cfg, pkt);
01671 #if CONFIG_WEBM_IO
01672         if (stream->config.write_webm) {
01673           write_webm_block(&stream->webm_ctx, cfg, pkt);
01674         }
01675 #endif
01676         if (!stream->config.write_webm) {
01677           if (pkt->data.frame.partition_id <= 0) {
01678             ivf_header_pos = ftello(stream->file);
01679             fsize = pkt->data.frame.sz;
01680 
01681             ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
01682           } else {
01683             fsize += pkt->data.frame.sz;
01684 
01685             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
01686               const int64_t currpos = ftello(stream->file);
01687               fseeko(stream->file, ivf_header_pos, SEEK_SET);
01688               ivf_write_frame_size(stream->file, fsize);
01689               fseeko(stream->file, currpos, SEEK_SET);
01690             }
01691           }
01692 
01693           (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
01694                        stream->file);
01695         }
01696         stream->nbytes += pkt->data.raw.sz;
01697 
01698         *got_data = 1;
01699 #if CONFIG_DECODERS
01700         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
01701           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
01702                            (unsigned int)pkt->data.frame.sz, NULL, 0);
01703           if (stream->decoder.err) {
01704             warn_or_exit_on_error(&stream->decoder,
01705                                   global->test_decode == TEST_DECODE_FATAL,
01706                                   "Failed to decode frame %d in stream %d",
01707                                   stream->frames_out + 1, stream->index);
01708             stream->mismatch_seen = stream->frames_out + 1;
01709           }
01710         }
01711 #endif
01712         break;
01713       case VPX_CODEC_STATS_PKT:
01714         stream->frames_out++;
01715         stats_write(&stream->stats, pkt->data.twopass_stats.buf,
01716                     pkt->data.twopass_stats.sz);
01717         stream->nbytes += pkt->data.raw.sz;
01718         break;
01719 #if CONFIG_FP_MB_STATS
01720       case VPX_CODEC_FPMB_STATS_PKT:
01721         stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
01722                     pkt->data.firstpass_mb_stats.sz);
01723         stream->nbytes += pkt->data.raw.sz;
01724         break;
01725 #endif
01726       case VPX_CODEC_PSNR_PKT:
01727 
01728         if (global->show_psnr) {
01729           int i;
01730 
01731           stream->psnr_sse_total += pkt->data.psnr.sse[0];
01732           stream->psnr_samples_total += pkt->data.psnr.samples[0];
01733           for (i = 0; i < 4; i++) {
01734             if (!global->quiet)
01735               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
01736             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
01737           }
01738           stream->psnr_count++;
01739         }
01740 
01741         break;
01742       default: break;
01743     }
01744   }
01745 }
01746 
01747 static void show_psnr(struct stream_state *stream, double peak) {
01748   int i;
01749   double ovpsnr;
01750 
01751   if (!stream->psnr_count) return;
01752 
01753   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
01754   ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
01755                        (double)stream->psnr_sse_total);
01756   fprintf(stderr, " %.3f", ovpsnr);
01757 
01758   for (i = 0; i < 4; i++) {
01759     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
01760   }
01761   fprintf(stderr, "\n");
01762 }
01763 
01764 static float usec_to_fps(uint64_t usec, unsigned int frames) {
01765   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
01766 }
01767 
01768 static void test_decode(struct stream_state *stream,
01769                         enum TestDecodeFatality fatal,
01770                         const VpxInterface *codec) {
01771   vpx_image_t enc_img, dec_img;
01772 
01773   if (stream->mismatch_seen) return;
01774 
01775   /* Get the internal reference frame */
01776   if (strcmp(codec->name, "vp8") == 0) {
01777     struct vpx_ref_frame ref_enc, ref_dec;
01778     int width, height;
01779 
01780     width = (stream->config.cfg.g_w + 15) & ~15;
01781     height = (stream->config.cfg.g_h + 15) & ~15;
01782     vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
01783     enc_img = ref_enc.img;
01784     vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
01785     dec_img = ref_dec.img;
01786 
01787     ref_enc.frame_type = VP8_LAST_FRAME;
01788     ref_dec.frame_type = VP8_LAST_FRAME;
01789     vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
01790     vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
01791   } else {
01792     struct vp9_ref_frame ref_enc, ref_dec;
01793 
01794     ref_enc.idx = 0;
01795     ref_dec.idx = 0;
01796     vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
01797     enc_img = ref_enc.img;
01798     vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
01799     dec_img = ref_dec.img;
01800 #if CONFIG_VP9_HIGHBITDEPTH
01801     if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
01802         (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
01803       if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
01804         vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
01805                       enc_img.d_w, enc_img.d_h, 16);
01806         vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
01807       }
01808       if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
01809         vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
01810                       dec_img.d_w, dec_img.d_h, 16);
01811         vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
01812       }
01813     }
01814 #endif
01815   }
01816   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
01817   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
01818 
01819   if (!compare_img(&enc_img, &dec_img)) {
01820     int y[4], u[4], v[4];
01821 #if CONFIG_VP9_HIGHBITDEPTH
01822     if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
01823       find_mismatch_high(&enc_img, &dec_img, y, u, v);
01824     } else {
01825       find_mismatch(&enc_img, &dec_img, y, u, v);
01826     }
01827 #else
01828     find_mismatch(&enc_img, &dec_img, y, u, v);
01829 #endif
01830     stream->decoder.err = 1;
01831     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
01832                           "Stream %d: Encode/decode mismatch on frame %d at"
01833                           " Y[%d, %d] {%d/%d},"
01834                           " U[%d, %d] {%d/%d},"
01835                           " V[%d, %d] {%d/%d}",
01836                           stream->index, stream->frames_out, y[0], y[1], y[2],
01837                           y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
01838     stream->mismatch_seen = stream->frames_out;
01839   }
01840 
01841   vpx_img_free(&enc_img);
01842   vpx_img_free(&dec_img);
01843 }
01844 
01845 static void print_time(const char *label, int64_t etl) {
01846   int64_t hours;
01847   int64_t mins;
01848   int64_t secs;
01849 
01850   if (etl >= 0) {
01851     hours = etl / 3600;
01852     etl -= hours * 3600;
01853     mins = etl / 60;
01854     etl -= mins * 60;
01855     secs = etl;
01856 
01857     fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
01858             hours, mins, secs);
01859   } else {
01860     fprintf(stderr, "[%3s  unknown] ", label);
01861   }
01862 }
01863 
01864 int main(int argc, const char **argv_) {
01865   int pass;
01866   vpx_image_t raw;
01867 #if CONFIG_VP9_HIGHBITDEPTH
01868   vpx_image_t raw_shift;
01869   int allocated_raw_shift = 0;
01870   int use_16bit_internal = 0;
01871   int input_shift = 0;
01872 #endif
01873   int frame_avail, got_data;
01874 
01875   struct VpxInputContext input;
01876   struct VpxEncoderConfig global;
01877   struct stream_state *streams = NULL;
01878   char **argv, **argi;
01879   uint64_t cx_time = 0;
01880   int stream_cnt = 0;
01881   int res = 0;
01882 
01883   memset(&input, 0, sizeof(input));
01884   exec_name = argv_[0];
01885 
01886   if (argc < 3) usage_exit();
01887 
01888   /* Setup default input stream settings */
01889   input.framerate.numerator = 30;
01890   input.framerate.denominator = 1;
01891   input.only_i420 = 1;
01892   input.bit_depth = 0;
01893 
01894   /* First parse the global configuration values, because we want to apply
01895    * other parameters on top of the default configuration provided by the
01896    * codec.
01897    */
01898   argv = argv_dup(argc - 1, argv_ + 1);
01899   parse_global_config(&global, argv);
01900 
01901   switch (global.color_type) {
01902     case I420: input.fmt = VPX_IMG_FMT_I420; break;
01903     case I422: input.fmt = VPX_IMG_FMT_I422; break;
01904     case I444: input.fmt = VPX_IMG_FMT_I444; break;
01905     case I440: input.fmt = VPX_IMG_FMT_I440; break;
01906     case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
01907   }
01908 
01909   {
01910     /* Now parse each stream's parameters. Using a local scope here
01911      * due to the use of 'stream' as loop variable in FOREACH_STREAM
01912      * loops
01913      */
01914     struct stream_state *stream = NULL;
01915 
01916     do {
01917       stream = new_stream(&global, stream);
01918       stream_cnt++;
01919       if (!streams) streams = stream;
01920     } while (parse_stream_params(&global, stream, argv));
01921   }
01922 
01923   /* Check for unrecognized options */
01924   for (argi = argv; *argi; argi++)
01925     if (argi[0][0] == '-' && argi[0][1])
01926       die("Error: Unrecognized option %s\n", *argi);
01927 
01928   FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
01929                                       &stream->config.cfg););
01930 
01931   /* Handle non-option arguments */
01932   input.filename = argv[0];
01933 
01934   if (!input.filename) usage_exit();
01935 
01936   /* Decide if other chroma subsamplings than 4:2:0 are supported */
01937   if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
01938 
01939   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
01940     int frames_in = 0, seen_frames = 0;
01941     int64_t estimated_time_left = -1;
01942     int64_t average_rate = -1;
01943     int64_t lagged_count = 0;
01944 
01945     open_input_file(&input);
01946 
01947     /* If the input file doesn't specify its w/h (raw files), try to get
01948      * the data from the first stream's configuration.
01949      */
01950     if (!input.width || !input.height) {
01951       FOREACH_STREAM({
01952         if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
01953           input.width = stream->config.cfg.g_w;
01954           input.height = stream->config.cfg.g_h;
01955           break;
01956         }
01957       });
01958     }
01959 
01960     /* Update stream configurations from the input file's parameters */
01961     if (!input.width || !input.height)
01962       fatal(
01963           "Specify stream dimensions with --width (-w) "
01964           " and --height (-h)");
01965 
01966     /* If input file does not specify bit-depth but input-bit-depth parameter
01967      * exists, assume that to be the input bit-depth. However, if the
01968      * input-bit-depth paramter does not exist, assume the input bit-depth
01969      * to be the same as the codec bit-depth.
01970      */
01971     if (!input.bit_depth) {
01972       FOREACH_STREAM({
01973         if (stream->config.cfg.g_input_bit_depth)
01974           input.bit_depth = stream->config.cfg.g_input_bit_depth;
01975         else
01976           input.bit_depth = stream->config.cfg.g_input_bit_depth =
01977               (int)stream->config.cfg.g_bit_depth;
01978       });
01979       if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
01980     } else {
01981       FOREACH_STREAM(
01982           { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
01983     }
01984 
01985     FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
01986     FOREACH_STREAM(validate_stream_config(stream, &global));
01987 
01988     /* Ensure that --passes and --pass are consistent. If --pass is set and
01989      * --passes=2, ensure --fpf was set.
01990      */
01991     if (global.pass && global.passes == 2)
01992       FOREACH_STREAM({
01993         if (!stream->config.stats_fn)
01994           die("Stream %d: Must specify --fpf when --pass=%d"
01995               " and --passes=2\n",
01996               stream->index, global.pass);
01997       });
01998 
01999 #if !CONFIG_WEBM_IO
02000     FOREACH_STREAM({
02001       if (stream->config.write_webm) {
02002         stream->config.write_webm = 0;
02003         warn(
02004             "vpxenc was compiled without WebM container support."
02005             "Producing IVF output");
02006       }
02007     });
02008 #endif
02009 
02010     /* Use the frame rate from the file only if none was specified
02011      * on the command-line.
02012      */
02013     if (!global.have_framerate) {
02014       global.framerate.num = input.framerate.numerator;
02015       global.framerate.den = input.framerate.denominator;
02016       FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
02017                      stream->config.cfg.g_timebase.num = global.framerate.den);
02018     }
02019 
02020     /* Show configuration */
02021     if (global.verbose && pass == 0)
02022       FOREACH_STREAM(show_stream_config(stream, &global, &input));
02023 
02024     if (pass == (global.pass ? global.pass - 1 : 0)) {
02025       if (input.file_type == FILE_TYPE_Y4M)
02026         /*The Y4M reader does its own allocation.
02027           Just initialize this here to avoid problems if we never read any
02028            frames.*/
02029         memset(&raw, 0, sizeof(raw));
02030       else
02031         vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
02032 
02033       FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
02034                          &stream->config.cfg, &global.framerate));
02035     }
02036 
02037     FOREACH_STREAM(setup_pass(stream, &global, pass));
02038     FOREACH_STREAM(
02039         open_output_file(stream, &global, &input.pixel_aspect_ratio));
02040     FOREACH_STREAM(initialize_encoder(stream, &global));
02041 
02042 #if CONFIG_VP9_HIGHBITDEPTH
02043     if (strcmp(global.codec->name, "vp9") == 0) {
02044       // Check to see if at least one stream uses 16 bit internal.
02045       // Currently assume that the bit_depths for all streams using
02046       // highbitdepth are the same.
02047       FOREACH_STREAM({
02048         if (stream->config.use_16bit_internal) {
02049           use_16bit_internal = 1;
02050         }
02051         if (stream->config.cfg.g_profile == 0) {
02052           input_shift = 0;
02053         } else {
02054           input_shift = (int)stream->config.cfg.g_bit_depth -
02055                         stream->config.cfg.g_input_bit_depth;
02056         }
02057       });
02058     }
02059 #endif
02060 
02061     frame_avail = 1;
02062     got_data = 0;
02063 
02064     while (frame_avail || got_data) {
02065       struct vpx_usec_timer timer;
02066 
02067       if (!global.limit || frames_in < global.limit) {
02068         frame_avail = read_frame(&input, &raw);
02069 
02070         if (frame_avail) frames_in++;
02071         seen_frames =
02072             frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
02073 
02074         if (!global.quiet) {
02075           float fps = usec_to_fps(cx_time, seen_frames);
02076           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
02077 
02078           if (stream_cnt == 1)
02079             fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
02080                     streams->frames_out, (int64_t)streams->nbytes);
02081           else
02082             fprintf(stderr, "frame %4d ", frames_in);
02083 
02084           fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
02085                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
02086                   cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
02087                   fps >= 1.0 ? "fps" : "fpm");
02088           print_time("ETA", estimated_time_left);
02089         }
02090 
02091       } else
02092         frame_avail = 0;
02093 
02094       if (frames_in > global.skip_frames) {
02095 #if CONFIG_VP9_HIGHBITDEPTH
02096         vpx_image_t *frame_to_encode;
02097         if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
02098           assert(use_16bit_internal);
02099           // Input bit depth and stream bit depth do not match, so up
02100           // shift frame to stream bit depth
02101           if (!allocated_raw_shift) {
02102             vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
02103                           input.width, input.height, 32);
02104             allocated_raw_shift = 1;
02105           }
02106           vpx_img_upshift(&raw_shift, &raw, input_shift);
02107           frame_to_encode = &raw_shift;
02108         } else {
02109           frame_to_encode = &raw;
02110         }
02111         vpx_usec_timer_start(&timer);
02112         if (use_16bit_internal) {
02113           assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
02114           FOREACH_STREAM({
02115             if (stream->config.use_16bit_internal)
02116               encode_frame(stream, &global,
02117                            frame_avail ? frame_to_encode : NULL, frames_in);
02118             else
02119               assert(0);
02120           });
02121         } else {
02122           assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
02123           FOREACH_STREAM(encode_frame(stream, &global,
02124                                       frame_avail ? frame_to_encode : NULL,
02125                                       frames_in));
02126         }
02127 #else
02128         vpx_usec_timer_start(&timer);
02129         FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
02130                                     frames_in));
02131 #endif
02132         vpx_usec_timer_mark(&timer);
02133         cx_time += vpx_usec_timer_elapsed(&timer);
02134 
02135         FOREACH_STREAM(update_quantizer_histogram(stream));
02136 
02137         got_data = 0;
02138         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
02139 
02140         if (!got_data && input.length && streams != NULL &&
02141             !streams->frames_out) {
02142           lagged_count = global.limit ? seen_frames : ftello(input.file);
02143         } else if (input.length) {
02144           int64_t remaining;
02145           int64_t rate;
02146 
02147           if (global.limit) {
02148             const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
02149 
02150             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
02151             remaining = 1000 * (global.limit - global.skip_frames -
02152                                 seen_frames + lagged_count);
02153           } else {
02154             const int64_t input_pos = ftello(input.file);
02155             const int64_t input_pos_lagged = input_pos - lagged_count;
02156             const int64_t limit = input.length;
02157 
02158             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
02159             remaining = limit - input_pos + lagged_count;
02160           }
02161 
02162           average_rate =
02163               (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
02164           estimated_time_left = average_rate ? remaining / average_rate : -1;
02165         }
02166 
02167         if (got_data && global.test_decode != TEST_DECODE_OFF)
02168           FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
02169       }
02170 
02171       fflush(stdout);
02172       if (!global.quiet) fprintf(stderr, "\033[K");
02173     }
02174 
02175     if (stream_cnt > 1) fprintf(stderr, "\n");
02176 
02177     if (!global.quiet) {
02178       FOREACH_STREAM(fprintf(
02179           stderr, "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64
02180                   "b/f %7" PRId64 "b/s"
02181                   " %7" PRId64 " %s (%.2f fps)\033[K\n",
02182           pass + 1, global.passes, frames_in, stream->frames_out,
02183           (int64_t)stream->nbytes,
02184           seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
02185           seen_frames
02186               ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
02187                     global.framerate.den / seen_frames
02188               : 0,
02189           stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
02190           stream->cx_time > 9999999 ? "ms" : "us",
02191           usec_to_fps(stream->cx_time, seen_frames)));
02192     }
02193 
02194     if (global.show_psnr) {
02195       if (global.codec->fourcc == VP9_FOURCC) {
02196         FOREACH_STREAM(
02197             show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
02198       } else {
02199         FOREACH_STREAM(show_psnr(stream, 255.0));
02200       }
02201     }
02202 
02203     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
02204 
02205     if (global.test_decode != TEST_DECODE_OFF) {
02206       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
02207     }
02208 
02209     close_input_file(&input);
02210 
02211     if (global.test_decode == TEST_DECODE_FATAL) {
02212       FOREACH_STREAM(res |= stream->mismatch_seen);
02213     }
02214     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
02215 
02216     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
02217 
02218 #if CONFIG_FP_MB_STATS
02219     FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
02220 #endif
02221 
02222     if (global.pass) break;
02223   }
02224 
02225   if (global.show_q_hist_buckets)
02226     FOREACH_STREAM(
02227         show_q_histogram(stream->counts, global.show_q_hist_buckets));
02228 
02229   if (global.show_rate_hist_buckets)
02230     FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
02231                                        global.show_rate_hist_buckets));
02232   FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
02233 
02234 #if CONFIG_INTERNAL_STATS
02235   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
02236    * to match some existing utilities.
02237    */
02238   if (!(global.pass == 1 && global.passes == 2))
02239     FOREACH_STREAM({
02240       FILE *f = fopen("opsnr.stt", "a");
02241       if (stream->mismatch_seen) {
02242         fprintf(f, "First mismatch occurred in frame %d\n",
02243                 stream->mismatch_seen);
02244       } else {
02245         fprintf(f, "No mismatch detected in recon buffers\n");
02246       }
02247       fclose(f);
02248     });
02249 #endif
02250 
02251 #if CONFIG_VP9_HIGHBITDEPTH
02252   if (allocated_raw_shift) vpx_img_free(&raw_shift);
02253 #endif
02254   vpx_img_free(&raw);
02255   free(argv);
02256   free(streams);
02257   return res ? EXIT_FAILURE : EXIT_SUCCESS;
02258 }

Generated on 16 Jun 2017 for WebM Codec SDK by  doxygen 1.6.1