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