]> granicus.if.org Git - libvpx/blob - vpxenc.c
Merge changes I6ab0ece8,I5f878e9b
[libvpx] / vpxenc.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include "./vpxenc.h"
12 #include "./vpx_config.h"
13
14 #include <assert.h>
15 #include <limits.h>
16 #include <math.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #if CONFIG_LIBYUV
23 #include "third_party/libyuv/include/libyuv/scale.h"
24 #endif
25
26 #include "vpx/vpx_encoder.h"
27 #if CONFIG_DECODERS
28 #include "vpx/vpx_decoder.h"
29 #endif
30
31 #include "./args.h"
32 #include "./ivfenc.h"
33 #include "./tools_common.h"
34
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
37 #endif
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
40 #endif
41
42 #include "vpx/vpx_integer.h"
43 #include "vpx_ports/mem_ops.h"
44 #include "vpx_ports/vpx_timer.h"
45 #include "./rate_hist.h"
46 #include "./vpxstats.h"
47 #include "./warnings.h"
48 #if CONFIG_WEBM_IO
49 #include "./webmenc.h"
50 #endif
51 #include "./y4minput.h"
52
53 /* Swallow warnings about unused results of fread/fwrite */
54 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
55   return fread(ptr, size, nmemb, stream);
56 }
57 #define fread wrap_fread
58
59 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
60                           FILE *stream) {
61   return fwrite(ptr, size, nmemb, stream);
62 }
63 #define fwrite wrap_fwrite
64
65 static const char *exec_name;
66
67 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
68                                    const char *s, va_list ap) {
69   if (ctx->err) {
70     const char *detail = vpx_codec_error_detail(ctx);
71
72     vfprintf(stderr, s, ap);
73     fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
74
75     if (detail) fprintf(stderr, "    %s\n", detail);
76
77     if (fatal) exit(EXIT_FAILURE);
78   }
79 }
80
81 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
82   va_list ap;
83
84   va_start(ap, s);
85   warn_or_exit_on_errorv(ctx, 1, s, ap);
86   va_end(ap);
87 }
88
89 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
90                                   const char *s, ...) {
91   va_list ap;
92
93   va_start(ap, s);
94   warn_or_exit_on_errorv(ctx, fatal, s, ap);
95   va_end(ap);
96 }
97
98 static int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
99   FILE *f = input_ctx->file;
100   y4m_input *y4m = &input_ctx->y4m;
101   int shortread = 0;
102
103   if (input_ctx->file_type == FILE_TYPE_Y4M) {
104     if (y4m_input_fetch_frame(y4m, f, img) < 1) return 0;
105   } else {
106     shortread = read_yuv_frame(input_ctx, img);
107   }
108
109   return !shortread;
110 }
111
112 static int file_is_y4m(const char detect[4]) {
113   if (memcmp(detect, "YUV4", 4) == 0) {
114     return 1;
115   }
116   return 0;
117 }
118
119 static int fourcc_is_ivf(const char detect[4]) {
120   if (memcmp(detect, "DKIF", 4) == 0) {
121     return 1;
122   }
123   return 0;
124 }
125
126 static const arg_def_t help =
127     ARG_DEF(NULL, "help", 0, "Show usage options and exit");
128 static const arg_def_t debugmode =
129     ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
130 static const arg_def_t outputfile =
131     ARG_DEF("o", "output", 1, "Output filename");
132 static const arg_def_t use_yv12 =
133     ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
134 static const arg_def_t use_i420 =
135     ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
136 static const arg_def_t use_i422 =
137     ARG_DEF(NULL, "i422", 0, "Input file is I422");
138 static const arg_def_t use_i444 =
139     ARG_DEF(NULL, "i444", 0, "Input file is I444");
140 static const arg_def_t use_i440 =
141     ARG_DEF(NULL, "i440", 0, "Input file is I440");
142 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
143 static const arg_def_t passes =
144     ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
145 static const arg_def_t pass_arg =
146     ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
147 static const arg_def_t fpf_name =
148     ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
149 #if CONFIG_FP_MB_STATS
150 static const arg_def_t fpmbf_name =
151     ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
152 #endif
153 static const arg_def_t limit =
154     ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
155 static const arg_def_t skip =
156     ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
157 static const arg_def_t deadline =
158     ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
159 static const arg_def_t best_dl =
160     ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
161 static const arg_def_t good_dl =
162     ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
163 static const arg_def_t rt_dl =
164     ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
165 static const arg_def_t quietarg =
166     ARG_DEF("q", "quiet", 0, "Do not print encode progress");
167 static const arg_def_t verbosearg =
168     ARG_DEF("v", "verbose", 0, "Show encoder parameters");
169 static const arg_def_t psnrarg =
170     ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
171
172 static const struct arg_enum_list test_decode_enum[] = {
173   { "off", TEST_DECODE_OFF },
174   { "fatal", TEST_DECODE_FATAL },
175   { "warn", TEST_DECODE_WARN },
176   { NULL, 0 }
177 };
178 static const arg_def_t recontest = ARG_DEF_ENUM(
179     NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
180 static const arg_def_t framerate =
181     ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
182 static const arg_def_t use_webm =
183     ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
184 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
185 static const arg_def_t out_part =
186     ARG_DEF("P", "output-partitions", 0,
187             "Makes encoder output partitions. Requires IVF output!");
188 static const arg_def_t q_hist_n =
189     ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
190 static const arg_def_t rate_hist_n =
191     ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
192 static const arg_def_t disable_warnings =
193     ARG_DEF(NULL, "disable-warnings", 0,
194             "Disable warnings about potentially incorrect encode settings.");
195 static const arg_def_t disable_warning_prompt =
196     ARG_DEF("y", "disable-warning-prompt", 0,
197             "Display warnings, but do not prompt user to continue.");
198
199 #if CONFIG_VP9_HIGHBITDEPTH
200 static const arg_def_t test16bitinternalarg = ARG_DEF(
201     NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
202 #endif
203
204 static const arg_def_t *main_args[] = { &help,
205                                         &debugmode,
206                                         &outputfile,
207                                         &codecarg,
208                                         &passes,
209                                         &pass_arg,
210                                         &fpf_name,
211                                         &limit,
212                                         &skip,
213                                         &deadline,
214                                         &best_dl,
215                                         &good_dl,
216                                         &rt_dl,
217                                         &quietarg,
218                                         &verbosearg,
219                                         &psnrarg,
220                                         &use_webm,
221                                         &use_ivf,
222                                         &out_part,
223                                         &q_hist_n,
224                                         &rate_hist_n,
225                                         &disable_warnings,
226                                         &disable_warning_prompt,
227                                         &recontest,
228                                         NULL };
229
230 static const arg_def_t usage =
231     ARG_DEF("u", "usage", 1, "Usage profile number to use");
232 static const arg_def_t threads =
233     ARG_DEF("t", "threads", 1, "Max number of threads to use");
234 static const arg_def_t profile =
235     ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
236 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
237 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
238 #if CONFIG_WEBM_IO
239 static const struct arg_enum_list stereo_mode_enum[] = {
240   { "mono", STEREO_FORMAT_MONO },
241   { "left-right", STEREO_FORMAT_LEFT_RIGHT },
242   { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
243   { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
244   { "right-left", STEREO_FORMAT_RIGHT_LEFT },
245   { NULL, 0 }
246 };
247 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
248     NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
249 #endif
250 static const arg_def_t timebase = ARG_DEF(
251     NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
252 static const arg_def_t error_resilient =
253     ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
254 static const arg_def_t lag_in_frames =
255     ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
256
257 static const arg_def_t *global_args[] = { &use_yv12,
258                                           &use_i420,
259                                           &use_i422,
260                                           &use_i444,
261                                           &use_i440,
262                                           &usage,
263                                           &threads,
264                                           &profile,
265                                           &width,
266                                           &height,
267 #if CONFIG_WEBM_IO
268                                           &stereo_mode,
269 #endif
270                                           &timebase,
271                                           &framerate,
272                                           &error_resilient,
273 #if CONFIG_VP9_HIGHBITDEPTH
274                                           &test16bitinternalarg,
275 #endif
276                                           &lag_in_frames,
277                                           NULL };
278
279 static const arg_def_t dropframe_thresh =
280     ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
281 static const arg_def_t resize_allowed =
282     ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
283 static const arg_def_t resize_width =
284     ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
285 static const arg_def_t resize_height =
286     ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
287 static const arg_def_t resize_up_thresh =
288     ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
289 static const arg_def_t resize_down_thresh =
290     ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
291 static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
292                                                        { "cbr", VPX_CBR },
293                                                        { "cq", VPX_CQ },
294                                                        { "q", VPX_Q },
295                                                        { NULL, 0 } };
296 static const arg_def_t end_usage =
297     ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
298 static const arg_def_t target_bitrate =
299     ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
300 static const arg_def_t min_quantizer =
301     ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
302 static const arg_def_t max_quantizer =
303     ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
304 static const arg_def_t undershoot_pct =
305     ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
306 static const arg_def_t overshoot_pct =
307     ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
308 static const arg_def_t buf_sz =
309     ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
310 static const arg_def_t buf_initial_sz =
311     ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
312 static const arg_def_t buf_optimal_sz =
313     ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
314 static const arg_def_t *rc_args[] = {
315   &dropframe_thresh, &resize_allowed,     &resize_width,   &resize_height,
316   &resize_up_thresh, &resize_down_thresh, &end_usage,      &target_bitrate,
317   &min_quantizer,    &max_quantizer,      &undershoot_pct, &overshoot_pct,
318   &buf_sz,           &buf_initial_sz,     &buf_optimal_sz, NULL
319 };
320
321 static const arg_def_t bias_pct =
322     ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
323 static const arg_def_t minsection_pct =
324     ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
325 static const arg_def_t maxsection_pct =
326     ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
327 static const arg_def_t corpus_complexity =
328     ARG_DEF(NULL, "corpus-complexity", 1, "corpus vbr complexity midpoint");
329 static const arg_def_t *rc_twopass_args[] = {
330   &bias_pct, &minsection_pct, &maxsection_pct, &corpus_complexity, NULL
331 };
332
333 static const arg_def_t kf_min_dist =
334     ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
335 static const arg_def_t kf_max_dist =
336     ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
337 static const arg_def_t kf_disabled =
338     ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
339 static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
340                                       NULL };
341
342 static const arg_def_t noise_sens =
343     ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
344 static const arg_def_t sharpness =
345     ARG_DEF(NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
346 static const arg_def_t static_thresh =
347     ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
348 static const arg_def_t auto_altref =
349     ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
350 static const arg_def_t arnr_maxframes =
351     ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
352 static const arg_def_t arnr_strength =
353     ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
354 static const arg_def_t arnr_type =
355     ARG_DEF(NULL, "arnr-type", 1, "AltRef filter type (1..3)");
356 static const struct arg_enum_list tuning_enum[] = {
357   { "psnr", VP8_TUNE_PSNR }, { "ssim", VP8_TUNE_SSIM }, { NULL, 0 }
358 };
359 static const arg_def_t tune_ssim =
360     ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
361 static const arg_def_t cq_level =
362     ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
363 static const arg_def_t max_intra_rate_pct =
364     ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
365 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
366     NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
367
368 #if CONFIG_VP8_ENCODER
369 static const arg_def_t cpu_used_vp8 =
370     ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
371 static const arg_def_t token_parts =
372     ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
373 static const arg_def_t screen_content_mode =
374     ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
375 static const arg_def_t *vp8_args[] = { &cpu_used_vp8,
376                                        &auto_altref,
377                                        &noise_sens,
378                                        &sharpness,
379                                        &static_thresh,
380                                        &token_parts,
381                                        &arnr_maxframes,
382                                        &arnr_strength,
383                                        &arnr_type,
384                                        &tune_ssim,
385                                        &cq_level,
386                                        &max_intra_rate_pct,
387                                        &gf_cbr_boost_pct,
388                                        &screen_content_mode,
389                                        NULL };
390 static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
391                                         VP8E_SET_ENABLEAUTOALTREF,
392                                         VP8E_SET_NOISE_SENSITIVITY,
393                                         VP8E_SET_SHARPNESS,
394                                         VP8E_SET_STATIC_THRESHOLD,
395                                         VP8E_SET_TOKEN_PARTITIONS,
396                                         VP8E_SET_ARNR_MAXFRAMES,
397                                         VP8E_SET_ARNR_STRENGTH,
398                                         VP8E_SET_ARNR_TYPE,
399                                         VP8E_SET_TUNING,
400                                         VP8E_SET_CQ_LEVEL,
401                                         VP8E_SET_MAX_INTRA_BITRATE_PCT,
402                                         VP8E_SET_GF_CBR_BOOST_PCT,
403                                         VP8E_SET_SCREEN_CONTENT_MODE,
404                                         0 };
405 #endif
406
407 #if CONFIG_VP9_ENCODER
408 static const arg_def_t cpu_used_vp9 =
409     ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-8..8)");
410 static const arg_def_t tile_cols =
411     ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
412 static const arg_def_t tile_rows =
413     ARG_DEF(NULL, "tile-rows", 1,
414             "Number of tile rows to use, log2 (set to 0 while threads > 1)");
415
416 static const arg_def_t enable_tpl_model =
417     ARG_DEF(NULL, "enable-tpl", 1, "Enable temporal dependency model");
418
419 static const arg_def_t lossless =
420     ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
421 static const arg_def_t frame_parallel_decoding = ARG_DEF(
422     NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
423 static const arg_def_t aq_mode = ARG_DEF(
424     NULL, "aq-mode", 1,
425     "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
426     "3: cyclic refresh, 4: equator360)");
427 static const arg_def_t alt_ref_aq = ARG_DEF(NULL, "alt-ref-aq", 1,
428                                             "Special adaptive quantization for "
429                                             "the alternate reference frames.");
430 static const arg_def_t frame_periodic_boost =
431     ARG_DEF(NULL, "frame-boost", 1,
432             "Enable frame periodic boost (0: off (default), 1: on)");
433 static const arg_def_t max_inter_rate_pct =
434     ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
435 static const arg_def_t min_gf_interval = ARG_DEF(
436     NULL, "min-gf-interval", 1,
437     "min gf/arf frame interval (default 0, indicating in-built behavior)");
438 static const arg_def_t max_gf_interval = ARG_DEF(
439     NULL, "max-gf-interval", 1,
440     "max gf/arf frame interval (default 0, indicating in-built behavior)");
441
442 static const struct arg_enum_list color_space_enum[] = {
443   { "unknown", VPX_CS_UNKNOWN },
444   { "bt601", VPX_CS_BT_601 },
445   { "bt709", VPX_CS_BT_709 },
446   { "smpte170", VPX_CS_SMPTE_170 },
447   { "smpte240", VPX_CS_SMPTE_240 },
448   { "bt2020", VPX_CS_BT_2020 },
449   { "reserved", VPX_CS_RESERVED },
450   { "sRGB", VPX_CS_SRGB },
451   { NULL, 0 }
452 };
453
454 static const arg_def_t input_color_space =
455     ARG_DEF_ENUM(NULL, "color-space", 1,
456                  "The color space of input content:", color_space_enum);
457
458 #if CONFIG_VP9_HIGHBITDEPTH
459 static const struct arg_enum_list bitdepth_enum[] = {
460   { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
461 };
462
463 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
464     "b", "bit-depth", 1,
465     "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
466     bitdepth_enum);
467 static const arg_def_t inbitdeptharg =
468     ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
469 #endif
470
471 static const struct arg_enum_list tune_content_enum[] = {
472   { "default", VP9E_CONTENT_DEFAULT },
473   { "screen", VP9E_CONTENT_SCREEN },
474   { "film", VP9E_CONTENT_FILM },
475   { NULL, 0 }
476 };
477
478 static const arg_def_t tune_content = ARG_DEF_ENUM(
479     NULL, "tune-content", 1, "Tune content type", tune_content_enum);
480
481 static const arg_def_t target_level = ARG_DEF(
482     NULL, "target-level", 1,
483     "Target level\n"
484     "                                        255: off (default)\n"
485     "                                          0: only keep level stats\n"
486     "                                          1: adaptively set alt-ref "
487     "distance and column tile limit based on picture size, and keep"
488     " level stats\n"
489     "                                         10: level 1.0  11: level 1.1  "
490     "...  62: level 6.2");
491
492 static const arg_def_t row_mt =
493     ARG_DEF(NULL, "row-mt", 1,
494             "Enable row based non-deterministic multi-threading in VP9");
495 #endif
496
497 #if CONFIG_VP9_ENCODER
498 static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
499                                        &auto_altref,
500                                        &sharpness,
501                                        &static_thresh,
502                                        &tile_cols,
503                                        &tile_rows,
504                                        &enable_tpl_model,
505                                        &arnr_maxframes,
506                                        &arnr_strength,
507                                        &arnr_type,
508                                        &tune_ssim,
509                                        &cq_level,
510                                        &max_intra_rate_pct,
511                                        &max_inter_rate_pct,
512                                        &gf_cbr_boost_pct,
513                                        &lossless,
514                                        &frame_parallel_decoding,
515                                        &aq_mode,
516                                        &alt_ref_aq,
517                                        &frame_periodic_boost,
518                                        &noise_sens,
519                                        &tune_content,
520                                        &input_color_space,
521                                        &min_gf_interval,
522                                        &max_gf_interval,
523                                        &target_level,
524                                        &row_mt,
525 #if CONFIG_VP9_HIGHBITDEPTH
526                                        &bitdeptharg,
527                                        &inbitdeptharg,
528 #endif  // CONFIG_VP9_HIGHBITDEPTH
529                                        NULL };
530 static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
531                                         VP8E_SET_ENABLEAUTOALTREF,
532                                         VP8E_SET_SHARPNESS,
533                                         VP8E_SET_STATIC_THRESHOLD,
534                                         VP9E_SET_TILE_COLUMNS,
535                                         VP9E_SET_TILE_ROWS,
536                                         VP9E_SET_TPL,
537                                         VP8E_SET_ARNR_MAXFRAMES,
538                                         VP8E_SET_ARNR_STRENGTH,
539                                         VP8E_SET_ARNR_TYPE,
540                                         VP8E_SET_TUNING,
541                                         VP8E_SET_CQ_LEVEL,
542                                         VP8E_SET_MAX_INTRA_BITRATE_PCT,
543                                         VP9E_SET_MAX_INTER_BITRATE_PCT,
544                                         VP9E_SET_GF_CBR_BOOST_PCT,
545                                         VP9E_SET_LOSSLESS,
546                                         VP9E_SET_FRAME_PARALLEL_DECODING,
547                                         VP9E_SET_AQ_MODE,
548                                         VP9E_SET_ALT_REF_AQ,
549                                         VP9E_SET_FRAME_PERIODIC_BOOST,
550                                         VP9E_SET_NOISE_SENSITIVITY,
551                                         VP9E_SET_TUNE_CONTENT,
552                                         VP9E_SET_COLOR_SPACE,
553                                         VP9E_SET_MIN_GF_INTERVAL,
554                                         VP9E_SET_MAX_GF_INTERVAL,
555                                         VP9E_SET_TARGET_LEVEL,
556                                         VP9E_SET_ROW_MT,
557                                         0 };
558 #endif
559
560 static const arg_def_t *no_args[] = { NULL };
561
562 void show_help(FILE *fout, int shorthelp) {
563   int i;
564   const int num_encoder = get_vpx_encoder_count();
565
566   fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
567           exec_name);
568
569   if (shorthelp) {
570     fprintf(fout, "Use --help to see the full list of options.\n");
571     return;
572   }
573
574   fprintf(fout, "\nOptions:\n");
575   arg_show_usage(fout, main_args);
576   fprintf(fout, "\nEncoder Global Options:\n");
577   arg_show_usage(fout, global_args);
578   fprintf(fout, "\nRate Control Options:\n");
579   arg_show_usage(fout, rc_args);
580   fprintf(fout, "\nTwopass Rate Control Options:\n");
581   arg_show_usage(fout, rc_twopass_args);
582   fprintf(fout, "\nKeyframe Placement Options:\n");
583   arg_show_usage(fout, kf_args);
584 #if CONFIG_VP8_ENCODER
585   fprintf(fout, "\nVP8 Specific Options:\n");
586   arg_show_usage(fout, vp8_args);
587 #endif
588 #if CONFIG_VP9_ENCODER
589   fprintf(fout, "\nVP9 Specific Options:\n");
590   arg_show_usage(fout, vp9_args);
591 #endif
592   fprintf(fout,
593           "\nStream timebase (--timebase):\n"
594           "  The desired precision of timestamps in the output, expressed\n"
595           "  in fractional seconds. Default is 1/1000.\n");
596   fprintf(fout, "\nIncluded encoders:\n\n");
597
598   for (i = 0; i < num_encoder; ++i) {
599     const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
600     const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
601     fprintf(fout, "    %-6s - %s %s\n", encoder->name,
602             vpx_codec_iface_name(encoder->codec_interface()), defstr);
603   }
604   fprintf(fout, "\n        ");
605   fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
606 }
607
608 void usage_exit(void) {
609   show_help(stderr, 1);
610   exit(EXIT_FAILURE);
611 }
612
613 #define mmin(a, b) ((a) < (b) ? (a) : (b))
614
615 #if CONFIG_VP9_HIGHBITDEPTH
616 static void find_mismatch_high(const vpx_image_t *const img1,
617                                const vpx_image_t *const img2, int yloc[4],
618                                int uloc[4], int vloc[4]) {
619   uint16_t *plane1, *plane2;
620   uint32_t stride1, stride2;
621   const uint32_t bsize = 64;
622   const uint32_t bsizey = bsize >> img1->y_chroma_shift;
623   const uint32_t bsizex = bsize >> img1->x_chroma_shift;
624   const uint32_t c_w =
625       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
626   const uint32_t c_h =
627       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
628   int match = 1;
629   uint32_t i, j;
630   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
631   plane1 = (uint16_t *)img1->planes[VPX_PLANE_Y];
632   plane2 = (uint16_t *)img2->planes[VPX_PLANE_Y];
633   stride1 = img1->stride[VPX_PLANE_Y] / 2;
634   stride2 = img2->stride[VPX_PLANE_Y] / 2;
635   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
636     for (j = 0; match && j < img1->d_w; j += bsize) {
637       int k, l;
638       const int si = mmin(i + bsize, img1->d_h) - i;
639       const int sj = mmin(j + bsize, img1->d_w) - j;
640       for (k = 0; match && k < si; ++k) {
641         for (l = 0; match && l < sj; ++l) {
642           if (*(plane1 + (i + k) * stride1 + j + l) !=
643               *(plane2 + (i + k) * stride2 + j + l)) {
644             yloc[0] = i + k;
645             yloc[1] = j + l;
646             yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
647             yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
648             match = 0;
649             break;
650           }
651         }
652       }
653     }
654   }
655
656   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
657   plane1 = (uint16_t *)img1->planes[VPX_PLANE_U];
658   plane2 = (uint16_t *)img2->planes[VPX_PLANE_U];
659   stride1 = img1->stride[VPX_PLANE_U] / 2;
660   stride2 = img2->stride[VPX_PLANE_U] / 2;
661   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
662     for (j = 0; match && j < c_w; j += bsizex) {
663       int k, l;
664       const int si = mmin(i + bsizey, c_h - i);
665       const int sj = mmin(j + bsizex, c_w - j);
666       for (k = 0; match && k < si; ++k) {
667         for (l = 0; match && l < sj; ++l) {
668           if (*(plane1 + (i + k) * stride1 + j + l) !=
669               *(plane2 + (i + k) * stride2 + j + l)) {
670             uloc[0] = i + k;
671             uloc[1] = j + l;
672             uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
673             uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
674             match = 0;
675             break;
676           }
677         }
678       }
679     }
680   }
681
682   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
683   plane1 = (uint16_t *)img1->planes[VPX_PLANE_V];
684   plane2 = (uint16_t *)img2->planes[VPX_PLANE_V];
685   stride1 = img1->stride[VPX_PLANE_V] / 2;
686   stride2 = img2->stride[VPX_PLANE_V] / 2;
687   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
688     for (j = 0; match && j < c_w; j += bsizex) {
689       int k, l;
690       const int si = mmin(i + bsizey, c_h - i);
691       const int sj = mmin(j + bsizex, c_w - j);
692       for (k = 0; match && k < si; ++k) {
693         for (l = 0; match && l < sj; ++l) {
694           if (*(plane1 + (i + k) * stride1 + j + l) !=
695               *(plane2 + (i + k) * stride2 + j + l)) {
696             vloc[0] = i + k;
697             vloc[1] = j + l;
698             vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
699             vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
700             match = 0;
701             break;
702           }
703         }
704       }
705     }
706   }
707 }
708 #endif
709
710 static void find_mismatch(const vpx_image_t *const img1,
711                           const vpx_image_t *const img2, int yloc[4],
712                           int uloc[4], int vloc[4]) {
713   const uint32_t bsize = 64;
714   const uint32_t bsizey = bsize >> img1->y_chroma_shift;
715   const uint32_t bsizex = bsize >> img1->x_chroma_shift;
716   const uint32_t c_w =
717       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
718   const uint32_t c_h =
719       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
720   int match = 1;
721   uint32_t i, j;
722   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
723   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
724     for (j = 0; match && j < img1->d_w; j += bsize) {
725       int k, l;
726       const int si = mmin(i + bsize, img1->d_h) - i;
727       const int sj = mmin(j + bsize, img1->d_w) - j;
728       for (k = 0; match && k < si; ++k) {
729         for (l = 0; match && l < sj; ++l) {
730           if (*(img1->planes[VPX_PLANE_Y] +
731                 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
732               *(img2->planes[VPX_PLANE_Y] +
733                 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
734             yloc[0] = i + k;
735             yloc[1] = j + l;
736             yloc[2] = *(img1->planes[VPX_PLANE_Y] +
737                         (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
738             yloc[3] = *(img2->planes[VPX_PLANE_Y] +
739                         (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
740             match = 0;
741             break;
742           }
743         }
744       }
745     }
746   }
747
748   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
749   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
750     for (j = 0; match && j < c_w; j += bsizex) {
751       int k, l;
752       const int si = mmin(i + bsizey, c_h - i);
753       const int sj = mmin(j + bsizex, c_w - j);
754       for (k = 0; match && k < si; ++k) {
755         for (l = 0; match && l < sj; ++l) {
756           if (*(img1->planes[VPX_PLANE_U] +
757                 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
758               *(img2->planes[VPX_PLANE_U] +
759                 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
760             uloc[0] = i + k;
761             uloc[1] = j + l;
762             uloc[2] = *(img1->planes[VPX_PLANE_U] +
763                         (i + k) * img1->stride[VPX_PLANE_U] + j + l);
764             uloc[3] = *(img2->planes[VPX_PLANE_U] +
765                         (i + k) * img2->stride[VPX_PLANE_U] + j + l);
766             match = 0;
767             break;
768           }
769         }
770       }
771     }
772   }
773   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
774   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
775     for (j = 0; match && j < c_w; j += bsizex) {
776       int k, l;
777       const int si = mmin(i + bsizey, c_h - i);
778       const int sj = mmin(j + bsizex, c_w - j);
779       for (k = 0; match && k < si; ++k) {
780         for (l = 0; match && l < sj; ++l) {
781           if (*(img1->planes[VPX_PLANE_V] +
782                 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
783               *(img2->planes[VPX_PLANE_V] +
784                 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
785             vloc[0] = i + k;
786             vloc[1] = j + l;
787             vloc[2] = *(img1->planes[VPX_PLANE_V] +
788                         (i + k) * img1->stride[VPX_PLANE_V] + j + l);
789             vloc[3] = *(img2->planes[VPX_PLANE_V] +
790                         (i + k) * img2->stride[VPX_PLANE_V] + j + l);
791             match = 0;
792             break;
793           }
794         }
795       }
796     }
797   }
798 }
799
800 static int compare_img(const vpx_image_t *const img1,
801                        const vpx_image_t *const img2) {
802   uint32_t l_w = img1->d_w;
803   uint32_t c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
804   const uint32_t c_h =
805       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
806   uint32_t i;
807   int match = 1;
808
809   match &= (img1->fmt == img2->fmt);
810   match &= (img1->d_w == img2->d_w);
811   match &= (img1->d_h == img2->d_h);
812 #if CONFIG_VP9_HIGHBITDEPTH
813   if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
814     l_w *= 2;
815     c_w *= 2;
816   }
817 #endif
818
819   for (i = 0; i < img1->d_h; ++i)
820     match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
821                      img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
822                      l_w) == 0);
823
824   for (i = 0; i < c_h; ++i)
825     match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
826                      img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
827                      c_w) == 0);
828
829   for (i = 0; i < c_h; ++i)
830     match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
831                      img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
832                      c_w) == 0);
833
834   return match;
835 }
836
837 #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
838 #if CONFIG_VP9_ENCODER
839 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
840 #else
841 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
842 #endif
843
844 #if !CONFIG_WEBM_IO
845 typedef int stereo_format_t;
846 struct WebmOutputContext {
847   int debug;
848 };
849 #endif
850
851 /* Per-stream configuration */
852 struct stream_config {
853   struct vpx_codec_enc_cfg cfg;
854   const char *out_fn;
855   const char *stats_fn;
856 #if CONFIG_FP_MB_STATS
857   const char *fpmb_stats_fn;
858 #endif
859   stereo_format_t stereo_fmt;
860   int arg_ctrls[ARG_CTRL_CNT_MAX][2];
861   int arg_ctrl_cnt;
862   int write_webm;
863 #if CONFIG_VP9_HIGHBITDEPTH
864   // whether to use 16bit internal buffers
865   int use_16bit_internal;
866 #endif
867 };
868
869 struct stream_state {
870   int index;
871   struct stream_state *next;
872   struct stream_config config;
873   FILE *file;
874   struct rate_hist *rate_hist;
875   struct WebmOutputContext webm_ctx;
876   uint64_t psnr_sse_total;
877   uint64_t psnr_samples_total;
878   double psnr_totals[4];
879   int psnr_count;
880   int counts[64];
881   vpx_codec_ctx_t encoder;
882   unsigned int frames_out;
883   uint64_t cx_time;
884   size_t nbytes;
885   stats_io_t stats;
886 #if CONFIG_FP_MB_STATS
887   stats_io_t fpmb_stats;
888 #endif
889   struct vpx_image *img;
890   vpx_codec_ctx_t decoder;
891   int mismatch_seen;
892 };
893
894 static void validate_positive_rational(const char *msg,
895                                        struct vpx_rational *rat) {
896   if (rat->den < 0) {
897     rat->num *= -1;
898     rat->den *= -1;
899   }
900
901   if (rat->num < 0) die("Error: %s must be positive\n", msg);
902
903   if (!rat->den) die("Error: %s has zero denominator\n", msg);
904 }
905
906 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
907   char **argi, **argj;
908   struct arg arg;
909   const int num_encoder = get_vpx_encoder_count();
910
911   if (num_encoder < 1) die("Error: no valid encoder available\n");
912
913   /* Initialize default parameters */
914   memset(global, 0, sizeof(*global));
915   global->codec = get_vpx_encoder_by_index(num_encoder - 1);
916   global->passes = 0;
917   global->color_type = I420;
918   /* Assign default deadline to good quality */
919   global->deadline = VPX_DL_GOOD_QUALITY;
920
921   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
922     arg.argv_step = 1;
923
924     if (arg_match(&arg, &help, argi)) {
925       show_help(stdout, 0);
926       exit(EXIT_SUCCESS);
927     } else if (arg_match(&arg, &codecarg, argi)) {
928       global->codec = get_vpx_encoder_by_name(arg.val);
929       if (!global->codec)
930         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
931     } else if (arg_match(&arg, &passes, argi)) {
932       global->passes = arg_parse_uint(&arg);
933
934       if (global->passes < 1 || global->passes > 2)
935         die("Error: Invalid number of passes (%d)\n", global->passes);
936     } else if (arg_match(&arg, &pass_arg, argi)) {
937       global->pass = arg_parse_uint(&arg);
938
939       if (global->pass < 1 || global->pass > 2)
940         die("Error: Invalid pass selected (%d)\n", global->pass);
941     } else if (arg_match(&arg, &usage, argi))
942       global->usage = arg_parse_uint(&arg);
943     else if (arg_match(&arg, &deadline, argi))
944       global->deadline = arg_parse_uint(&arg);
945     else if (arg_match(&arg, &best_dl, argi))
946       global->deadline = VPX_DL_BEST_QUALITY;
947     else if (arg_match(&arg, &good_dl, argi))
948       global->deadline = VPX_DL_GOOD_QUALITY;
949     else if (arg_match(&arg, &rt_dl, argi))
950       global->deadline = VPX_DL_REALTIME;
951     else if (arg_match(&arg, &use_yv12, argi))
952       global->color_type = YV12;
953     else if (arg_match(&arg, &use_i420, argi))
954       global->color_type = I420;
955     else if (arg_match(&arg, &use_i422, argi))
956       global->color_type = I422;
957     else if (arg_match(&arg, &use_i444, argi))
958       global->color_type = I444;
959     else if (arg_match(&arg, &use_i440, argi))
960       global->color_type = I440;
961     else if (arg_match(&arg, &quietarg, argi))
962       global->quiet = 1;
963     else if (arg_match(&arg, &verbosearg, argi))
964       global->verbose = 1;
965     else if (arg_match(&arg, &limit, argi))
966       global->limit = arg_parse_uint(&arg);
967     else if (arg_match(&arg, &skip, argi))
968       global->skip_frames = arg_parse_uint(&arg);
969     else if (arg_match(&arg, &psnrarg, argi))
970       global->show_psnr = 1;
971     else if (arg_match(&arg, &recontest, argi))
972       global->test_decode = arg_parse_enum_or_int(&arg);
973     else if (arg_match(&arg, &framerate, argi)) {
974       global->framerate = arg_parse_rational(&arg);
975       validate_positive_rational(arg.name, &global->framerate);
976       global->have_framerate = 1;
977     } else if (arg_match(&arg, &out_part, argi))
978       global->out_part = 1;
979     else if (arg_match(&arg, &debugmode, argi))
980       global->debug = 1;
981     else if (arg_match(&arg, &q_hist_n, argi))
982       global->show_q_hist_buckets = arg_parse_uint(&arg);
983     else if (arg_match(&arg, &rate_hist_n, argi))
984       global->show_rate_hist_buckets = arg_parse_uint(&arg);
985     else if (arg_match(&arg, &disable_warnings, argi))
986       global->disable_warnings = 1;
987     else if (arg_match(&arg, &disable_warning_prompt, argi))
988       global->disable_warning_prompt = 1;
989     else
990       argj++;
991   }
992
993   if (global->pass) {
994     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
995     if (global->pass > global->passes) {
996       warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
997            global->pass);
998       global->passes = global->pass;
999     }
1000   }
1001   /* Validate global config */
1002   if (global->passes == 0) {
1003 #if CONFIG_VP9_ENCODER
1004     // Make default VP9 passes = 2 until there is a better quality 1-pass
1005     // encoder
1006     if (global->codec != NULL && global->codec->name != NULL)
1007       global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
1008                         global->deadline != VPX_DL_REALTIME)
1009                            ? 2
1010                            : 1;
1011 #else
1012     global->passes = 1;
1013 #endif
1014   }
1015
1016   if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
1017     warn("Enforcing one-pass encoding in realtime mode\n");
1018     global->passes = 1;
1019   }
1020 }
1021
1022 static void open_input_file(struct VpxInputContext *input) {
1023   /* Parse certain options from the input file, if possible */
1024   input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
1025                                              : set_binary_mode(stdin);
1026
1027   if (!input->file) fatal("Failed to open input file");
1028
1029   if (!fseeko(input->file, 0, SEEK_END)) {
1030     /* Input file is seekable. Figure out how long it is, so we can get
1031      * progress info.
1032      */
1033     input->length = ftello(input->file);
1034     rewind(input->file);
1035   }
1036
1037   /* Default to 1:1 pixel aspect ratio. */
1038   input->pixel_aspect_ratio.numerator = 1;
1039   input->pixel_aspect_ratio.denominator = 1;
1040
1041   /* For RAW input sources, these bytes will applied on the first frame
1042    *  in read_frame().
1043    */
1044   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1045   input->detect.position = 0;
1046
1047   if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
1048     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
1049                        input->only_i420) >= 0) {
1050       input->file_type = FILE_TYPE_Y4M;
1051       input->width = input->y4m.pic_w;
1052       input->height = input->y4m.pic_h;
1053       input->pixel_aspect_ratio.numerator = input->y4m.par_n;
1054       input->pixel_aspect_ratio.denominator = input->y4m.par_d;
1055       input->framerate.numerator = input->y4m.fps_n;
1056       input->framerate.denominator = input->y4m.fps_d;
1057       input->fmt = input->y4m.vpx_fmt;
1058       input->bit_depth = input->y4m.bit_depth;
1059     } else
1060       fatal("Unsupported Y4M stream.");
1061   } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
1062     fatal("IVF is not supported as input.");
1063   } else {
1064     input->file_type = FILE_TYPE_RAW;
1065   }
1066 }
1067
1068 static void close_input_file(struct VpxInputContext *input) {
1069   fclose(input->file);
1070   if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
1071 }
1072
1073 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
1074                                        struct stream_state *prev) {
1075   struct stream_state *stream;
1076
1077   stream = calloc(1, sizeof(*stream));
1078   if (stream == NULL) {
1079     fatal("Failed to allocate new stream.");
1080   }
1081
1082   if (prev) {
1083     memcpy(stream, prev, sizeof(*stream));
1084     stream->index++;
1085     prev->next = stream;
1086   } else {
1087     vpx_codec_err_t res;
1088
1089     /* Populate encoder configuration */
1090     res = vpx_codec_enc_config_default(global->codec->codec_interface(),
1091                                        &stream->config.cfg, global->usage);
1092     if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1093
1094     /* Change the default timebase to a high enough value so that the
1095      * encoder will always create strictly increasing timestamps.
1096      */
1097     stream->config.cfg.g_timebase.den = 1000;
1098
1099     /* Never use the library's default resolution, require it be parsed
1100      * from the file or set on the command line.
1101      */
1102     stream->config.cfg.g_w = 0;
1103     stream->config.cfg.g_h = 0;
1104
1105     /* Initialize remaining stream parameters */
1106     stream->config.write_webm = 1;
1107 #if CONFIG_WEBM_IO
1108     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1109     stream->webm_ctx.last_pts_ns = -1;
1110     stream->webm_ctx.writer = NULL;
1111     stream->webm_ctx.segment = NULL;
1112 #endif
1113
1114     /* Allows removal of the application version from the EBML tags */
1115     stream->webm_ctx.debug = global->debug;
1116
1117     /* Default lag_in_frames is 0 in realtime mode CBR mode*/
1118     if (global->deadline == VPX_DL_REALTIME &&
1119         stream->config.cfg.rc_end_usage == 1)
1120       stream->config.cfg.g_lag_in_frames = 0;
1121   }
1122
1123   /* Output files must be specified for each stream */
1124   stream->config.out_fn = NULL;
1125
1126   stream->next = NULL;
1127   return stream;
1128 }
1129
1130 static int parse_stream_params(struct VpxEncoderConfig *global,
1131                                struct stream_state *stream, char **argv) {
1132   char **argi, **argj;
1133   struct arg arg;
1134   static const arg_def_t **ctrl_args = no_args;
1135   static const int *ctrl_args_map = NULL;
1136   struct stream_config *config = &stream->config;
1137   int eos_mark_found = 0;
1138 #if CONFIG_VP9_HIGHBITDEPTH
1139   int test_16bit_internal = 0;
1140 #endif
1141
1142   // Handle codec specific options
1143   if (0) {
1144 #if CONFIG_VP8_ENCODER
1145   } else if (strcmp(global->codec->name, "vp8") == 0) {
1146     ctrl_args = vp8_args;
1147     ctrl_args_map = vp8_arg_ctrl_map;
1148 #endif
1149 #if CONFIG_VP9_ENCODER
1150   } else if (strcmp(global->codec->name, "vp9") == 0) {
1151     ctrl_args = vp9_args;
1152     ctrl_args_map = vp9_arg_ctrl_map;
1153 #endif
1154   }
1155
1156   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1157     arg.argv_step = 1;
1158
1159     /* Once we've found an end-of-stream marker (--) we want to continue
1160      * shifting arguments but not consuming them.
1161      */
1162     if (eos_mark_found) {
1163       argj++;
1164       continue;
1165     } else if (!strcmp(*argj, "--")) {
1166       eos_mark_found = 1;
1167       continue;
1168     }
1169
1170     if (arg_match(&arg, &outputfile, argi)) {
1171       config->out_fn = arg.val;
1172     } else if (arg_match(&arg, &fpf_name, argi)) {
1173       config->stats_fn = arg.val;
1174 #if CONFIG_FP_MB_STATS
1175     } else if (arg_match(&arg, &fpmbf_name, argi)) {
1176       config->fpmb_stats_fn = arg.val;
1177 #endif
1178     } else if (arg_match(&arg, &use_webm, argi)) {
1179 #if CONFIG_WEBM_IO
1180       config->write_webm = 1;
1181 #else
1182       die("Error: --webm specified but webm is disabled.");
1183 #endif
1184     } else if (arg_match(&arg, &use_ivf, argi)) {
1185       config->write_webm = 0;
1186     } else if (arg_match(&arg, &threads, argi)) {
1187       config->cfg.g_threads = arg_parse_uint(&arg);
1188     } else if (arg_match(&arg, &profile, argi)) {
1189       config->cfg.g_profile = arg_parse_uint(&arg);
1190     } else if (arg_match(&arg, &width, argi)) {
1191       config->cfg.g_w = arg_parse_uint(&arg);
1192     } else if (arg_match(&arg, &height, argi)) {
1193       config->cfg.g_h = arg_parse_uint(&arg);
1194 #if CONFIG_VP9_HIGHBITDEPTH
1195     } else if (arg_match(&arg, &bitdeptharg, argi)) {
1196       config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1197     } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1198       config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1199 #endif
1200 #if CONFIG_WEBM_IO
1201     } else if (arg_match(&arg, &stereo_mode, argi)) {
1202       config->stereo_fmt = arg_parse_enum_or_int(&arg);
1203 #endif
1204     } else if (arg_match(&arg, &timebase, argi)) {
1205       config->cfg.g_timebase = arg_parse_rational(&arg);
1206       validate_positive_rational(arg.name, &config->cfg.g_timebase);
1207     } else if (arg_match(&arg, &error_resilient, argi)) {
1208       config->cfg.g_error_resilient = arg_parse_uint(&arg);
1209     } else if (arg_match(&arg, &end_usage, argi)) {
1210       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1211     } else if (arg_match(&arg, &lag_in_frames, argi)) {
1212       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1213       if (global->deadline == VPX_DL_REALTIME &&
1214           config->cfg.rc_end_usage == VPX_CBR &&
1215           config->cfg.g_lag_in_frames != 0) {
1216         warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
1217         config->cfg.g_lag_in_frames = 0;
1218       }
1219     } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1220       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1221     } else if (arg_match(&arg, &resize_allowed, argi)) {
1222       config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1223     } else if (arg_match(&arg, &resize_width, argi)) {
1224       config->cfg.rc_scaled_width = arg_parse_uint(&arg);
1225     } else if (arg_match(&arg, &resize_height, argi)) {
1226       config->cfg.rc_scaled_height = arg_parse_uint(&arg);
1227     } else if (arg_match(&arg, &resize_up_thresh, argi)) {
1228       config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1229     } else if (arg_match(&arg, &resize_down_thresh, argi)) {
1230       config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1231     } else if (arg_match(&arg, &end_usage, argi)) {
1232       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1233     } else if (arg_match(&arg, &target_bitrate, argi)) {
1234       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1235     } else if (arg_match(&arg, &min_quantizer, argi)) {
1236       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1237     } else if (arg_match(&arg, &max_quantizer, argi)) {
1238       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1239     } else if (arg_match(&arg, &undershoot_pct, argi)) {
1240       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1241     } else if (arg_match(&arg, &overshoot_pct, argi)) {
1242       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1243     } else if (arg_match(&arg, &buf_sz, argi)) {
1244       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1245     } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1246       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1247     } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1248       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1249     } else if (arg_match(&arg, &bias_pct, argi)) {
1250       config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1251       if (global->passes < 2)
1252         warn("option %s ignored in one-pass mode.\n", arg.name);
1253     } else if (arg_match(&arg, &minsection_pct, argi)) {
1254       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1255
1256       if (global->passes < 2)
1257         warn("option %s ignored in one-pass mode.\n", arg.name);
1258     } else if (arg_match(&arg, &maxsection_pct, argi)) {
1259       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1260
1261       if (global->passes < 2)
1262         warn("option %s ignored in one-pass mode.\n", arg.name);
1263     } else if (arg_match(&arg, &corpus_complexity, argi)) {
1264       config->cfg.rc_2pass_vbr_corpus_complexity = arg_parse_uint(&arg);
1265
1266       if (global->passes < 2)
1267         warn("option %s ignored in one-pass mode.\n", arg.name);
1268     } else if (arg_match(&arg, &kf_min_dist, argi)) {
1269       config->cfg.kf_min_dist = arg_parse_uint(&arg);
1270     } else if (arg_match(&arg, &kf_max_dist, argi)) {
1271       config->cfg.kf_max_dist = arg_parse_uint(&arg);
1272     } else if (arg_match(&arg, &kf_disabled, argi)) {
1273       config->cfg.kf_mode = VPX_KF_DISABLED;
1274 #if CONFIG_VP9_HIGHBITDEPTH
1275     } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
1276       if (strcmp(global->codec->name, "vp9") == 0) {
1277         test_16bit_internal = 1;
1278       }
1279 #endif
1280     } else {
1281       int i, match = 0;
1282       for (i = 0; ctrl_args[i]; i++) {
1283         if (arg_match(&arg, ctrl_args[i], argi)) {
1284           int j;
1285           match = 1;
1286
1287           /* Point either to the next free element or the first
1288            * instance of this control.
1289            */
1290           for (j = 0; j < config->arg_ctrl_cnt; j++)
1291             if (ctrl_args_map != NULL &&
1292                 config->arg_ctrls[j][0] == ctrl_args_map[i])
1293               break;
1294
1295           /* Update/insert */
1296           assert(j < (int)ARG_CTRL_CNT_MAX);
1297           if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
1298             config->arg_ctrls[j][0] = ctrl_args_map[i];
1299             config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1300             if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1301           }
1302         }
1303       }
1304       if (!match) argj++;
1305     }
1306   }
1307 #if CONFIG_VP9_HIGHBITDEPTH
1308   if (strcmp(global->codec->name, "vp9") == 0) {
1309     config->use_16bit_internal =
1310         test_16bit_internal | (config->cfg.g_profile > 1);
1311   }
1312 #endif
1313   return eos_mark_found;
1314 }
1315
1316 #define FOREACH_STREAM(func)                                \
1317   do {                                                      \
1318     struct stream_state *stream;                            \
1319     for (stream = streams; stream; stream = stream->next) { \
1320       func;                                                 \
1321     }                                                       \
1322   } while (0)
1323
1324 static void validate_stream_config(const struct stream_state *stream,
1325                                    const struct VpxEncoderConfig *global) {
1326   const struct stream_state *streami;
1327   (void)global;
1328
1329   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1330     fatal(
1331         "Stream %d: Specify stream dimensions with --width (-w) "
1332         " and --height (-h)",
1333         stream->index);
1334
1335   // Check that the codec bit depth is greater than the input bit depth.
1336   if (stream->config.cfg.g_input_bit_depth >
1337       (unsigned int)stream->config.cfg.g_bit_depth) {
1338     fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1339           stream->index, (int)stream->config.cfg.g_bit_depth,
1340           stream->config.cfg.g_input_bit_depth);
1341   }
1342
1343   for (streami = stream; streami; streami = streami->next) {
1344     /* All streams require output files */
1345     if (!streami->config.out_fn)
1346       fatal("Stream %d: Output file is required (specify with -o)",
1347             streami->index);
1348
1349     /* Check for two streams outputting to the same file */
1350     if (streami != stream) {
1351       const char *a = stream->config.out_fn;
1352       const char *b = streami->config.out_fn;
1353       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1354         fatal("Stream %d: duplicate output file (from stream %d)",
1355               streami->index, stream->index);
1356     }
1357
1358     /* Check for two streams sharing a stats file. */
1359     if (streami != stream) {
1360       const char *a = stream->config.stats_fn;
1361       const char *b = streami->config.stats_fn;
1362       if (a && b && !strcmp(a, b))
1363         fatal("Stream %d: duplicate stats file (from stream %d)",
1364               streami->index, stream->index);
1365     }
1366
1367 #if CONFIG_FP_MB_STATS
1368     /* Check for two streams sharing a mb stats file. */
1369     if (streami != stream) {
1370       const char *a = stream->config.fpmb_stats_fn;
1371       const char *b = streami->config.fpmb_stats_fn;
1372       if (a && b && !strcmp(a, b))
1373         fatal("Stream %d: duplicate mb stats file (from stream %d)",
1374               streami->index, stream->index);
1375     }
1376 #endif
1377   }
1378 }
1379
1380 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1381                                   unsigned int h) {
1382   if (!stream->config.cfg.g_w) {
1383     if (!stream->config.cfg.g_h)
1384       stream->config.cfg.g_w = w;
1385     else
1386       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1387   }
1388   if (!stream->config.cfg.g_h) {
1389     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1390   }
1391 }
1392
1393 static const char *file_type_to_string(enum VideoFileType t) {
1394   switch (t) {
1395     case FILE_TYPE_RAW: return "RAW";
1396     case FILE_TYPE_Y4M: return "Y4M";
1397     default: return "Other";
1398   }
1399 }
1400
1401 static const char *image_format_to_string(vpx_img_fmt_t f) {
1402   switch (f) {
1403     case VPX_IMG_FMT_I420: return "I420";
1404     case VPX_IMG_FMT_I422: return "I422";
1405     case VPX_IMG_FMT_I444: return "I444";
1406     case VPX_IMG_FMT_I440: return "I440";
1407     case VPX_IMG_FMT_YV12: return "YV12";
1408     case VPX_IMG_FMT_I42016: return "I42016";
1409     case VPX_IMG_FMT_I42216: return "I42216";
1410     case VPX_IMG_FMT_I44416: return "I44416";
1411     case VPX_IMG_FMT_I44016: return "I44016";
1412     default: return "Other";
1413   }
1414 }
1415
1416 static void show_stream_config(struct stream_state *stream,
1417                                struct VpxEncoderConfig *global,
1418                                struct VpxInputContext *input) {
1419 #define SHOW(field) \
1420   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
1421
1422   if (stream->index == 0) {
1423     fprintf(stderr, "Codec: %s\n",
1424             vpx_codec_iface_name(global->codec->codec_interface()));
1425     fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1426             input->filename, file_type_to_string(input->file_type),
1427             image_format_to_string(input->fmt));
1428   }
1429   if (stream->next || stream->index)
1430     fprintf(stderr, "\nStream Index: %d\n", stream->index);
1431   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1432   fprintf(stderr, "Encoder parameters:\n");
1433
1434   SHOW(g_usage);
1435   SHOW(g_threads);
1436   SHOW(g_profile);
1437   SHOW(g_w);
1438   SHOW(g_h);
1439   SHOW(g_bit_depth);
1440   SHOW(g_input_bit_depth);
1441   SHOW(g_timebase.num);
1442   SHOW(g_timebase.den);
1443   SHOW(g_error_resilient);
1444   SHOW(g_pass);
1445   SHOW(g_lag_in_frames);
1446   SHOW(rc_dropframe_thresh);
1447   SHOW(rc_resize_allowed);
1448   SHOW(rc_scaled_width);
1449   SHOW(rc_scaled_height);
1450   SHOW(rc_resize_up_thresh);
1451   SHOW(rc_resize_down_thresh);
1452   SHOW(rc_end_usage);
1453   SHOW(rc_target_bitrate);
1454   SHOW(rc_min_quantizer);
1455   SHOW(rc_max_quantizer);
1456   SHOW(rc_undershoot_pct);
1457   SHOW(rc_overshoot_pct);
1458   SHOW(rc_buf_sz);
1459   SHOW(rc_buf_initial_sz);
1460   SHOW(rc_buf_optimal_sz);
1461   SHOW(rc_2pass_vbr_bias_pct);
1462   SHOW(rc_2pass_vbr_minsection_pct);
1463   SHOW(rc_2pass_vbr_maxsection_pct);
1464   SHOW(rc_2pass_vbr_corpus_complexity);
1465   SHOW(kf_mode);
1466   SHOW(kf_min_dist);
1467   SHOW(kf_max_dist);
1468 }
1469
1470 static void open_output_file(struct stream_state *stream,
1471                              struct VpxEncoderConfig *global,
1472                              const struct VpxRational *pixel_aspect_ratio) {
1473   const char *fn = stream->config.out_fn;
1474   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1475
1476   if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1477
1478   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1479
1480   if (!stream->file) fatal("Failed to open output file");
1481
1482   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1483     fatal("WebM output to pipes not supported.");
1484
1485 #if CONFIG_WEBM_IO
1486   if (stream->config.write_webm) {
1487     stream->webm_ctx.stream = stream->file;
1488     write_webm_file_header(&stream->webm_ctx, cfg, stream->config.stereo_fmt,
1489                            global->codec->fourcc, pixel_aspect_ratio);
1490   }
1491 #else
1492   (void)pixel_aspect_ratio;
1493 #endif
1494
1495   if (!stream->config.write_webm) {
1496     ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1497   }
1498 }
1499
1500 static void close_output_file(struct stream_state *stream,
1501                               unsigned int fourcc) {
1502   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1503
1504   if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1505
1506 #if CONFIG_WEBM_IO
1507   if (stream->config.write_webm) {
1508     write_webm_file_footer(&stream->webm_ctx);
1509   }
1510 #endif
1511
1512   if (!stream->config.write_webm) {
1513     if (!fseek(stream->file, 0, SEEK_SET))
1514       ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1515                             stream->frames_out);
1516   }
1517
1518   fclose(stream->file);
1519 }
1520
1521 static void setup_pass(struct stream_state *stream,
1522                        struct VpxEncoderConfig *global, int pass) {
1523   if (stream->config.stats_fn) {
1524     if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1525       fatal("Failed to open statistics store");
1526   } else {
1527     if (!stats_open_mem(&stream->stats, pass))
1528       fatal("Failed to open statistics store");
1529   }
1530
1531 #if CONFIG_FP_MB_STATS
1532   if (stream->config.fpmb_stats_fn) {
1533     if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
1534                          pass))
1535       fatal("Failed to open mb statistics store");
1536   } else {
1537     if (!stats_open_mem(&stream->fpmb_stats, pass))
1538       fatal("Failed to open mb statistics store");
1539   }
1540 #endif
1541
1542   stream->config.cfg.g_pass = global->passes == 2
1543                                   ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1544                                   : VPX_RC_ONE_PASS;
1545   if (pass) {
1546     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1547 #if CONFIG_FP_MB_STATS
1548     stream->config.cfg.rc_firstpass_mb_stats_in =
1549         stats_get(&stream->fpmb_stats);
1550 #endif
1551   }
1552
1553   stream->cx_time = 0;
1554   stream->nbytes = 0;
1555   stream->frames_out = 0;
1556 }
1557
1558 static void initialize_encoder(struct stream_state *stream,
1559                                struct VpxEncoderConfig *global) {
1560   int i;
1561   int flags = 0;
1562
1563   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1564   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1565 #if CONFIG_VP9_HIGHBITDEPTH
1566   flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1567 #endif
1568
1569   /* Construct Encoder Context */
1570   vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1571                      &stream->config.cfg, flags);
1572   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1573
1574   /* Note that we bypass the vpx_codec_control wrapper macro because
1575    * we're being clever to store the control IDs in an array. Real
1576    * applications will want to make use of the enumerations directly
1577    */
1578   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1579     int ctrl = stream->config.arg_ctrls[i][0];
1580     int value = stream->config.arg_ctrls[i][1];
1581     if (vpx_codec_control_(&stream->encoder, ctrl, value))
1582       fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1583
1584     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1585   }
1586
1587 #if CONFIG_DECODERS
1588   if (global->test_decode != TEST_DECODE_OFF) {
1589     const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1590     vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1591   }
1592 #endif
1593 }
1594
1595 static void encode_frame(struct stream_state *stream,
1596                          struct VpxEncoderConfig *global, struct vpx_image *img,
1597                          unsigned int frames_in) {
1598   vpx_codec_pts_t frame_start, next_frame_start;
1599   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1600   struct vpx_usec_timer timer;
1601
1602   frame_start =
1603       (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1604       cfg->g_timebase.num / global->framerate.num;
1605   next_frame_start =
1606       (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1607       cfg->g_timebase.num / global->framerate.num;
1608
1609 /* Scale if necessary */
1610 #if CONFIG_VP9_HIGHBITDEPTH
1611   if (img) {
1612     if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1613         (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1614       if (img->fmt != VPX_IMG_FMT_I42016) {
1615         fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1616         exit(EXIT_FAILURE);
1617       }
1618 #if CONFIG_LIBYUV
1619       if (!stream->img) {
1620         stream->img =
1621             vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1622       }
1623       I420Scale_16(
1624           (uint16_t *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
1625           (uint16_t *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
1626           (uint16_t *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
1627           img->d_w, img->d_h, (uint16_t *)stream->img->planes[VPX_PLANE_Y],
1628           stream->img->stride[VPX_PLANE_Y] / 2,
1629           (uint16_t *)stream->img->planes[VPX_PLANE_U],
1630           stream->img->stride[VPX_PLANE_U] / 2,
1631           (uint16_t *)stream->img->planes[VPX_PLANE_V],
1632           stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
1633           stream->img->d_h, kFilterBox);
1634       img = stream->img;
1635 #else
1636       stream->encoder.err = 1;
1637       ctx_exit_on_error(&stream->encoder,
1638                         "Stream %d: Failed to encode frame.\n"
1639                         "Scaling disabled in this configuration. \n"
1640                         "To enable, configure with --enable-libyuv\n",
1641                         stream->index);
1642 #endif
1643     }
1644   }
1645 #endif
1646   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1647     if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1648       fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1649       exit(EXIT_FAILURE);
1650     }
1651 #if CONFIG_LIBYUV
1652     if (!stream->img)
1653       stream->img =
1654           vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
1655     I420Scale(
1656         img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1657         img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1658         img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
1659         stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
1660         stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
1661         stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
1662         stream->img->d_w, stream->img->d_h, kFilterBox);
1663     img = stream->img;
1664 #else
1665     stream->encoder.err = 1;
1666     ctx_exit_on_error(&stream->encoder,
1667                       "Stream %d: Failed to encode frame.\n"
1668                       "Scaling disabled in this configuration. \n"
1669                       "To enable, configure with --enable-libyuv\n",
1670                       stream->index);
1671 #endif
1672   }
1673
1674   vpx_usec_timer_start(&timer);
1675   vpx_codec_encode(&stream->encoder, img, frame_start,
1676                    (unsigned long)(next_frame_start - frame_start), 0,
1677                    global->deadline);
1678   vpx_usec_timer_mark(&timer);
1679   stream->cx_time += vpx_usec_timer_elapsed(&timer);
1680   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1681                     stream->index);
1682 }
1683
1684 static void update_quantizer_histogram(struct stream_state *stream) {
1685   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1686     int q;
1687
1688     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1689     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1690     stream->counts[q]++;
1691   }
1692 }
1693
1694 static void get_cx_data(struct stream_state *stream,
1695                         struct VpxEncoderConfig *global, int *got_data) {
1696   const vpx_codec_cx_pkt_t *pkt;
1697   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1698   vpx_codec_iter_t iter = NULL;
1699
1700   *got_data = 0;
1701   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1702     static size_t fsize = 0;
1703     static FileOffset ivf_header_pos = 0;
1704
1705     switch (pkt->kind) {
1706       case VPX_CODEC_CX_FRAME_PKT:
1707         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1708           stream->frames_out++;
1709         }
1710         if (!global->quiet)
1711           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1712
1713         update_rate_histogram(stream->rate_hist, cfg, pkt);
1714 #if CONFIG_WEBM_IO
1715         if (stream->config.write_webm) {
1716           write_webm_block(&stream->webm_ctx, cfg, pkt);
1717         }
1718 #endif
1719         if (!stream->config.write_webm) {
1720           if (pkt->data.frame.partition_id <= 0) {
1721             ivf_header_pos = ftello(stream->file);
1722             fsize = pkt->data.frame.sz;
1723
1724             ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1725           } else {
1726             fsize += pkt->data.frame.sz;
1727
1728             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1729               const FileOffset currpos = ftello(stream->file);
1730               fseeko(stream->file, ivf_header_pos, SEEK_SET);
1731               ivf_write_frame_size(stream->file, fsize);
1732               fseeko(stream->file, currpos, SEEK_SET);
1733             }
1734           }
1735
1736           (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1737                        stream->file);
1738         }
1739         stream->nbytes += pkt->data.raw.sz;
1740
1741         *got_data = 1;
1742 #if CONFIG_DECODERS
1743         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1744           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1745                            (unsigned int)pkt->data.frame.sz, NULL, 0);
1746           if (stream->decoder.err) {
1747             warn_or_exit_on_error(&stream->decoder,
1748                                   global->test_decode == TEST_DECODE_FATAL,
1749                                   "Failed to decode frame %d in stream %d",
1750                                   stream->frames_out + 1, stream->index);
1751             stream->mismatch_seen = stream->frames_out + 1;
1752           }
1753         }
1754 #endif
1755         break;
1756       case VPX_CODEC_STATS_PKT:
1757         stream->frames_out++;
1758         stats_write(&stream->stats, pkt->data.twopass_stats.buf,
1759                     pkt->data.twopass_stats.sz);
1760         stream->nbytes += pkt->data.raw.sz;
1761         break;
1762 #if CONFIG_FP_MB_STATS
1763       case VPX_CODEC_FPMB_STATS_PKT:
1764         stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
1765                     pkt->data.firstpass_mb_stats.sz);
1766         stream->nbytes += pkt->data.raw.sz;
1767         break;
1768 #endif
1769       case VPX_CODEC_PSNR_PKT:
1770
1771         if (global->show_psnr) {
1772           int i;
1773
1774           stream->psnr_sse_total += pkt->data.psnr.sse[0];
1775           stream->psnr_samples_total += pkt->data.psnr.samples[0];
1776           for (i = 0; i < 4; i++) {
1777             if (!global->quiet)
1778               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1779             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1780           }
1781           stream->psnr_count++;
1782         }
1783
1784         break;
1785       default: break;
1786     }
1787   }
1788 }
1789
1790 static void show_psnr(struct stream_state *stream, double peak) {
1791   int i;
1792   double ovpsnr;
1793
1794   if (!stream->psnr_count) return;
1795
1796   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1797   ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1798                        (double)stream->psnr_sse_total);
1799   fprintf(stderr, " %.3f", ovpsnr);
1800
1801   for (i = 0; i < 4; i++) {
1802     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1803   }
1804   fprintf(stderr, "\n");
1805 }
1806
1807 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1808   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1809 }
1810
1811 static void test_decode(struct stream_state *stream,
1812                         enum TestDecodeFatality fatal,
1813                         const VpxInterface *codec) {
1814   vpx_image_t enc_img, dec_img;
1815
1816   if (stream->mismatch_seen) return;
1817
1818   /* Get the internal reference frame */
1819   if (strcmp(codec->name, "vp8") == 0) {
1820     struct vpx_ref_frame ref_enc, ref_dec;
1821     int width, height;
1822
1823     width = (stream->config.cfg.g_w + 15) & ~15;
1824     height = (stream->config.cfg.g_h + 15) & ~15;
1825     vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1826     enc_img = ref_enc.img;
1827     vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1828     dec_img = ref_dec.img;
1829
1830     ref_enc.frame_type = VP8_LAST_FRAME;
1831     ref_dec.frame_type = VP8_LAST_FRAME;
1832     vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1833     vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1834   } else {
1835     struct vp9_ref_frame ref_enc, ref_dec;
1836
1837     ref_enc.idx = 0;
1838     ref_dec.idx = 0;
1839     vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1840     enc_img = ref_enc.img;
1841     vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1842     dec_img = ref_dec.img;
1843 #if CONFIG_VP9_HIGHBITDEPTH
1844     if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1845         (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1846       if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1847         vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1848                       enc_img.d_w, enc_img.d_h, 16);
1849         vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1850       }
1851       if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1852         vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1853                       dec_img.d_w, dec_img.d_h, 16);
1854         vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1855       }
1856     }
1857 #endif
1858   }
1859   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1860   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1861
1862   if (!compare_img(&enc_img, &dec_img)) {
1863     int y[4], u[4], v[4];
1864 #if CONFIG_VP9_HIGHBITDEPTH
1865     if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1866       find_mismatch_high(&enc_img, &dec_img, y, u, v);
1867     } else {
1868       find_mismatch(&enc_img, &dec_img, y, u, v);
1869     }
1870 #else
1871     find_mismatch(&enc_img, &dec_img, y, u, v);
1872 #endif
1873     stream->decoder.err = 1;
1874     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1875                           "Stream %d: Encode/decode mismatch on frame %d at"
1876                           " Y[%d, %d] {%d/%d},"
1877                           " U[%d, %d] {%d/%d},"
1878                           " V[%d, %d] {%d/%d}",
1879                           stream->index, stream->frames_out, y[0], y[1], y[2],
1880                           y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
1881     stream->mismatch_seen = stream->frames_out;
1882   }
1883
1884   vpx_img_free(&enc_img);
1885   vpx_img_free(&dec_img);
1886 }
1887
1888 static void print_time(const char *label, int64_t etl) {
1889   int64_t hours;
1890   int64_t mins;
1891   int64_t secs;
1892
1893   if (etl >= 0) {
1894     hours = etl / 3600;
1895     etl -= hours * 3600;
1896     mins = etl / 60;
1897     etl -= mins * 60;
1898     secs = etl;
1899
1900     fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
1901             hours, mins, secs);
1902   } else {
1903     fprintf(stderr, "[%3s  unknown] ", label);
1904   }
1905 }
1906
1907 int main(int argc, const char **argv_) {
1908   int pass;
1909   vpx_image_t raw;
1910 #if CONFIG_VP9_HIGHBITDEPTH
1911   vpx_image_t raw_shift;
1912   int allocated_raw_shift = 0;
1913   int use_16bit_internal = 0;
1914   int input_shift = 0;
1915 #endif
1916   int frame_avail, got_data;
1917
1918   struct VpxInputContext input;
1919   struct VpxEncoderConfig global;
1920   struct stream_state *streams = NULL;
1921   char **argv, **argi;
1922   uint64_t cx_time = 0;
1923   int stream_cnt = 0;
1924   int res = 0;
1925
1926   memset(&input, 0, sizeof(input));
1927   exec_name = argv_[0];
1928
1929   /* Setup default input stream settings */
1930   input.framerate.numerator = 30;
1931   input.framerate.denominator = 1;
1932   input.only_i420 = 1;
1933   input.bit_depth = 0;
1934
1935   /* First parse the global configuration values, because we want to apply
1936    * other parameters on top of the default configuration provided by the
1937    * codec.
1938    */
1939   argv = argv_dup(argc - 1, argv_ + 1);
1940   parse_global_config(&global, argv);
1941
1942   if (argc < 3) usage_exit();
1943
1944   switch (global.color_type) {
1945     case I420: input.fmt = VPX_IMG_FMT_I420; break;
1946     case I422: input.fmt = VPX_IMG_FMT_I422; break;
1947     case I444: input.fmt = VPX_IMG_FMT_I444; break;
1948     case I440: input.fmt = VPX_IMG_FMT_I440; break;
1949     case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
1950   }
1951
1952   {
1953     /* Now parse each stream's parameters. Using a local scope here
1954      * due to the use of 'stream' as loop variable in FOREACH_STREAM
1955      * loops
1956      */
1957     struct stream_state *stream = NULL;
1958
1959     do {
1960       stream = new_stream(&global, stream);
1961       stream_cnt++;
1962       if (!streams) streams = stream;
1963     } while (parse_stream_params(&global, stream, argv));
1964   }
1965
1966   /* Check for unrecognized options */
1967   for (argi = argv; *argi; argi++)
1968     if (argi[0][0] == '-' && argi[0][1])
1969       die("Error: Unrecognized option %s\n", *argi);
1970
1971   FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
1972                                       &stream->config.cfg););
1973
1974   /* Handle non-option arguments */
1975   input.filename = argv[0];
1976
1977   if (!input.filename) {
1978     fprintf(stderr, "No input file specified!\n");
1979     usage_exit();
1980   }
1981
1982   /* Decide if other chroma subsamplings than 4:2:0 are supported */
1983   if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
1984
1985   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1986     int frames_in = 0, seen_frames = 0;
1987     int64_t estimated_time_left = -1;
1988     int64_t average_rate = -1;
1989     int64_t lagged_count = 0;
1990
1991     open_input_file(&input);
1992
1993     /* If the input file doesn't specify its w/h (raw files), try to get
1994      * the data from the first stream's configuration.
1995      */
1996     if (!input.width || !input.height) {
1997       FOREACH_STREAM({
1998         if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1999           input.width = stream->config.cfg.g_w;
2000           input.height = stream->config.cfg.g_h;
2001           break;
2002         }
2003       });
2004     }
2005
2006     /* Update stream configurations from the input file's parameters */
2007     if (!input.width || !input.height)
2008       fatal(
2009           "Specify stream dimensions with --width (-w) "
2010           " and --height (-h)");
2011
2012     /* If input file does not specify bit-depth but input-bit-depth parameter
2013      * exists, assume that to be the input bit-depth. However, if the
2014      * input-bit-depth paramter does not exist, assume the input bit-depth
2015      * to be the same as the codec bit-depth.
2016      */
2017     if (!input.bit_depth) {
2018       FOREACH_STREAM({
2019         if (stream->config.cfg.g_input_bit_depth)
2020           input.bit_depth = stream->config.cfg.g_input_bit_depth;
2021         else
2022           input.bit_depth = stream->config.cfg.g_input_bit_depth =
2023               (int)stream->config.cfg.g_bit_depth;
2024       });
2025       if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
2026     } else {
2027       FOREACH_STREAM(
2028           { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
2029     }
2030
2031     FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
2032     FOREACH_STREAM(validate_stream_config(stream, &global));
2033
2034     /* Ensure that --passes and --pass are consistent. If --pass is set and
2035      * --passes=2, ensure --fpf was set.
2036      */
2037     if (global.pass && global.passes == 2)
2038       FOREACH_STREAM({
2039         if (!stream->config.stats_fn)
2040           die("Stream %d: Must specify --fpf when --pass=%d"
2041               " and --passes=2\n",
2042               stream->index, global.pass);
2043       });
2044
2045 #if !CONFIG_WEBM_IO
2046     FOREACH_STREAM({
2047       if (stream->config.write_webm) {
2048         stream->config.write_webm = 0;
2049         warn(
2050             "vpxenc was compiled without WebM container support."
2051             "Producing IVF output");
2052       }
2053     });
2054 #endif
2055
2056     /* Use the frame rate from the file only if none was specified
2057      * on the command-line.
2058      */
2059     if (!global.have_framerate) {
2060       global.framerate.num = input.framerate.numerator;
2061       global.framerate.den = input.framerate.denominator;
2062       FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
2063                      stream->config.cfg.g_timebase.num = global.framerate.den);
2064     }
2065
2066     /* Show configuration */
2067     if (global.verbose && pass == 0)
2068       FOREACH_STREAM(show_stream_config(stream, &global, &input));
2069
2070     if (pass == (global.pass ? global.pass - 1 : 0)) {
2071       if (input.file_type == FILE_TYPE_Y4M)
2072         /*The Y4M reader does its own allocation.
2073           Just initialize this here to avoid problems if we never read any
2074            frames.*/
2075         memset(&raw, 0, sizeof(raw));
2076       else
2077         vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2078
2079       FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
2080                          &stream->config.cfg, &global.framerate));
2081     }
2082
2083     FOREACH_STREAM(setup_pass(stream, &global, pass));
2084     FOREACH_STREAM(
2085         open_output_file(stream, &global, &input.pixel_aspect_ratio));
2086     FOREACH_STREAM(initialize_encoder(stream, &global));
2087
2088 #if CONFIG_VP9_HIGHBITDEPTH
2089     if (strcmp(global.codec->name, "vp9") == 0) {
2090       // Check to see if at least one stream uses 16 bit internal.
2091       // Currently assume that the bit_depths for all streams using
2092       // highbitdepth are the same.
2093       FOREACH_STREAM({
2094         if (stream->config.use_16bit_internal) {
2095           use_16bit_internal = 1;
2096         }
2097         if (stream->config.cfg.g_profile == 0) {
2098           input_shift = 0;
2099         } else {
2100           input_shift = (int)stream->config.cfg.g_bit_depth -
2101                         stream->config.cfg.g_input_bit_depth;
2102         }
2103       });
2104     }
2105 #endif
2106
2107     frame_avail = 1;
2108     got_data = 0;
2109
2110     while (frame_avail || got_data) {
2111       struct vpx_usec_timer timer;
2112
2113       if (!global.limit || frames_in < global.limit) {
2114         frame_avail = read_frame(&input, &raw);
2115
2116         if (frame_avail) frames_in++;
2117         seen_frames =
2118             frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2119
2120         if (!global.quiet) {
2121           float fps = usec_to_fps(cx_time, seen_frames);
2122           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2123
2124           if (stream_cnt == 1)
2125             fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2126                     streams->frames_out, (int64_t)streams->nbytes);
2127           else
2128             fprintf(stderr, "frame %4d ", frames_in);
2129
2130           fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2131                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
2132                   cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2133                   fps >= 1.0 ? "fps" : "fpm");
2134           print_time("ETA", estimated_time_left);
2135         }
2136
2137       } else
2138         frame_avail = 0;
2139
2140       if (frames_in > global.skip_frames) {
2141 #if CONFIG_VP9_HIGHBITDEPTH
2142         vpx_image_t *frame_to_encode;
2143         if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2144           assert(use_16bit_internal);
2145           // Input bit depth and stream bit depth do not match, so up
2146           // shift frame to stream bit depth
2147           if (!allocated_raw_shift) {
2148             vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2149                           input.width, input.height, 32);
2150             allocated_raw_shift = 1;
2151           }
2152           vpx_img_upshift(&raw_shift, &raw, input_shift);
2153           frame_to_encode = &raw_shift;
2154         } else {
2155           frame_to_encode = &raw;
2156         }
2157         vpx_usec_timer_start(&timer);
2158         if (use_16bit_internal) {
2159           assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2160           FOREACH_STREAM({
2161             if (stream->config.use_16bit_internal)
2162               encode_frame(stream, &global,
2163                            frame_avail ? frame_to_encode : NULL, frames_in);
2164             else
2165               assert(0);
2166           });
2167         } else {
2168           assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2169           FOREACH_STREAM(encode_frame(stream, &global,
2170                                       frame_avail ? frame_to_encode : NULL,
2171                                       frames_in));
2172         }
2173 #else
2174         vpx_usec_timer_start(&timer);
2175         FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
2176                                     frames_in));
2177 #endif
2178         vpx_usec_timer_mark(&timer);
2179         cx_time += vpx_usec_timer_elapsed(&timer);
2180
2181         FOREACH_STREAM(update_quantizer_histogram(stream));
2182
2183         got_data = 0;
2184         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2185
2186         if (!got_data && input.length && streams != NULL &&
2187             !streams->frames_out) {
2188           lagged_count = global.limit ? seen_frames : ftello(input.file);
2189         } else if (input.length) {
2190           int64_t remaining;
2191           int64_t rate;
2192
2193           if (global.limit) {
2194             const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2195
2196             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2197             remaining = 1000 * (global.limit - global.skip_frames -
2198                                 seen_frames + lagged_count);
2199           } else {
2200             const int64_t input_pos = ftello(input.file);
2201             const int64_t input_pos_lagged = input_pos - lagged_count;
2202             const int64_t limit = input.length;
2203
2204             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2205             remaining = limit - input_pos + lagged_count;
2206           }
2207
2208           average_rate =
2209               (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2210           estimated_time_left = average_rate ? remaining / average_rate : -1;
2211         }
2212
2213         if (got_data && global.test_decode != TEST_DECODE_OFF)
2214           FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2215       }
2216
2217       fflush(stdout);
2218       if (!global.quiet) fprintf(stderr, "\033[K");
2219     }
2220
2221     if (stream_cnt > 1) fprintf(stderr, "\n");
2222
2223     if (!global.quiet) {
2224       FOREACH_STREAM(fprintf(
2225           stderr,
2226           "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64 "b/f %7" PRId64
2227           "b/s %7" PRId64 " %s (%.2f fps)\033[K\n",
2228           pass + 1, global.passes, frames_in, stream->frames_out,
2229           (int64_t)stream->nbytes,
2230           seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2231           seen_frames
2232               ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2233                     global.framerate.den / seen_frames
2234               : 0,
2235           stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2236           stream->cx_time > 9999999 ? "ms" : "us",
2237           usec_to_fps(stream->cx_time, seen_frames)));
2238     }
2239
2240     if (global.show_psnr) {
2241       if (global.codec->fourcc == VP9_FOURCC) {
2242         FOREACH_STREAM(
2243             show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2244       } else {
2245         FOREACH_STREAM(show_psnr(stream, 255.0));
2246       }
2247     }
2248
2249     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2250
2251     if (global.test_decode != TEST_DECODE_OFF) {
2252       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2253     }
2254
2255     close_input_file(&input);
2256
2257     if (global.test_decode == TEST_DECODE_FATAL) {
2258       FOREACH_STREAM(res |= stream->mismatch_seen);
2259     }
2260     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2261
2262     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2263
2264 #if CONFIG_FP_MB_STATS
2265     FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2266 #endif
2267
2268     if (global.pass) break;
2269   }
2270
2271   if (global.show_q_hist_buckets)
2272     FOREACH_STREAM(
2273         show_q_histogram(stream->counts, global.show_q_hist_buckets));
2274
2275   if (global.show_rate_hist_buckets)
2276     FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2277                                        global.show_rate_hist_buckets));
2278   FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2279
2280 #if CONFIG_INTERNAL_STATS
2281   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2282    * to match some existing utilities.
2283    */
2284   if (!(global.pass == 1 && global.passes == 2))
2285     FOREACH_STREAM({
2286       FILE *f = fopen("opsnr.stt", "a");
2287       if (stream->mismatch_seen) {
2288         fprintf(f, "First mismatch occurred in frame %d\n",
2289                 stream->mismatch_seen);
2290       } else {
2291         fprintf(f, "No mismatch detected in recon buffers\n");
2292       }
2293       fclose(f);
2294     });
2295 #endif
2296
2297 #if CONFIG_VP9_HIGHBITDEPTH
2298   if (allocated_raw_shift) vpx_img_free(&raw_shift);
2299 #endif
2300   vpx_img_free(&raw);
2301   free(argv);
2302   free(streams);
2303   return res ? EXIT_FAILURE : EXIT_SUCCESS;
2304 }