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