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