]> granicus.if.org Git - libvpx/blob - vpxenc.c
Merge "Use defines for inline and __builtin_prefetch"
[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   (void)global;
1201
1202   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1203     fatal("Stream %d: Specify stream dimensions with --width (-w) "
1204           " and --height (-h)", stream->index);
1205
1206   // Check that the codec bit depth is greater than the input bit depth.
1207   if (stream->config.cfg.g_input_bit_depth >
1208       (unsigned int)stream->config.cfg.g_bit_depth) {
1209     fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1210           stream->index, (int)stream->config.cfg.g_bit_depth,
1211           stream->config.cfg.g_input_bit_depth);
1212   }
1213
1214   for (streami = stream; streami; streami = streami->next) {
1215     /* All streams require output files */
1216     if (!streami->config.out_fn)
1217       fatal("Stream %d: Output file is required (specify with -o)",
1218             streami->index);
1219
1220     /* Check for two streams outputting to the same file */
1221     if (streami != stream) {
1222       const char *a = stream->config.out_fn;
1223       const char *b = streami->config.out_fn;
1224       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1225         fatal("Stream %d: duplicate output file (from stream %d)",
1226               streami->index, stream->index);
1227     }
1228
1229     /* Check for two streams sharing a stats file. */
1230     if (streami != stream) {
1231       const char *a = stream->config.stats_fn;
1232       const char *b = streami->config.stats_fn;
1233       if (a && b && !strcmp(a, b))
1234         fatal("Stream %d: duplicate stats file (from stream %d)",
1235               streami->index, stream->index);
1236     }
1237
1238 #if CONFIG_FP_MB_STATS
1239     /* Check for two streams sharing a mb stats file. */
1240     if (streami != stream) {
1241       const char *a = stream->config.fpmb_stats_fn;
1242       const char *b = streami->config.fpmb_stats_fn;
1243       if (a && b && !strcmp(a, b))
1244         fatal("Stream %d: duplicate mb stats file (from stream %d)",
1245               streami->index, stream->index);
1246     }
1247 #endif
1248   }
1249 }
1250
1251
1252 static void set_stream_dimensions(struct stream_state *stream,
1253                                   unsigned int w,
1254                                   unsigned int h) {
1255   if (!stream->config.cfg.g_w) {
1256     if (!stream->config.cfg.g_h)
1257       stream->config.cfg.g_w = w;
1258     else
1259       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1260   }
1261   if (!stream->config.cfg.g_h) {
1262     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1263   }
1264 }
1265
1266
1267 static void set_default_kf_interval(struct stream_state *stream,
1268                                     struct VpxEncoderConfig *global) {
1269   /* Use a max keyframe interval of 5 seconds, if none was
1270    * specified on the command line.
1271    */
1272   if (!stream->config.have_kf_max_dist) {
1273     double framerate = (double)global->framerate.num / global->framerate.den;
1274     if (framerate > 0.0)
1275       stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1276   }
1277 }
1278
1279 static const char* file_type_to_string(enum VideoFileType t) {
1280   switch (t) {
1281     case FILE_TYPE_RAW: return "RAW";
1282     case FILE_TYPE_Y4M: return "Y4M";
1283     default: return "Other";
1284   }
1285 }
1286
1287 static const char* image_format_to_string(vpx_img_fmt_t f) {
1288   switch (f) {
1289     case VPX_IMG_FMT_I420: return "I420";
1290     case VPX_IMG_FMT_I422: return "I422";
1291     case VPX_IMG_FMT_I444: return "I444";
1292     case VPX_IMG_FMT_I440: return "I440";
1293     case VPX_IMG_FMT_YV12: return "YV12";
1294     case VPX_IMG_FMT_I42016: return "I42016";
1295     case VPX_IMG_FMT_I42216: return "I42216";
1296     case VPX_IMG_FMT_I44416: return "I44416";
1297     case VPX_IMG_FMT_I44016: return "I44016";
1298     default: return "Other";
1299   }
1300 }
1301
1302 static void show_stream_config(struct stream_state *stream,
1303                                struct VpxEncoderConfig *global,
1304                                struct VpxInputContext *input) {
1305
1306 #define SHOW(field) \
1307   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
1308
1309   if (stream->index == 0) {
1310     fprintf(stderr, "Codec: %s\n",
1311             vpx_codec_iface_name(global->codec->codec_interface()));
1312     fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1313             input->filename,
1314             file_type_to_string(input->file_type),
1315             image_format_to_string(input->fmt));
1316   }
1317   if (stream->next || stream->index)
1318     fprintf(stderr, "\nStream Index: %d\n", stream->index);
1319   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1320   fprintf(stderr, "Encoder parameters:\n");
1321
1322   SHOW(g_usage);
1323   SHOW(g_threads);
1324   SHOW(g_profile);
1325   SHOW(g_w);
1326   SHOW(g_h);
1327   SHOW(g_bit_depth);
1328   SHOW(g_input_bit_depth);
1329   SHOW(g_timebase.num);
1330   SHOW(g_timebase.den);
1331   SHOW(g_error_resilient);
1332   SHOW(g_pass);
1333   SHOW(g_lag_in_frames);
1334   SHOW(rc_dropframe_thresh);
1335   SHOW(rc_resize_allowed);
1336   SHOW(rc_scaled_width);
1337   SHOW(rc_scaled_height);
1338   SHOW(rc_resize_up_thresh);
1339   SHOW(rc_resize_down_thresh);
1340   SHOW(rc_end_usage);
1341   SHOW(rc_target_bitrate);
1342   SHOW(rc_min_quantizer);
1343   SHOW(rc_max_quantizer);
1344   SHOW(rc_undershoot_pct);
1345   SHOW(rc_overshoot_pct);
1346   SHOW(rc_buf_sz);
1347   SHOW(rc_buf_initial_sz);
1348   SHOW(rc_buf_optimal_sz);
1349   SHOW(rc_2pass_vbr_bias_pct);
1350   SHOW(rc_2pass_vbr_minsection_pct);
1351   SHOW(rc_2pass_vbr_maxsection_pct);
1352   SHOW(kf_mode);
1353   SHOW(kf_min_dist);
1354   SHOW(kf_max_dist);
1355 }
1356
1357
1358 static void open_output_file(struct stream_state *stream,
1359                              struct VpxEncoderConfig *global) {
1360   const char *fn = stream->config.out_fn;
1361   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1362
1363   if (cfg->g_pass == VPX_RC_FIRST_PASS)
1364     return;
1365
1366   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1367
1368   if (!stream->file)
1369     fatal("Failed to open output file");
1370
1371   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1372     fatal("WebM output to pipes not supported.");
1373
1374 #if CONFIG_WEBM_IO
1375   if (stream->config.write_webm) {
1376     stream->ebml.stream = stream->file;
1377     write_webm_file_header(&stream->ebml, cfg,
1378                            &global->framerate,
1379                            stream->config.stereo_fmt,
1380                            global->codec->fourcc);
1381   }
1382 #endif
1383
1384   if (!stream->config.write_webm) {
1385     ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1386   }
1387 }
1388
1389
1390 static void close_output_file(struct stream_state *stream,
1391                               unsigned int fourcc) {
1392   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1393
1394   if (cfg->g_pass == VPX_RC_FIRST_PASS)
1395     return;
1396
1397 #if CONFIG_WEBM_IO
1398   if (stream->config.write_webm) {
1399     write_webm_file_footer(&stream->ebml);
1400   }
1401 #endif
1402
1403   if (!stream->config.write_webm) {
1404     if (!fseek(stream->file, 0, SEEK_SET))
1405       ivf_write_file_header(stream->file, &stream->config.cfg,
1406                             fourcc,
1407                             stream->frames_out);
1408   }
1409
1410   fclose(stream->file);
1411 }
1412
1413
1414 static void setup_pass(struct stream_state *stream,
1415                        struct VpxEncoderConfig *global,
1416                        int pass) {
1417   if (stream->config.stats_fn) {
1418     if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1419                          pass))
1420       fatal("Failed to open statistics store");
1421   } else {
1422     if (!stats_open_mem(&stream->stats, pass))
1423       fatal("Failed to open statistics store");
1424   }
1425
1426 #if CONFIG_FP_MB_STATS
1427   if (stream->config.fpmb_stats_fn) {
1428     if (!stats_open_file(&stream->fpmb_stats,
1429                          stream->config.fpmb_stats_fn, pass))
1430       fatal("Failed to open mb statistics store");
1431   } else {
1432     if (!stats_open_mem(&stream->fpmb_stats, pass))
1433       fatal("Failed to open mb statistics store");
1434   }
1435 #endif
1436
1437   stream->config.cfg.g_pass = global->passes == 2
1438                               ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1439                             : VPX_RC_ONE_PASS;
1440   if (pass) {
1441     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1442 #if CONFIG_FP_MB_STATS
1443     stream->config.cfg.rc_firstpass_mb_stats_in =
1444         stats_get(&stream->fpmb_stats);
1445 #endif
1446   }
1447
1448   stream->cx_time = 0;
1449   stream->nbytes = 0;
1450   stream->frames_out = 0;
1451 }
1452
1453
1454 static void initialize_encoder(struct stream_state *stream,
1455                                struct VpxEncoderConfig *global) {
1456   int i;
1457   int flags = 0;
1458
1459   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1460   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1461 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1462   flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1463 #endif
1464
1465   /* Construct Encoder Context */
1466   vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1467                      &stream->config.cfg, flags);
1468   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1469
1470   /* Note that we bypass the vpx_codec_control wrapper macro because
1471    * we're being clever to store the control IDs in an array. Real
1472    * applications will want to make use of the enumerations directly
1473    */
1474   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1475     int ctrl = stream->config.arg_ctrls[i][0];
1476     int value = stream->config.arg_ctrls[i][1];
1477     if (vpx_codec_control_(&stream->encoder, ctrl, value))
1478       fprintf(stderr, "Error: Tried to set control %d = %d\n",
1479               ctrl, value);
1480
1481     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1482   }
1483
1484 #if CONFIG_DECODERS
1485   if (global->test_decode != TEST_DECODE_OFF) {
1486     const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1487     vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1488   }
1489 #endif
1490 }
1491
1492
1493 static void encode_frame(struct stream_state *stream,
1494                          struct VpxEncoderConfig *global,
1495                          struct vpx_image *img,
1496                          unsigned int frames_in) {
1497   vpx_codec_pts_t frame_start, next_frame_start;
1498   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1499   struct vpx_usec_timer timer;
1500
1501   frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1502                  * global->framerate.den)
1503                 / cfg->g_timebase.num / global->framerate.num;
1504   next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1505                       * global->framerate.den)
1506                      / cfg->g_timebase.num / global->framerate.num;
1507
1508   /* Scale if necessary */
1509 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1510   if (img) {
1511     if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1512         (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1513       if (img->fmt != VPX_IMG_FMT_I42016) {
1514         fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1515         exit(EXIT_FAILURE);
1516       }
1517 #if CONFIG_LIBYUV
1518       if (!stream->img) {
1519         stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I42016,
1520                                     cfg->g_w, cfg->g_h, 16);
1521       }
1522       I420Scale_16((uint16*)img->planes[VPX_PLANE_Y],
1523                    img->stride[VPX_PLANE_Y]/2,
1524                    (uint16*)img->planes[VPX_PLANE_U],
1525                    img->stride[VPX_PLANE_U]/2,
1526                    (uint16*)img->planes[VPX_PLANE_V],
1527                    img->stride[VPX_PLANE_V]/2,
1528                    img->d_w, img->d_h,
1529                    (uint16*)stream->img->planes[VPX_PLANE_Y],
1530                    stream->img->stride[VPX_PLANE_Y]/2,
1531                    (uint16*)stream->img->planes[VPX_PLANE_U],
1532                    stream->img->stride[VPX_PLANE_U]/2,
1533                    (uint16*)stream->img->planes[VPX_PLANE_V],
1534                    stream->img->stride[VPX_PLANE_V]/2,
1535                    stream->img->d_w, stream->img->d_h,
1536                    kFilterBox);
1537       img = stream->img;
1538 #else
1539     stream->encoder.err = 1;
1540     ctx_exit_on_error(&stream->encoder,
1541                       "Stream %d: Failed to encode frame.\n"
1542                       "Scaling disabled in this configuration. \n"
1543                       "To enable, configure with --enable-libyuv\n",
1544                       stream->index);
1545 #endif
1546     }
1547   }
1548 #endif
1549   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1550     if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1551       fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1552       exit(EXIT_FAILURE);
1553     }
1554 #if CONFIG_LIBYUV
1555     if (!stream->img)
1556       stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1557                                   cfg->g_w, cfg->g_h, 16);
1558     I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1559               img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1560               img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1561               img->d_w, img->d_h,
1562               stream->img->planes[VPX_PLANE_Y],
1563               stream->img->stride[VPX_PLANE_Y],
1564               stream->img->planes[VPX_PLANE_U],
1565               stream->img->stride[VPX_PLANE_U],
1566               stream->img->planes[VPX_PLANE_V],
1567               stream->img->stride[VPX_PLANE_V],
1568               stream->img->d_w, stream->img->d_h,
1569               kFilterBox);
1570     img = stream->img;
1571 #else
1572     stream->encoder.err = 1;
1573     ctx_exit_on_error(&stream->encoder,
1574                       "Stream %d: Failed to encode frame.\n"
1575                       "Scaling disabled in this configuration. \n"
1576                       "To enable, configure with --enable-libyuv\n",
1577                       stream->index);
1578 #endif
1579   }
1580
1581   vpx_usec_timer_start(&timer);
1582   vpx_codec_encode(&stream->encoder, img, frame_start,
1583                    (unsigned long)(next_frame_start - frame_start),
1584                    0, global->deadline);
1585   vpx_usec_timer_mark(&timer);
1586   stream->cx_time += vpx_usec_timer_elapsed(&timer);
1587   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1588                     stream->index);
1589 }
1590
1591
1592 static void update_quantizer_histogram(struct stream_state *stream) {
1593   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1594     int q;
1595
1596     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1597     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1598     stream->counts[q]++;
1599   }
1600 }
1601
1602
1603 static void get_cx_data(struct stream_state *stream,
1604                         struct VpxEncoderConfig *global,
1605                         int *got_data) {
1606   const vpx_codec_cx_pkt_t *pkt;
1607   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1608   vpx_codec_iter_t iter = NULL;
1609
1610   *got_data = 0;
1611   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1612     static size_t fsize = 0;
1613     static int64_t ivf_header_pos = 0;
1614
1615     switch (pkt->kind) {
1616       case VPX_CODEC_CX_FRAME_PKT:
1617         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1618           stream->frames_out++;
1619         }
1620         if (!global->quiet)
1621           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1622
1623         update_rate_histogram(stream->rate_hist, cfg, pkt);
1624 #if CONFIG_WEBM_IO
1625         if (stream->config.write_webm) {
1626           write_webm_block(&stream->ebml, cfg, pkt);
1627         }
1628 #endif
1629         if (!stream->config.write_webm) {
1630           if (pkt->data.frame.partition_id <= 0) {
1631             ivf_header_pos = ftello(stream->file);
1632             fsize = pkt->data.frame.sz;
1633
1634             ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1635           } else {
1636             fsize += pkt->data.frame.sz;
1637
1638             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1639               const int64_t currpos = ftello(stream->file);
1640               fseeko(stream->file, ivf_header_pos, SEEK_SET);
1641               ivf_write_frame_size(stream->file, fsize);
1642               fseeko(stream->file, currpos, SEEK_SET);
1643             }
1644           }
1645
1646           (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1647                         stream->file);
1648         }
1649         stream->nbytes += pkt->data.raw.sz;
1650
1651         *got_data = 1;
1652 #if CONFIG_DECODERS
1653         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1654           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1655                            (unsigned int)pkt->data.frame.sz, NULL, 0);
1656           if (stream->decoder.err) {
1657             warn_or_exit_on_error(&stream->decoder,
1658                                   global->test_decode == TEST_DECODE_FATAL,
1659                                   "Failed to decode frame %d in stream %d",
1660                                   stream->frames_out + 1, stream->index);
1661             stream->mismatch_seen = stream->frames_out + 1;
1662           }
1663         }
1664 #endif
1665         break;
1666       case VPX_CODEC_STATS_PKT:
1667         stream->frames_out++;
1668         stats_write(&stream->stats,
1669                     pkt->data.twopass_stats.buf,
1670                     pkt->data.twopass_stats.sz);
1671         stream->nbytes += pkt->data.raw.sz;
1672         break;
1673 #if CONFIG_FP_MB_STATS
1674       case VPX_CODEC_FPMB_STATS_PKT:
1675         stats_write(&stream->fpmb_stats,
1676                     pkt->data.firstpass_mb_stats.buf,
1677                     pkt->data.firstpass_mb_stats.sz);
1678         stream->nbytes += pkt->data.raw.sz;
1679         break;
1680 #endif
1681       case VPX_CODEC_PSNR_PKT:
1682
1683         if (global->show_psnr) {
1684           int i;
1685
1686           stream->psnr_sse_total += pkt->data.psnr.sse[0];
1687           stream->psnr_samples_total += pkt->data.psnr.samples[0];
1688           for (i = 0; i < 4; i++) {
1689             if (!global->quiet)
1690               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1691             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1692           }
1693           stream->psnr_count++;
1694         }
1695
1696         break;
1697       default:
1698         break;
1699     }
1700   }
1701 }
1702
1703
1704 static void show_psnr(struct stream_state  *stream, double peak) {
1705   int i;
1706   double ovpsnr;
1707
1708   if (!stream->psnr_count)
1709     return;
1710
1711   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1712   ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1713                        (double)stream->psnr_sse_total);
1714   fprintf(stderr, " %.3f", ovpsnr);
1715
1716   for (i = 0; i < 4; i++) {
1717     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1718   }
1719   fprintf(stderr, "\n");
1720 }
1721
1722
1723 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1724   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1725 }
1726
1727 static void test_decode(struct stream_state  *stream,
1728                         enum TestDecodeFatality fatal,
1729                         const VpxInterface *codec) {
1730   vpx_image_t enc_img, dec_img;
1731
1732   if (stream->mismatch_seen)
1733     return;
1734
1735   /* Get the internal reference frame */
1736   if (strcmp(codec->name, "vp8") == 0) {
1737     struct vpx_ref_frame ref_enc, ref_dec;
1738     int width, height;
1739
1740     width = (stream->config.cfg.g_w + 15) & ~15;
1741     height = (stream->config.cfg.g_h + 15) & ~15;
1742     vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1743     enc_img = ref_enc.img;
1744     vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1745     dec_img = ref_dec.img;
1746
1747     ref_enc.frame_type = VP8_LAST_FRAME;
1748     ref_dec.frame_type = VP8_LAST_FRAME;
1749     vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1750     vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1751   } else {
1752     struct vp9_ref_frame ref_enc, ref_dec;
1753
1754     ref_enc.idx = 0;
1755     ref_dec.idx = 0;
1756     vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1757     enc_img = ref_enc.img;
1758     vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1759     dec_img = ref_dec.img;
1760 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1761     if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1762         (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1763       if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1764         vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1765                       enc_img.d_w, enc_img.d_h, 16);
1766         vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1767       }
1768       if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1769         vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1770                       dec_img.d_w, dec_img.d_h, 16);
1771         vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1772       }
1773     }
1774 #endif
1775   }
1776   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1777   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1778
1779   if (!compare_img(&enc_img, &dec_img)) {
1780     int y[4], u[4], v[4];
1781 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1782     if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1783       find_mismatch_high(&enc_img, &dec_img, y, u, v);
1784     } else {
1785       find_mismatch(&enc_img, &dec_img, y, u, v);
1786     }
1787 #else
1788     find_mismatch(&enc_img, &dec_img, y, u, v);
1789 #endif
1790     stream->decoder.err = 1;
1791     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1792                           "Stream %d: Encode/decode mismatch on frame %d at"
1793                           " Y[%d, %d] {%d/%d},"
1794                           " U[%d, %d] {%d/%d},"
1795                           " V[%d, %d] {%d/%d}",
1796                           stream->index, stream->frames_out,
1797                           y[0], y[1], y[2], y[3],
1798                           u[0], u[1], u[2], u[3],
1799                           v[0], v[1], v[2], v[3]);
1800     stream->mismatch_seen = stream->frames_out;
1801   }
1802
1803   vpx_img_free(&enc_img);
1804   vpx_img_free(&dec_img);
1805 }
1806
1807
1808 static void print_time(const char *label, int64_t etl) {
1809   int64_t hours;
1810   int64_t mins;
1811   int64_t secs;
1812
1813   if (etl >= 0) {
1814     hours = etl / 3600;
1815     etl -= hours * 3600;
1816     mins = etl / 60;
1817     etl -= mins * 60;
1818     secs = etl;
1819
1820     fprintf(stderr, "[%3s %2"PRId64":%02"PRId64":%02"PRId64"] ",
1821             label, hours, mins, secs);
1822   } else {
1823     fprintf(stderr, "[%3s  unknown] ", label);
1824   }
1825 }
1826
1827
1828 int main(int argc, const char **argv_) {
1829   int pass;
1830   vpx_image_t raw;
1831 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1832   vpx_image_t raw_shift;
1833   int allocated_raw_shift = 0;
1834   int use_16bit_internal = 0;
1835   int input_shift = 0;
1836 #endif
1837   int frame_avail, got_data;
1838
1839   struct VpxInputContext input;
1840   struct VpxEncoderConfig global;
1841   struct stream_state *streams = NULL;
1842   char **argv, **argi;
1843   uint64_t cx_time = 0;
1844   int stream_cnt = 0;
1845   int res = 0;
1846
1847   memset(&input, 0, sizeof(input));
1848   exec_name = argv_[0];
1849
1850   if (argc < 3)
1851     usage_exit();
1852
1853   /* Setup default input stream settings */
1854   input.framerate.numerator = 30;
1855   input.framerate.denominator = 1;
1856   input.only_i420 = 1;
1857   input.bit_depth = 0;
1858
1859   /* First parse the global configuration values, because we want to apply
1860    * other parameters on top of the default configuration provided by the
1861    * codec.
1862    */
1863   argv = argv_dup(argc - 1, argv_ + 1);
1864   parse_global_config(&global, argv);
1865
1866   switch (global.color_type) {
1867     case I420:
1868       input.fmt = VPX_IMG_FMT_I420;
1869       break;
1870     case I422:
1871       input.fmt = VPX_IMG_FMT_I422;
1872       break;
1873     case I444:
1874       input.fmt = VPX_IMG_FMT_I444;
1875       break;
1876     case I440:
1877       input.fmt = VPX_IMG_FMT_I440;
1878       break;
1879     case YV12:
1880       input.fmt = VPX_IMG_FMT_YV12;
1881       break;
1882   }
1883
1884   {
1885     /* Now parse each stream's parameters. Using a local scope here
1886      * due to the use of 'stream' as loop variable in FOREACH_STREAM
1887      * loops
1888      */
1889     struct stream_state *stream = NULL;
1890
1891     do {
1892       stream = new_stream(&global, stream);
1893       stream_cnt++;
1894       if (!streams)
1895         streams = stream;
1896     } while (parse_stream_params(&global, stream, argv));
1897   }
1898
1899   /* Check for unrecognized options */
1900   for (argi = argv; *argi; argi++)
1901     if (argi[0][0] == '-' && argi[0][1])
1902       die("Error: Unrecognized option %s\n", *argi);
1903
1904   FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt,
1905                                       &global, &stream->config.cfg););
1906
1907   /* Handle non-option arguments */
1908   input.filename = argv[0];
1909
1910   if (!input.filename)
1911     usage_exit();
1912
1913   /* Decide if other chroma subsamplings than 4:2:0 are supported */
1914   if (global.codec->fourcc == VP9_FOURCC)
1915     input.only_i420 = 0;
1916
1917   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1918     int frames_in = 0, seen_frames = 0;
1919     int64_t estimated_time_left = -1;
1920     int64_t average_rate = -1;
1921     int64_t lagged_count = 0;
1922
1923     open_input_file(&input);
1924
1925     /* If the input file doesn't specify its w/h (raw files), try to get
1926      * the data from the first stream's configuration.
1927      */
1928     if (!input.width || !input.height) {
1929       FOREACH_STREAM({
1930         if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1931           input.width = stream->config.cfg.g_w;
1932           input.height = stream->config.cfg.g_h;
1933           break;
1934         }
1935       });
1936     }
1937
1938     /* Update stream configurations from the input file's parameters */
1939     if (!input.width || !input.height)
1940       fatal("Specify stream dimensions with --width (-w) "
1941             " and --height (-h)");
1942
1943     /* If input file does not specify bit-depth but input-bit-depth parameter
1944      * exists, assume that to be the input bit-depth. However, if the
1945      * input-bit-depth paramter does not exist, assume the input bit-depth
1946      * to be the same as the codec bit-depth.
1947      */
1948     if (!input.bit_depth) {
1949       FOREACH_STREAM({
1950         if (stream->config.cfg.g_input_bit_depth)
1951           input.bit_depth = stream->config.cfg.g_input_bit_depth;
1952         else
1953           input.bit_depth = stream->config.cfg.g_input_bit_depth =
1954               (int)stream->config.cfg.g_bit_depth;
1955       });
1956       if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
1957     } else {
1958       FOREACH_STREAM({
1959         stream->config.cfg.g_input_bit_depth = input.bit_depth;
1960       });
1961     }
1962
1963     FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1964     FOREACH_STREAM(validate_stream_config(stream, &global));
1965
1966     /* Ensure that --passes and --pass are consistent. If --pass is set and
1967      * --passes=2, ensure --fpf was set.
1968      */
1969     if (global.pass && global.passes == 2)
1970       FOREACH_STREAM( {
1971       if (!stream->config.stats_fn)
1972         die("Stream %d: Must specify --fpf when --pass=%d"
1973         " and --passes=2\n", stream->index, global.pass);
1974     });
1975
1976 #if !CONFIG_WEBM_IO
1977     FOREACH_STREAM({
1978       stream->config.write_webm = 0;
1979       warn("vpxenc was compiled without WebM container support."
1980            "Producing IVF output");
1981     });
1982 #endif
1983
1984     /* Use the frame rate from the file only if none was specified
1985      * on the command-line.
1986      */
1987     if (!global.have_framerate) {
1988       global.framerate.num = input.framerate.numerator;
1989       global.framerate.den = input.framerate.denominator;
1990     }
1991
1992     FOREACH_STREAM(set_default_kf_interval(stream, &global));
1993
1994     /* Show configuration */
1995     if (global.verbose && pass == 0)
1996       FOREACH_STREAM(show_stream_config(stream, &global, &input));
1997
1998     if (pass == (global.pass ? global.pass - 1 : 0)) {
1999       if (input.file_type == FILE_TYPE_Y4M)
2000         /*The Y4M reader does its own allocation.
2001           Just initialize this here to avoid problems if we never read any
2002            frames.*/
2003         memset(&raw, 0, sizeof(raw));
2004       else
2005         vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2006
2007       FOREACH_STREAM(stream->rate_hist =
2008                          init_rate_histogram(&stream->config.cfg,
2009                                              &global.framerate));
2010     }
2011
2012     FOREACH_STREAM(setup_pass(stream, &global, pass));
2013     FOREACH_STREAM(open_output_file(stream, &global));
2014     FOREACH_STREAM(initialize_encoder(stream, &global));
2015
2016 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2017     if (strcmp(global.codec->name, "vp9") == 0) {
2018       // Check to see if at least one stream uses 16 bit internal.
2019       // Currently assume that the bit_depths for all streams using
2020       // highbitdepth are the same.
2021       FOREACH_STREAM({
2022         if (stream->config.use_16bit_internal) {
2023           use_16bit_internal = 1;
2024         }
2025         if (stream->config.cfg.g_profile == 0) {
2026           input_shift = 0;
2027         } else {
2028           input_shift = (int)stream->config.cfg.g_bit_depth -
2029               stream->config.cfg.g_input_bit_depth;
2030         }
2031       });
2032     }
2033 #endif
2034
2035     frame_avail = 1;
2036     got_data = 0;
2037
2038     while (frame_avail || got_data) {
2039       struct vpx_usec_timer timer;
2040
2041       if (!global.limit || frames_in < global.limit) {
2042         frame_avail = read_frame(&input, &raw);
2043
2044         if (frame_avail)
2045           frames_in++;
2046         seen_frames = frames_in > global.skip_frames ?
2047                           frames_in - global.skip_frames : 0;
2048
2049         if (!global.quiet) {
2050           float fps = usec_to_fps(cx_time, seen_frames);
2051           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2052
2053           if (stream_cnt == 1)
2054             fprintf(stderr,
2055                     "frame %4d/%-4d %7"PRId64"B ",
2056                     frames_in, streams->frames_out, (int64_t)streams->nbytes);
2057           else
2058             fprintf(stderr, "frame %4d ", frames_in);
2059
2060           fprintf(stderr, "%7"PRId64" %s %.2f %s ",
2061                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
2062                   cx_time > 9999999 ? "ms" : "us",
2063                   fps >= 1.0 ? fps : fps * 60,
2064                   fps >= 1.0 ? "fps" : "fpm");
2065           print_time("ETA", estimated_time_left);
2066         }
2067
2068       } else
2069         frame_avail = 0;
2070
2071       if (frames_in > global.skip_frames) {
2072 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2073         vpx_image_t *frame_to_encode;
2074         if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2075           assert(use_16bit_internal);
2076           // Input bit depth and stream bit depth do not match, so up
2077           // shift frame to stream bit depth
2078           if (!allocated_raw_shift) {
2079             vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2080                           input.width, input.height, 32);
2081             allocated_raw_shift = 1;
2082           }
2083           vpx_img_upshift(&raw_shift, &raw, input_shift);
2084           frame_to_encode = &raw_shift;
2085         } else {
2086           frame_to_encode = &raw;
2087         }
2088         vpx_usec_timer_start(&timer);
2089         if (use_16bit_internal) {
2090           assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2091           FOREACH_STREAM({
2092             if (stream->config.use_16bit_internal)
2093               encode_frame(stream, &global,
2094                            frame_avail ? frame_to_encode : NULL,
2095                            frames_in);
2096             else
2097               assert(0);
2098           });
2099         } else {
2100           assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2101           FOREACH_STREAM(encode_frame(stream, &global,
2102                                       frame_avail ? frame_to_encode : NULL,
2103                                       frames_in));
2104         }
2105 #else
2106         vpx_usec_timer_start(&timer);
2107         FOREACH_STREAM(encode_frame(stream, &global,
2108                                     frame_avail ? &raw : NULL,
2109                                     frames_in));
2110 #endif
2111         vpx_usec_timer_mark(&timer);
2112         cx_time += vpx_usec_timer_elapsed(&timer);
2113
2114         FOREACH_STREAM(update_quantizer_histogram(stream));
2115
2116         got_data = 0;
2117         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2118
2119         if (!got_data && input.length && streams != NULL &&
2120             !streams->frames_out) {
2121           lagged_count = global.limit ? seen_frames : ftello(input.file);
2122         } else if (input.length) {
2123           int64_t remaining;
2124           int64_t rate;
2125
2126           if (global.limit) {
2127             const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2128
2129             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2130             remaining = 1000 * (global.limit - global.skip_frames
2131                                 - seen_frames + lagged_count);
2132           } else {
2133             const int64_t input_pos = ftello(input.file);
2134             const int64_t input_pos_lagged = input_pos - lagged_count;
2135             const int64_t limit = input.length;
2136
2137             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2138             remaining = limit - input_pos + lagged_count;
2139           }
2140
2141           average_rate = (average_rate <= 0)
2142               ? rate
2143               : (average_rate * 7 + rate) / 8;
2144           estimated_time_left = average_rate ? remaining / average_rate : -1;
2145         }
2146
2147         if (got_data && global.test_decode != TEST_DECODE_OFF)
2148           FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2149       }
2150
2151       fflush(stdout);
2152       if (!global.quiet)
2153         fprintf(stderr, "\033[K");
2154     }
2155
2156     if (stream_cnt > 1)
2157       fprintf(stderr, "\n");
2158
2159     if (!global.quiet) {
2160       FOREACH_STREAM(fprintf(stderr,
2161           "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7"PRId64"b/f %7"PRId64"b/s"
2162           " %7"PRId64" %s (%.2f fps)\033[K\n",
2163           pass + 1,
2164           global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2165           seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2166           seen_frames ? (int64_t)stream->nbytes * 8 *
2167               (int64_t)global.framerate.num / global.framerate.den /
2168               seen_frames : 0,
2169           stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2170           stream->cx_time > 9999999 ? "ms" : "us",
2171           usec_to_fps(stream->cx_time, seen_frames)));
2172     }
2173
2174     if (global.show_psnr) {
2175       if (global.codec->fourcc == VP9_FOURCC) {
2176         FOREACH_STREAM(
2177             show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2178       } else {
2179         FOREACH_STREAM(show_psnr(stream, 255.0));
2180       }
2181     }
2182
2183     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2184
2185     if (global.test_decode != TEST_DECODE_OFF) {
2186       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2187     }
2188
2189     close_input_file(&input);
2190
2191     if (global.test_decode == TEST_DECODE_FATAL) {
2192       FOREACH_STREAM(res |= stream->mismatch_seen);
2193     }
2194     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2195
2196     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2197
2198 #if CONFIG_FP_MB_STATS
2199     FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2200 #endif
2201
2202     if (global.pass)
2203       break;
2204   }
2205
2206   if (global.show_q_hist_buckets)
2207     FOREACH_STREAM(show_q_histogram(stream->counts,
2208                                     global.show_q_hist_buckets));
2209
2210   if (global.show_rate_hist_buckets)
2211     FOREACH_STREAM(show_rate_histogram(stream->rate_hist,
2212                                        &stream->config.cfg,
2213                                        global.show_rate_hist_buckets));
2214   FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2215
2216 #if CONFIG_INTERNAL_STATS
2217   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2218    * to match some existing utilities.
2219    */
2220   if (!(global.pass == 1 && global.passes == 2))
2221     FOREACH_STREAM({
2222       FILE *f = fopen("opsnr.stt", "a");
2223       if (stream->mismatch_seen) {
2224         fprintf(f, "First mismatch occurred in frame %d\n",
2225                 stream->mismatch_seen);
2226       } else {
2227         fprintf(f, "No mismatch detected in recon buffers\n");
2228       }
2229       fclose(f);
2230     });
2231 #endif
2232
2233 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2234   if (allocated_raw_shift)
2235     vpx_img_free(&raw_shift);
2236 #endif
2237   vpx_img_free(&raw);
2238   free(argv);
2239   free(streams);
2240   return res ? EXIT_FAILURE : EXIT_SUCCESS;
2241 }