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