AOMedia Codec SDK
aomenc
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include "apps/aomenc.h"
13 
14 #include "config/aom_config.h"
15 
16 #include <assert.h>
17 #include <limits.h>
18 #include <math.h>
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #if CONFIG_AV1_DECODER
25 #include "aom/aom_decoder.h"
26 #include "aom/aomdx.h"
27 #endif
28 
29 #include "aom/aom_encoder.h"
30 #include "aom/aom_integer.h"
31 #include "aom/aomcx.h"
32 #include "aom_dsp/aom_dsp_common.h"
33 #include "aom_ports/aom_timer.h"
34 #include "aom_ports/mem_ops.h"
35 #include "common/args.h"
36 #include "common/ivfenc.h"
37 #include "common/tools_common.h"
38 #include "common/warnings.h"
39 
40 #if CONFIG_WEBM_IO
41 #include "common/webmenc.h"
42 #endif
43 
44 #include "common/y4minput.h"
45 #include "examples/encoder_util.h"
46 #include "stats/aomstats.h"
47 #include "stats/rate_hist.h"
48 
49 #if CONFIG_LIBYUV
50 #include "third_party/libyuv/include/libyuv/scale.h"
51 #endif
52 
53 /* Swallow warnings about unused results of fread/fwrite */
54 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
55  return fread(ptr, size, nmemb, stream);
56 }
57 #define fread wrap_fread
58 
59 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
60  FILE *stream) {
61  return fwrite(ptr, size, nmemb, stream);
62 }
63 #define fwrite wrap_fwrite
64 
65 static const char *exec_name;
66 
67 static void warn_or_exit_on_errorv(aom_codec_ctx_t *ctx, int fatal,
68  const char *s, va_list ap) {
69  if (ctx->err) {
70  const char *detail = aom_codec_error_detail(ctx);
71 
72  vfprintf(stderr, s, ap);
73  fprintf(stderr, ": %s\n", aom_codec_error(ctx));
74 
75  if (detail) fprintf(stderr, " %s\n", detail);
76 
77  if (fatal) exit(EXIT_FAILURE);
78  }
79 }
80 
81 static void ctx_exit_on_error(aom_codec_ctx_t *ctx, const char *s, ...) {
82  va_list ap;
83 
84  va_start(ap, s);
85  warn_or_exit_on_errorv(ctx, 1, s, ap);
86  va_end(ap);
87 }
88 
89 static void warn_or_exit_on_error(aom_codec_ctx_t *ctx, int fatal,
90  const char *s, ...) {
91  va_list ap;
92 
93  va_start(ap, s);
94  warn_or_exit_on_errorv(ctx, fatal, s, ap);
95  va_end(ap);
96 }
97 
98 static int read_frame(struct AvxInputContext *input_ctx, aom_image_t *img) {
99  FILE *f = input_ctx->file;
100  y4m_input *y4m = &input_ctx->y4m;
101  int shortread = 0;
102 
103  if (input_ctx->file_type == FILE_TYPE_Y4M) {
104  if (y4m_input_fetch_frame(y4m, f, img) < 1) return 0;
105  } else {
106  shortread = read_yuv_frame(input_ctx, img);
107  }
108 
109  return !shortread;
110 }
111 
112 static int file_is_y4m(const char detect[4]) {
113  if (memcmp(detect, "YUV4", 4) == 0) {
114  return 1;
115  }
116  return 0;
117 }
118 
119 static int fourcc_is_ivf(const char detect[4]) {
120  if (memcmp(detect, "DKIF", 4) == 0) {
121  return 1;
122  }
123  return 0;
124 }
125 
126 static const arg_def_t help =
127  ARG_DEF(NULL, "help", 0, "Show usage options and exit");
128 static const arg_def_t debugmode =
129  ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
130 static const arg_def_t outputfile =
131  ARG_DEF("o", "output", 1, "Output filename");
132 static const arg_def_t use_yv12 =
133  ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
134 static const arg_def_t use_i420 =
135  ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
136 static const arg_def_t use_i422 =
137  ARG_DEF(NULL, "i422", 0, "Input file is I422");
138 static const arg_def_t use_i444 =
139  ARG_DEF(NULL, "i444", 0, "Input file is I444");
140 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
141 static const arg_def_t passes =
142  ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
143 static const arg_def_t pass_arg =
144  ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
145 static const arg_def_t fpf_name =
146  ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
147 #if CONFIG_FP_MB_STATS
148 static const arg_def_t fpmbf_name =
149  ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
150 #endif
151 static const arg_def_t limit =
152  ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
153 static const arg_def_t skip =
154  ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
155 static const arg_def_t good_dl =
156  ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
157 static const arg_def_t quietarg =
158  ARG_DEF("q", "quiet", 0, "Do not print encode progress");
159 static const arg_def_t verbosearg =
160  ARG_DEF("v", "verbose", 0, "Show encoder parameters");
161 static const arg_def_t psnrarg =
162  ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
163 #if CONFIG_FILEOPTIONS
164 static const arg_def_t use_cfg = ARG_DEF("c", "cfg", 1, "Config file to use");
165 static const arg_def_t ext_partition =
166  ARG_DEF(NULL, "ext-partition", 1, "corresponds to extended partitions");
167 #endif
168 
169 static const struct arg_enum_list test_decode_enum[] = {
170  { "off", TEST_DECODE_OFF },
171  { "fatal", TEST_DECODE_FATAL },
172  { "warn", TEST_DECODE_WARN },
173  { NULL, 0 }
174 };
175 static const arg_def_t recontest = ARG_DEF_ENUM(
176  NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
177 static const arg_def_t framerate =
178  ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
179 static const arg_def_t use_webm =
180  ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
181 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
182 static const arg_def_t use_obu = ARG_DEF(NULL, "obu", 0, "Output OBU");
183 static const arg_def_t q_hist_n =
184  ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
185 static const arg_def_t rate_hist_n =
186  ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
187 static const arg_def_t disable_warnings =
188  ARG_DEF(NULL, "disable-warnings", 0,
189  "Disable warnings about potentially incorrect encode settings.");
190 static const arg_def_t disable_warning_prompt =
191  ARG_DEF("y", "disable-warning-prompt", 0,
192  "Display warnings, but do not prompt user to continue.");
193 static const struct arg_enum_list bitdepth_enum[] = {
194  { "8", AOM_BITS_8 }, { "10", AOM_BITS_10 }, { "12", AOM_BITS_12 }, { NULL, 0 }
195 };
196 
197 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
198  "b", "bit-depth", 1,
199  "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
200  bitdepth_enum);
201 static const arg_def_t inbitdeptharg =
202  ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
203 
204 static const arg_def_t input_chroma_subsampling_x = ARG_DEF(
205  NULL, "input-chroma-subsampling-x", 1, "chroma subsampling x value.");
206 static const arg_def_t input_chroma_subsampling_y = ARG_DEF(
207  NULL, "input-chroma-subsampling-y", 1, "chroma subsampling y value.");
208 
209 static const arg_def_t *main_args[] = { &help,
210 #if CONFIG_FILEOPTIONS
211  &use_cfg,
212 #endif
213  &debugmode,
214  &outputfile,
215  &codecarg,
216  &passes,
217  &pass_arg,
218  &fpf_name,
219  &limit,
220  &skip,
221  &good_dl,
222  &quietarg,
223  &verbosearg,
224  &psnrarg,
225  &use_webm,
226  &use_ivf,
227  &use_obu,
228  &q_hist_n,
229  &rate_hist_n,
230  &disable_warnings,
231  &disable_warning_prompt,
232  &recontest,
233  NULL };
234 
235 static const arg_def_t usage =
236  ARG_DEF("u", "usage", 1, "Usage profile number to use");
237 static const arg_def_t threads =
238  ARG_DEF("t", "threads", 1, "Max number of threads to use");
239 static const arg_def_t profile =
240  ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
241 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
242 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
243 static const arg_def_t forced_max_frame_width = ARG_DEF(
244  NULL, "forced_max_frame_width", 0, "Maximum frame width value to force");
245 static const arg_def_t forced_max_frame_height = ARG_DEF(
246  NULL, "forced_max_frame_height", 0, "Maximum frame height value to force");
247 #if CONFIG_WEBM_IO
248 static const struct arg_enum_list stereo_mode_enum[] = {
249  { "mono", STEREO_FORMAT_MONO },
250  { "left-right", STEREO_FORMAT_LEFT_RIGHT },
251  { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
252  { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
253  { "right-left", STEREO_FORMAT_RIGHT_LEFT },
254  { NULL, 0 }
255 };
256 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
257  NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
258 #endif
259 static const arg_def_t timebase = ARG_DEF(
260  NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
261 static const arg_def_t global_error_resilient =
262  ARG_DEF(NULL, "global-error-resilient", 1,
263  "Enable global error resiliency features");
264 static const arg_def_t lag_in_frames =
265  ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
266 static const arg_def_t large_scale_tile =
267  ARG_DEF(NULL, "large-scale-tile", 1,
268  "Large scale tile coding (0: off (default), 1: on)");
269 static const arg_def_t monochrome =
270  ARG_DEF(NULL, "monochrome", 0, "Monochrome video (no chroma planes)");
271 static const arg_def_t full_still_picture_hdr = ARG_DEF(
272  NULL, "full-still-picture-hdr", 0, "Use full header for still picture");
273 
274 static const arg_def_t *global_args[] = { &use_yv12,
275  &use_i420,
276  &use_i422,
277  &use_i444,
278  &usage,
279  &threads,
280  &profile,
281  &width,
282  &height,
283  &forced_max_frame_width,
284  &forced_max_frame_height,
285 #if CONFIG_WEBM_IO
286  &stereo_mode,
287 #endif
288  &timebase,
289  &framerate,
290  &global_error_resilient,
291  &bitdeptharg,
292  &lag_in_frames,
293  &large_scale_tile,
294  &monochrome,
295  &full_still_picture_hdr,
296  NULL };
297 
298 static const arg_def_t dropframe_thresh =
299  ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
300 static const arg_def_t resize_mode =
301  ARG_DEF(NULL, "resize-mode", 1, "Frame resize mode");
302 static const arg_def_t resize_denominator =
303  ARG_DEF(NULL, "resize-denominator", 1, "Frame resize denominator");
304 static const arg_def_t resize_kf_denominator = ARG_DEF(
305  NULL, "resize-kf-denominator", 1, "Frame resize keyframe denominator");
306 static const arg_def_t superres_mode =
307  ARG_DEF(NULL, "superres-mode", 1, "Frame super-resolution mode");
308 static const arg_def_t superres_denominator = ARG_DEF(
309  NULL, "superres-denominator", 1, "Frame super-resolution denominator");
310 static const arg_def_t superres_kf_denominator =
311  ARG_DEF(NULL, "superres-kf-denominator", 1,
312  "Frame super-resolution keyframe denominator");
313 static const arg_def_t superres_qthresh = ARG_DEF(
314  NULL, "superres-qthresh", 1, "Frame super-resolution qindex threshold");
315 static const arg_def_t superres_kf_qthresh =
316  ARG_DEF(NULL, "superres-kf-qthresh", 1,
317  "Frame super-resolution keyframe qindex threshold");
318 static const struct arg_enum_list end_usage_enum[] = { { "vbr", AOM_VBR },
319  { "cbr", AOM_CBR },
320  { "cq", AOM_CQ },
321  { "q", AOM_Q },
322  { NULL, 0 } };
323 static const arg_def_t end_usage =
324  ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
325 static const arg_def_t target_bitrate =
326  ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
327 static const arg_def_t min_quantizer =
328  ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
329 static const arg_def_t max_quantizer =
330  ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
331 static const arg_def_t undershoot_pct =
332  ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
333 static const arg_def_t overshoot_pct =
334  ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
335 static const arg_def_t buf_sz =
336  ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
337 static const arg_def_t buf_initial_sz =
338  ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
339 static const arg_def_t buf_optimal_sz =
340  ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
341 static const arg_def_t *rc_args[] = { &dropframe_thresh,
342  &resize_mode,
343  &resize_denominator,
344  &resize_kf_denominator,
345  &superres_mode,
346  &superres_denominator,
347  &superres_kf_denominator,
348  &superres_qthresh,
349  &superres_kf_qthresh,
350  &end_usage,
351  &target_bitrate,
352  &min_quantizer,
353  &max_quantizer,
354  &undershoot_pct,
355  &overshoot_pct,
356  &buf_sz,
357  &buf_initial_sz,
358  &buf_optimal_sz,
359  NULL };
360 
361 static const arg_def_t bias_pct =
362  ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
363 static const arg_def_t minsection_pct =
364  ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
365 static const arg_def_t maxsection_pct =
366  ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
367 static const arg_def_t *rc_twopass_args[] = { &bias_pct, &minsection_pct,
368  &maxsection_pct, NULL };
369 static const arg_def_t fwd_kf_enabled =
370  ARG_DEF(NULL, "enable-fwd-kf", 1, "Enable forward reference keyframes");
371 static const arg_def_t kf_min_dist =
372  ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
373 static const arg_def_t kf_max_dist =
374  ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
375 static const arg_def_t kf_disabled =
376  ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
377 static const arg_def_t *kf_args[] = { &fwd_kf_enabled, &kf_min_dist,
378  &kf_max_dist, &kf_disabled, NULL };
379 static const arg_def_t sframe_dist =
380  ARG_DEF(NULL, "sframe-dist", 1, "S-Frame interval (frames)");
381 static const arg_def_t sframe_mode =
382  ARG_DEF(NULL, "sframe-mode", 1, "S-Frame insertion mode (1..2)");
383 static const arg_def_t save_as_annexb =
384  ARG_DEF(NULL, "annexb", 1, "Save as Annex-B");
385 static const arg_def_t noise_sens =
386  ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
387 static const arg_def_t sharpness =
388  ARG_DEF(NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
389 static const arg_def_t static_thresh =
390  ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
391 static const arg_def_t auto_altref =
392  ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
393 static const arg_def_t arnr_maxframes =
394  ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
395 static const arg_def_t arnr_strength =
396  ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
397 static const struct arg_enum_list tuning_enum[] = {
398  { "psnr", AOM_TUNE_PSNR },
399  { "ssim", AOM_TUNE_SSIM },
400 #ifdef CONFIG_DIST_8X8
401  { "cdef-dist", AOM_TUNE_CDEF_DIST },
402  { "daala-dist", AOM_TUNE_DAALA_DIST },
403 #endif
404  { NULL, 0 }
405 };
406 static const arg_def_t tune_metric =
407  ARG_DEF_ENUM(NULL, "tune", 1, "Distortion metric tuned with", tuning_enum);
408 static const arg_def_t cq_level =
409  ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
410 static const arg_def_t max_intra_rate_pct =
411  ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
412 
413 #if CONFIG_AV1_ENCODER
414 static const arg_def_t cpu_used_av1 =
415  ARG_DEF(NULL, "cpu-used", 1, "CPU Used (0..8)");
416 static const arg_def_t rowmtarg =
417  ARG_DEF(NULL, "row-mt", 1,
418  "Enable row based multi-threading (0: off (default), 1: on)");
419 static const arg_def_t tile_cols =
420  ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
421 static const arg_def_t tile_rows =
422  ARG_DEF(NULL, "tile-rows", 1, "Number of tile rows to use, log2");
423 static const arg_def_t tile_width =
424  ARG_DEF(NULL, "tile-width", 1, "Tile widths (comma separated)");
425 static const arg_def_t tile_height =
426  ARG_DEF(NULL, "tile-height", 1, "Tile heights (command separated)");
427 static const arg_def_t lossless =
428  ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
429 static const arg_def_t enable_cdef =
430  ARG_DEF(NULL, "enable-cdef", 1,
431  "Enable the constrained directional enhancement filter (0: false, "
432  "1: true (default))");
433 static const arg_def_t enable_restoration =
434  ARG_DEF(NULL, "enable-restoration", 1,
435  "Enable the loop restoration filter (0: false, "
436  "1: true (default))");
437 static const arg_def_t disable_trellis_quant =
438  ARG_DEF(NULL, "disable-trellis-quant", 1,
439  "Disable trellis optimization of quantized coefficients (0: false ("
440  "default) 1: true)");
441 static const arg_def_t enable_qm =
442  ARG_DEF(NULL, "enable-qm", 1,
443  "Enable quantisation matrices (0: false (default), 1: true)");
444 static const arg_def_t qm_min = ARG_DEF(
445  NULL, "qm-min", 1, "Min quant matrix flatness (0..15), default is 8");
446 static const arg_def_t qm_max = ARG_DEF(
447  NULL, "qm-max", 1, "Max quant matrix flatness (0..15), default is 15");
448 #if CONFIG_DIST_8X8
449 static const arg_def_t enable_dist_8x8 =
450  ARG_DEF(NULL, "enable-dist-8x8", 1,
451  "Enable dist-8x8 (0: false (default), 1: true)");
452 #endif // CONFIG_DIST_8X8
453 static const arg_def_t num_tg = ARG_DEF(
454  NULL, "num-tile-groups", 1, "Maximum number of tile groups, default is 1");
455 static const arg_def_t mtu_size =
456  ARG_DEF(NULL, "mtu-size", 1,
457  "MTU size for a tile group, default is 0 (no MTU targeting), "
458  "overrides maximum number of tile groups");
459 static const struct arg_enum_list timing_info_enum[] = {
460  { "unspecified", AOM_TIMING_UNSPECIFIED },
461  { "constant", AOM_TIMING_EQUAL },
462  { "model", AOM_TIMING_DEC_MODEL },
463  { NULL, 0 }
464 };
465 static const arg_def_t timing_info =
466  ARG_DEF_ENUM(NULL, "timing-info", 1,
467  "Signal timing info in the bitstream (model unly works for no "
468  "hidden frames, no super-res yet):",
469  timing_info_enum);
470 static const arg_def_t film_grain_test =
471  ARG_DEF(NULL, "film-grain-test", 1,
472  "Film grain test vectors (0: none (default), 1: test-1 2: test-2, "
473  "... 16: test-16)");
474 static const arg_def_t film_grain_table =
475  ARG_DEF(NULL, "film-grain-table", 1,
476  "Path to file containing film grain parameters");
477 #if CONFIG_DENOISE
478 static const arg_def_t denoise_noise_level =
479  ARG_DEF(NULL, "denoise-noise-level", 1,
480  "Amount of noise (from 0 = don't denoise, to 50)");
481 static const arg_def_t denoise_block_size =
482  ARG_DEF(NULL, "denoise-block-size", 1, "Denoise block size (default = 32)");
483 #endif
484 static const arg_def_t enable_ref_frame_mvs =
485  ARG_DEF(NULL, "enable-ref-frame-mvs", 1,
486  "Enable temporal mv prediction (default is 1)");
487 static const arg_def_t frame_parallel_decoding =
488  ARG_DEF(NULL, "frame-parallel", 1,
489  "Enable frame parallel decodability features "
490  "(0: false (default), 1: true)");
491 static const arg_def_t error_resilient_mode =
492  ARG_DEF(NULL, "error-resilient", 1,
493  "Enable error resilient features "
494  "(0: false (default), 1: true)");
495 static const arg_def_t aq_mode = ARG_DEF(
496  NULL, "aq-mode", 1,
497  "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
498  "3: cyclic refresh)");
499 static const arg_def_t deltaq_mode = ARG_DEF(
500  NULL, "deltaq-mode", 1,
501  "Delta qindex mode (0: off (default), 1: deltaq 2: deltaq + deltalf)");
502 static const arg_def_t frame_periodic_boost =
503  ARG_DEF(NULL, "frame-boost", 1,
504  "Enable frame periodic boost (0: off (default), 1: on)");
505 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
506  NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
507 static const arg_def_t max_inter_rate_pct =
508  ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
509 static const arg_def_t min_gf_interval = ARG_DEF(
510  NULL, "min-gf-interval", 1,
511  "min gf/arf frame interval (default 0, indicating in-built behavior)");
512 static const arg_def_t max_gf_interval = ARG_DEF(
513  NULL, "max-gf-interval", 1,
514  "max gf/arf frame interval (default 0, indicating in-built behavior)");
515 
516 static const struct arg_enum_list color_primaries_enum[] = {
517  { "bt709", AOM_CICP_CP_BT_709 },
518  { "unspecified", AOM_CICP_CP_UNSPECIFIED },
519  { "bt601", AOM_CICP_CP_BT_601 },
520  { "bt470m", AOM_CICP_CP_BT_470_M },
521  { "bt470bg", AOM_CICP_CP_BT_470_B_G },
522  { "smpte240", AOM_CICP_CP_SMPTE_240 },
523  { "film", AOM_CICP_CP_GENERIC_FILM },
524  { "bt2020", AOM_CICP_CP_BT_2020 },
525  { "xyz", AOM_CICP_CP_XYZ },
526  { "smpte431", AOM_CICP_CP_SMPTE_431 },
527  { "smpte432", AOM_CICP_CP_SMPTE_432 },
528  { "ebu3213", AOM_CICP_CP_EBU_3213 },
529  { NULL, 0 }
530 };
531 
532 static const arg_def_t input_color_primaries = ARG_DEF_ENUM(
533  NULL, "color-primaries", 1,
534  "Color primaries (CICP) of input content:", color_primaries_enum);
535 
536 static const struct arg_enum_list transfer_characteristics_enum[] = {
537  { "unspecified", AOM_CICP_CP_UNSPECIFIED },
538  { "bt709", AOM_CICP_TC_BT_709 },
539  { "bt470m", AOM_CICP_TC_BT_470_M },
540  { "bt470bg", AOM_CICP_TC_BT_470_B_G },
541  { "bt601", AOM_CICP_TC_BT_601 },
542  { "smpte240", AOM_CICP_TC_SMPTE_240 },
543  { "lin", AOM_CICP_TC_LINEAR },
544  { "log100", AOM_CICP_TC_LOG_100 },
545  { "log100sq10", AOM_CICP_TC_LOG_100_SQRT10 },
546  { "iec61966", AOM_CICP_TC_IEC_61966 },
547  { "bt1361", AOM_CICP_TC_BT_1361 },
548  { "srgb", AOM_CICP_TC_SRGB },
549  { "bt2020-10bit", AOM_CICP_TC_BT_2020_10_BIT },
550  { "bt2020-12bit", AOM_CICP_TC_BT_2020_12_BIT },
551  { "smpte2084", AOM_CICP_TC_SMPTE_2084 },
552  { "hlg", AOM_CICP_TC_HLG },
553  { "smpte428", AOM_CICP_TC_SMPTE_428 },
554  { NULL, 0 }
555 };
556 
557 static const arg_def_t input_transfer_characteristics =
558  ARG_DEF_ENUM(NULL, "transfer-characteristics", 1,
559  "Transfer characteristics (CICP) of input content:",
560  transfer_characteristics_enum);
561 
562 static const struct arg_enum_list matrix_coefficients_enum[] = {
563  { "identity", AOM_CICP_MC_IDENTITY },
564  { "bt709", AOM_CICP_MC_BT_709 },
565  { "unspecified", AOM_CICP_MC_UNSPECIFIED },
566  { "fcc73", AOM_CICP_MC_FCC },
567  { "bt470bg", AOM_CICP_MC_BT_470_B_G },
568  { "bt601", AOM_CICP_MC_BT_601 },
569  { "smpte240", AOM_CICP_CP_SMPTE_240 },
570  { "ycgco", AOM_CICP_MC_SMPTE_YCGCO },
571  { "bt2020ncl", AOM_CICP_MC_BT_2020_NCL },
572  { "bt2020cl", AOM_CICP_MC_BT_2020_CL },
573  { "smpte2085", AOM_CICP_MC_SMPTE_2085 },
574  { "chromncl", AOM_CICP_MC_CHROMAT_NCL },
575  { "chromcl", AOM_CICP_MC_CHROMAT_CL },
576  { "ictcp", AOM_CICP_MC_ICTCP },
577  { NULL, 0 }
578 };
579 
580 static const arg_def_t input_matrix_coefficients = ARG_DEF_ENUM(
581  NULL, "matrix-coefficients", 1,
582  "Matrix coefficients (CICP) of input content:", matrix_coefficients_enum);
583 
584 static const struct arg_enum_list chroma_sample_position_enum[] = {
585  { "unknown", AOM_CSP_UNKNOWN },
586  { "vertical", AOM_CSP_VERTICAL },
587  { "colocated", AOM_CSP_COLOCATED },
588  { NULL, 0 }
589 };
590 
591 static const arg_def_t input_chroma_sample_position =
592  ARG_DEF_ENUM(NULL, "chroma-sample-position", 1,
593  "The chroma sample position when chroma 4:2:0 is signaled:",
594  chroma_sample_position_enum);
595 
596 static const struct arg_enum_list tune_content_enum[] = {
597  { "default", AOM_CONTENT_DEFAULT },
598  { "screen", AOM_CONTENT_SCREEN },
599  { NULL, 0 }
600 };
601 
602 static const arg_def_t tune_content = ARG_DEF_ENUM(
603  NULL, "tune-content", 1, "Tune content type", tune_content_enum);
604 
605 static const arg_def_t cdf_update_mode =
606  ARG_DEF(NULL, "cdf-update-mode", 1,
607  "CDF update mode for entropy coding "
608  "(0: no CDF update; 1: update CDF on all frames(default); "
609  "2: selectively update CDF on some frames");
610 
611 static const struct arg_enum_list superblock_size_enum[] = {
612  { "dynamic", AOM_SUPERBLOCK_SIZE_DYNAMIC },
613  { "64", AOM_SUPERBLOCK_SIZE_64X64 },
614  { "128", AOM_SUPERBLOCK_SIZE_128X128 },
615  { NULL, 0 }
616 };
617 static const arg_def_t superblock_size = ARG_DEF_ENUM(
618  NULL, "sb-size", 1, "Superblock size to use", superblock_size_enum);
619 
620 static const arg_def_t *av1_args[] = { &cpu_used_av1,
621  &auto_altref,
622  &sharpness,
623  &static_thresh,
624  &rowmtarg,
625  &tile_cols,
626  &tile_rows,
627  &arnr_maxframes,
628  &arnr_strength,
629  &tune_metric,
630  &cq_level,
631  &max_intra_rate_pct,
632  &max_inter_rate_pct,
633  &gf_cbr_boost_pct,
634  &lossless,
635  &enable_cdef,
636  &enable_restoration,
637  &disable_trellis_quant,
638  &enable_qm,
639  &qm_min,
640  &qm_max,
641 #if CONFIG_DIST_8X8
642  &enable_dist_8x8,
643 #endif
644  &frame_parallel_decoding,
645  &error_resilient_mode,
646  &aq_mode,
647  &deltaq_mode,
648  &frame_periodic_boost,
649  &noise_sens,
650  &tune_content,
651  &cdf_update_mode,
652  &input_color_primaries,
653  &input_transfer_characteristics,
654  &input_matrix_coefficients,
655  &input_chroma_sample_position,
656  &min_gf_interval,
657  &max_gf_interval,
658  &superblock_size,
659  &num_tg,
660  &mtu_size,
661  &timing_info,
662  &film_grain_test,
663  &film_grain_table,
664 #if CONFIG_DENOISE
665  &denoise_noise_level,
666  &denoise_block_size,
667 #endif
668  &enable_ref_frame_mvs,
669  &bitdeptharg,
670  &inbitdeptharg,
671  &input_chroma_subsampling_x,
672  &input_chroma_subsampling_y,
673  &sframe_dist,
674  &sframe_mode,
675  &save_as_annexb,
676  NULL };
677 static const int av1_arg_ctrl_map[] = { AOME_SET_CPUUSED,
698 #if CONFIG_DIST_8X8
700 #endif
717  AV1E_SET_MTU,
721 #if CONFIG_DENOISE
724 #endif
730  0 };
731 #endif // CONFIG_AV1_ENCODER
732 
733 static const arg_def_t *no_args[] = { NULL };
734 
735 static void show_help(FILE *fout, int shorthelp) {
736  fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
737  exec_name);
738 
739  if (shorthelp) {
740  fprintf(fout, "Use --help to see the full list of options.\n");
741  return;
742  }
743 
744  fprintf(fout, "\nOptions:\n");
745  arg_show_usage(fout, main_args);
746  fprintf(fout, "\nEncoder Global Options:\n");
747  arg_show_usage(fout, global_args);
748  fprintf(fout, "\nRate Control Options:\n");
749  arg_show_usage(fout, rc_args);
750  fprintf(fout, "\nTwopass Rate Control Options:\n");
751  arg_show_usage(fout, rc_twopass_args);
752  fprintf(fout, "\nKeyframe Placement Options:\n");
753  arg_show_usage(fout, kf_args);
754 #if CONFIG_AV1_ENCODER
755  fprintf(fout, "\nAV1 Specific Options:\n");
756  arg_show_usage(fout, av1_args);
757 #endif
758  fprintf(fout,
759  "\nStream timebase (--timebase):\n"
760  " The desired precision of timestamps in the output, expressed\n"
761  " in fractional seconds. Default is 1/1000.\n");
762  fprintf(fout, "\nIncluded encoders:\n\n");
763 
764  const int num_encoder = get_aom_encoder_count();
765  for (int i = 0; i < num_encoder; ++i) {
766  const AvxInterface *const encoder = get_aom_encoder_by_index(i);
767  const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
768  fprintf(fout, " %-6s - %s %s\n", encoder->name,
769  aom_codec_iface_name(encoder->codec_interface()), defstr);
770  }
771  fprintf(fout, "\n ");
772  fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
773 }
774 
775 void usage_exit(void) {
776  show_help(stderr, 1);
777  exit(EXIT_FAILURE);
778 }
779 
780 #if CONFIG_AV1_ENCODER
781 #define ARG_CTRL_CNT_MAX NELEMENTS(av1_arg_ctrl_map)
782 #endif
783 
784 #if !CONFIG_WEBM_IO
785 typedef int stereo_format_t;
786 struct WebmOutputContext {
787  int debug;
788 };
789 #endif
790 
791 /* Per-stream configuration */
792 struct stream_config {
793  struct aom_codec_enc_cfg cfg;
794  const char *out_fn;
795  const char *stats_fn;
796 #if CONFIG_FP_MB_STATS
797  const char *fpmb_stats_fn;
798 #endif
799  stereo_format_t stereo_fmt;
800  int arg_ctrls[ARG_CTRL_CNT_MAX][2];
801  int arg_ctrl_cnt;
802  int write_webm;
803  const char *film_grain_filename;
804  int write_ivf;
805  // whether to use 16bit internal buffers
806  int use_16bit_internal;
807 };
808 
809 struct stream_state {
810  int index;
811  struct stream_state *next;
812  struct stream_config config;
813  FILE *file;
814  struct rate_hist *rate_hist;
815  struct WebmOutputContext webm_ctx;
816  uint64_t psnr_sse_total;
817  uint64_t psnr_samples_total;
818  double psnr_totals[4];
819  int psnr_count;
820  int counts[64];
821  aom_codec_ctx_t encoder;
822  unsigned int frames_out;
823  uint64_t cx_time;
824  size_t nbytes;
825  stats_io_t stats;
826 #if CONFIG_FP_MB_STATS
827  stats_io_t fpmb_stats;
828 #endif
829  struct aom_image *img;
830  aom_codec_ctx_t decoder;
831  int mismatch_seen;
832  unsigned int chroma_subsampling_x;
833  unsigned int chroma_subsampling_y;
834 };
835 
836 static void validate_positive_rational(const char *msg,
837  struct aom_rational *rat) {
838  if (rat->den < 0) {
839  rat->num *= -1;
840  rat->den *= -1;
841  }
842 
843  if (rat->num < 0) die("Error: %s must be positive\n", msg);
844 
845  if (!rat->den) die("Error: %s has zero denominator\n", msg);
846 }
847 
848 /* Parses global config arguments into the AvxEncoderConfig. Note that
849  * argv is modified and overwrites all parsed arguments.
850  */
851 static void parse_global_config(struct AvxEncoderConfig *global, int argc,
852  char ***argv) {
853  char **argi, **argj;
854  struct arg arg;
855  const int num_encoder = get_aom_encoder_count();
856  char **argv_local = (char **)*argv;
857 #if CONFIG_FILEOPTIONS
858  int argc_local = argc;
859 #endif
860  if (num_encoder < 1) die("Error: no valid encoder available\n");
861 
862  /* Initialize default parameters */
863  memset(global, 0, sizeof(*global));
864  global->codec = get_aom_encoder_by_index(num_encoder - 1);
865  global->passes = 0;
866  global->color_type = I420;
867  global->csp = AOM_CSP_UNKNOWN;
868 
869 #if CONFIG_FILEOPTIONS
870  const char *cfg = NULL;
871  int cfg_included = 0;
872 #endif
873  for (argi = argj = argv_local; (*argj = *argi); argi += arg.argv_step) {
874  arg.argv_step = 1;
875 
876 #if CONFIG_FILEOPTIONS
877  if (arg_match(&arg, &use_cfg, argi)) {
878  if (cfg_included) continue;
879  cfg = arg.val;
880 
881  arg_cfg(&argc_local, &argv_local, cfg);
882 
883  *argj = *argi = *argv_local;
884  argj = argi = argv_local;
885  *argv = argv_local;
886  cfg_included = 1;
887  continue;
888  }
889 #endif
890  if (arg_match(&arg, &help, argi)) {
891  show_help(stdout, 0);
892  exit(EXIT_SUCCESS);
893  } else if (arg_match(&arg, &codecarg, argi)) {
894  global->codec = get_aom_encoder_by_name(arg.val);
895  if (!global->codec)
896  die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
897  } else if (arg_match(&arg, &passes, argi)) {
898  global->passes = arg_parse_uint(&arg);
899 
900  if (global->passes < 1 || global->passes > 2)
901  die("Error: Invalid number of passes (%d)\n", global->passes);
902  } else if (arg_match(&arg, &pass_arg, argi)) {
903  global->pass = arg_parse_uint(&arg);
904 
905  if (global->pass < 1 || global->pass > 2)
906  die("Error: Invalid pass selected (%d)\n", global->pass);
907  } else if (arg_match(&arg, &input_chroma_sample_position, argi)) {
908  global->csp = arg_parse_enum(&arg);
909  /* Flag is used by later code as well, preserve it. */
910  argj++;
911  } else if (arg_match(&arg, &usage, argi))
912  global->usage = arg_parse_uint(&arg);
913  else if (arg_match(&arg, &good_dl, argi))
914  warn("Deprecated --good option! Ignoring\n");
915  else if (arg_match(&arg, &use_yv12, argi))
916  global->color_type = YV12;
917  else if (arg_match(&arg, &use_i420, argi))
918  global->color_type = I420;
919  else if (arg_match(&arg, &use_i422, argi))
920  global->color_type = I422;
921  else if (arg_match(&arg, &use_i444, argi))
922  global->color_type = I444;
923  else if (arg_match(&arg, &quietarg, argi))
924  global->quiet = 1;
925  else if (arg_match(&arg, &verbosearg, argi))
926  global->verbose = 1;
927  else if (arg_match(&arg, &limit, argi))
928  global->limit = arg_parse_uint(&arg);
929  else if (arg_match(&arg, &skip, argi))
930  global->skip_frames = arg_parse_uint(&arg);
931  else if (arg_match(&arg, &psnrarg, argi))
932  global->show_psnr = 1;
933  else if (arg_match(&arg, &recontest, argi))
934  global->test_decode = arg_parse_enum_or_int(&arg);
935  else if (arg_match(&arg, &framerate, argi)) {
936  global->framerate = arg_parse_rational(&arg);
937  validate_positive_rational(arg.name, &global->framerate);
938  global->have_framerate = 1;
939  } else if (arg_match(&arg, &debugmode, argi))
940  global->debug = 1;
941  else if (arg_match(&arg, &q_hist_n, argi))
942  global->show_q_hist_buckets = arg_parse_uint(&arg);
943  else if (arg_match(&arg, &rate_hist_n, argi))
944  global->show_rate_hist_buckets = arg_parse_uint(&arg);
945  else if (arg_match(&arg, &disable_warnings, argi))
946  global->disable_warnings = 1;
947  else if (arg_match(&arg, &disable_warning_prompt, argi))
948  global->disable_warning_prompt = 1;
949  else
950  argj++;
951  }
952 
953  if (global->pass) {
954  /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
955  if (global->pass > global->passes) {
956  warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
957  global->pass);
958  global->passes = global->pass;
959  }
960  }
961  /* Validate global config */
962  if (global->passes == 0) {
963 #if CONFIG_AV1_ENCODER
964  // Make default AV1 passes = 2 until there is a better quality 1-pass
965  // encoder
966  if (global->codec != NULL && global->codec->name != NULL)
967  global->passes = (strcmp(global->codec->name, "av1") == 0) ? 2 : 1;
968 #else
969  global->passes = 1;
970 #endif
971  }
972 }
973 
974 static void open_input_file(struct AvxInputContext *input,
976  /* Parse certain options from the input file, if possible */
977  input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
978  : set_binary_mode(stdin);
979 
980  if (!input->file) fatal("Failed to open input file");
981 
982  if (!fseeko(input->file, 0, SEEK_END)) {
983  /* Input file is seekable. Figure out how long it is, so we can get
984  * progress info.
985  */
986  input->length = ftello(input->file);
987  rewind(input->file);
988  }
989 
990  /* Default to 1:1 pixel aspect ratio. */
991  input->pixel_aspect_ratio.numerator = 1;
992  input->pixel_aspect_ratio.denominator = 1;
993 
994  /* For RAW input sources, these bytes will applied on the first frame
995  * in read_frame().
996  */
997  input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
998  input->detect.position = 0;
999 
1000  if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
1001  if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4, csp,
1002  input->only_i420) >= 0) {
1003  input->file_type = FILE_TYPE_Y4M;
1004  input->width = input->y4m.pic_w;
1005  input->height = input->y4m.pic_h;
1006  input->pixel_aspect_ratio.numerator = input->y4m.par_n;
1007  input->pixel_aspect_ratio.denominator = input->y4m.par_d;
1008  input->framerate.numerator = input->y4m.fps_n;
1009  input->framerate.denominator = input->y4m.fps_d;
1010  input->fmt = input->y4m.aom_fmt;
1011  input->bit_depth = input->y4m.bit_depth;
1012  } else
1013  fatal("Unsupported Y4M stream.");
1014  } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
1015  fatal("IVF is not supported as input.");
1016  } else {
1017  input->file_type = FILE_TYPE_RAW;
1018  }
1019 }
1020 
1021 static void close_input_file(struct AvxInputContext *input) {
1022  fclose(input->file);
1023  if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
1024 }
1025 
1026 static struct stream_state *new_stream(struct AvxEncoderConfig *global,
1027  struct stream_state *prev) {
1028  struct stream_state *stream;
1029 
1030  stream = calloc(1, sizeof(*stream));
1031  if (stream == NULL) {
1032  fatal("Failed to allocate new stream.");
1033  }
1034 
1035  if (prev) {
1036  memcpy(stream, prev, sizeof(*stream));
1037  stream->index++;
1038  prev->next = stream;
1039  } else {
1040  aom_codec_err_t res;
1041 
1042  /* Populate encoder configuration */
1043  res = aom_codec_enc_config_default(global->codec->codec_interface(),
1044  &stream->config.cfg, global->usage);
1045  if (res) fatal("Failed to get config: %s\n", aom_codec_err_to_string(res));
1046 
1047  /* Change the default timebase to a high enough value so that the
1048  * encoder will always create strictly increasing timestamps.
1049  */
1050  stream->config.cfg.g_timebase.den = 1000;
1051 
1052  /* Never use the library's default resolution, require it be parsed
1053  * from the file or set on the command line.
1054  */
1055  stream->config.cfg.g_w = 0;
1056  stream->config.cfg.g_h = 0;
1057 
1058  /* Initialize remaining stream parameters */
1059  stream->config.write_webm = 1;
1060  stream->config.write_ivf = 0;
1061 
1062 #if CONFIG_WEBM_IO
1063  stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1064  stream->webm_ctx.last_pts_ns = -1;
1065  stream->webm_ctx.writer = NULL;
1066  stream->webm_ctx.segment = NULL;
1067 #endif
1068 
1069  /* Allows removal of the application version from the EBML tags */
1070  stream->webm_ctx.debug = global->debug;
1071  }
1072 
1073  /* Output files must be specified for each stream */
1074  stream->config.out_fn = NULL;
1075 
1076  stream->next = NULL;
1077  return stream;
1078 }
1079 
1080 static void set_config_arg_ctrls(struct stream_config *config, int key,
1081  const struct arg *arg) {
1082  int j;
1083  if (key == AV1E_SET_FILM_GRAIN_TABLE) {
1084  config->film_grain_filename = arg->val;
1085  return;
1086  }
1087 
1088  /* Point either to the next free element or the first instance of this
1089  * control.
1090  */
1091  for (j = 0; j < config->arg_ctrl_cnt; j++)
1092  if (config->arg_ctrls[j][0] == key) break;
1093 
1094  /* Update/insert */
1095  assert(j < (int)ARG_CTRL_CNT_MAX);
1096  config->arg_ctrls[j][0] = key;
1097  config->arg_ctrls[j][1] = arg_parse_enum_or_int(arg);
1098 
1099  if (key == AOME_SET_ENABLEAUTOALTREF && config->arg_ctrls[j][1] > 1) {
1100  warn("auto-alt-ref > 1 is deprecated... setting auto-alt-ref=1\n");
1101  config->arg_ctrls[j][1] = 1;
1102  }
1103  if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1104 }
1105 
1106 static int parse_stream_params(struct AvxEncoderConfig *global,
1107  struct stream_state *stream, char **argv) {
1108  char **argi, **argj;
1109  struct arg arg;
1110  static const arg_def_t **ctrl_args = no_args;
1111  static const int *ctrl_args_map = NULL;
1112  struct stream_config *config = &stream->config;
1113  int eos_mark_found = 0;
1114  int webm_forced = 0;
1115 
1116  // Handle codec specific options
1117  if (0) {
1118 #if CONFIG_AV1_ENCODER
1119  } else if (strcmp(global->codec->name, "av1") == 0) {
1120  // TODO(jingning): Reuse AV1 specific encoder configuration parameters.
1121  // Consider to expand this set for AV1 encoder control.
1122  ctrl_args = av1_args;
1123  ctrl_args_map = av1_arg_ctrl_map;
1124 #endif
1125  }
1126 
1127  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1128  arg.argv_step = 1;
1129 
1130  /* Once we've found an end-of-stream marker (--) we want to continue
1131  * shifting arguments but not consuming them.
1132  */
1133  if (eos_mark_found) {
1134  argj++;
1135  continue;
1136  } else if (!strcmp(*argj, "--")) {
1137  eos_mark_found = 1;
1138  continue;
1139  }
1140 
1141  if (arg_match(&arg, &outputfile, argi)) {
1142  config->out_fn = arg.val;
1143  if (!webm_forced) {
1144  const size_t out_fn_len = strlen(config->out_fn);
1145  if (out_fn_len >= 4 &&
1146  !strcmp(config->out_fn + out_fn_len - 4, ".ivf")) {
1147  config->write_webm = 0;
1148  config->write_ivf = 1;
1149  } else if (out_fn_len >= 4 &&
1150  !strcmp(config->out_fn + out_fn_len - 4, ".obu")) {
1151  config->write_webm = 0;
1152  config->write_ivf = 0;
1153  }
1154  }
1155  } else if (arg_match(&arg, &fpf_name, argi)) {
1156  config->stats_fn = arg.val;
1157 #if CONFIG_FP_MB_STATS
1158  } else if (arg_match(&arg, &fpmbf_name, argi)) {
1159  config->fpmb_stats_fn = arg.val;
1160 #endif
1161  } else if (arg_match(&arg, &use_webm, argi)) {
1162 #if CONFIG_WEBM_IO
1163  config->write_webm = 1;
1164  webm_forced = 1;
1165 #else
1166  die("Error: --webm specified but webm is disabled.");
1167 #endif
1168  } else if (arg_match(&arg, &use_ivf, argi)) {
1169  config->write_webm = 0;
1170  config->write_ivf = 1;
1171  } else if (arg_match(&arg, &use_obu, argi)) {
1172  config->write_webm = 0;
1173  config->write_ivf = 0;
1174  } else if (arg_match(&arg, &threads, argi)) {
1175  config->cfg.g_threads = arg_parse_uint(&arg);
1176  } else if (arg_match(&arg, &profile, argi)) {
1177  config->cfg.g_profile = arg_parse_uint(&arg);
1178  } else if (arg_match(&arg, &width, argi)) {
1179  config->cfg.g_w = arg_parse_uint(&arg);
1180  } else if (arg_match(&arg, &height, argi)) {
1181  config->cfg.g_h = arg_parse_uint(&arg);
1182  } else if (arg_match(&arg, &forced_max_frame_width, argi)) {
1183  config->cfg.g_forced_max_frame_width = arg_parse_uint(&arg);
1184  } else if (arg_match(&arg, &forced_max_frame_height, argi)) {
1185  config->cfg.g_forced_max_frame_height = arg_parse_uint(&arg);
1186  } else if (arg_match(&arg, &bitdeptharg, argi)) {
1187  config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1188  } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1189  config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1190  } else if (arg_match(&arg, &input_chroma_subsampling_x, argi)) {
1191  stream->chroma_subsampling_x = arg_parse_uint(&arg);
1192  } else if (arg_match(&arg, &input_chroma_subsampling_y, argi)) {
1193  stream->chroma_subsampling_y = arg_parse_uint(&arg);
1194 #if CONFIG_WEBM_IO
1195  } else if (arg_match(&arg, &stereo_mode, argi)) {
1196  config->stereo_fmt = arg_parse_enum_or_int(&arg);
1197 #endif
1198  } else if (arg_match(&arg, &timebase, argi)) {
1199  config->cfg.g_timebase = arg_parse_rational(&arg);
1200  validate_positive_rational(arg.name, &config->cfg.g_timebase);
1201  } else if (arg_match(&arg, &global_error_resilient, argi)) {
1202  config->cfg.g_error_resilient = arg_parse_uint(&arg);
1203  } else if (arg_match(&arg, &lag_in_frames, argi)) {
1204  config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1205  } else if (arg_match(&arg, &large_scale_tile, argi)) {
1206  config->cfg.large_scale_tile = arg_parse_uint(&arg);
1207  } else if (arg_match(&arg, &monochrome, argi)) {
1208  config->cfg.monochrome = 1;
1209  } else if (arg_match(&arg, &full_still_picture_hdr, argi)) {
1210  config->cfg.full_still_picture_hdr = 1;
1211  } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1212  config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1213  } else if (arg_match(&arg, &resize_mode, argi)) {
1214  config->cfg.rc_resize_mode = arg_parse_uint(&arg);
1215  } else if (arg_match(&arg, &resize_denominator, argi)) {
1216  config->cfg.rc_resize_denominator = arg_parse_uint(&arg);
1217  } else if (arg_match(&arg, &resize_kf_denominator, argi)) {
1218  config->cfg.rc_resize_kf_denominator = arg_parse_uint(&arg);
1219  } else if (arg_match(&arg, &superres_mode, argi)) {
1220  config->cfg.rc_superres_mode = arg_parse_uint(&arg);
1221  } else if (arg_match(&arg, &superres_denominator, argi)) {
1222  config->cfg.rc_superres_denominator = arg_parse_uint(&arg);
1223  } else if (arg_match(&arg, &superres_kf_denominator, argi)) {
1224  config->cfg.rc_superres_kf_denominator = arg_parse_uint(&arg);
1225  } else if (arg_match(&arg, &superres_qthresh, argi)) {
1226  config->cfg.rc_superres_qthresh = arg_parse_uint(&arg);
1227  } else if (arg_match(&arg, &superres_kf_qthresh, argi)) {
1228  config->cfg.rc_superres_kf_qthresh = arg_parse_uint(&arg);
1229  } else if (arg_match(&arg, &end_usage, argi)) {
1230  config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1231  } else if (arg_match(&arg, &target_bitrate, argi)) {
1232  config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1233  } else if (arg_match(&arg, &min_quantizer, argi)) {
1234  config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1235  } else if (arg_match(&arg, &max_quantizer, argi)) {
1236  config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1237  } else if (arg_match(&arg, &undershoot_pct, argi)) {
1238  config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1239  } else if (arg_match(&arg, &overshoot_pct, argi)) {
1240  config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1241  } else if (arg_match(&arg, &buf_sz, argi)) {
1242  config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1243  } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1244  config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1245  } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1246  config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1247  } else if (arg_match(&arg, &bias_pct, argi)) {
1248  config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1249  if (global->passes < 2)
1250  warn("option %s ignored in one-pass mode.\n", arg.name);
1251  } else if (arg_match(&arg, &minsection_pct, argi)) {
1252  config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1253 
1254  if (global->passes < 2)
1255  warn("option %s ignored in one-pass mode.\n", arg.name);
1256  } else if (arg_match(&arg, &maxsection_pct, argi)) {
1257  config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1258 
1259  if (global->passes < 2)
1260  warn("option %s ignored in one-pass mode.\n", arg.name);
1261  } else if (arg_match(&arg, &fwd_kf_enabled, argi)) {
1262  config->cfg.fwd_kf_enabled = arg_parse_uint(&arg);
1263  } else if (arg_match(&arg, &kf_min_dist, argi)) {
1264  config->cfg.kf_min_dist = arg_parse_uint(&arg);
1265  } else if (arg_match(&arg, &kf_max_dist, argi)) {
1266  config->cfg.kf_max_dist = arg_parse_uint(&arg);
1267  } else if (arg_match(&arg, &kf_disabled, argi)) {
1268  config->cfg.kf_mode = AOM_KF_DISABLED;
1269  } else if (arg_match(&arg, &sframe_dist, argi)) {
1270  config->cfg.sframe_dist = arg_parse_uint(&arg);
1271  } else if (arg_match(&arg, &sframe_mode, argi)) {
1272  config->cfg.sframe_mode = arg_parse_uint(&arg);
1273  } else if (arg_match(&arg, &save_as_annexb, argi)) {
1274  config->cfg.save_as_annexb = arg_parse_uint(&arg);
1275  } else if (arg_match(&arg, &tile_width, argi)) {
1276  config->cfg.tile_width_count =
1277  arg_parse_list(&arg, config->cfg.tile_widths, MAX_TILE_WIDTHS);
1278  } else if (arg_match(&arg, &tile_height, argi)) {
1279  config->cfg.tile_height_count =
1280  arg_parse_list(&arg, config->cfg.tile_heights, MAX_TILE_HEIGHTS);
1281 #if CONFIG_FILEOPTIONS
1282  } else if (arg_match(&arg, &ext_partition, argi)) {
1283  config->cfg.cfg.ext_partition = !!arg_parse_uint(&arg) > 0;
1284 #endif
1285  } else {
1286  int i, match = 0;
1287  for (i = 0; ctrl_args[i]; i++) {
1288  if (arg_match(&arg, ctrl_args[i], argi)) {
1289  match = 1;
1290  if (ctrl_args_map) {
1291  set_config_arg_ctrls(config, ctrl_args_map[i], &arg);
1292  }
1293  }
1294  }
1295  if (!match) argj++;
1296  }
1297  }
1298  config->use_16bit_internal =
1299  config->cfg.g_bit_depth > AOM_BITS_8 || !CONFIG_LOWBITDEPTH;
1300  return eos_mark_found;
1301 }
1302 
1303 #define FOREACH_STREAM(iterator, list) \
1304  for (struct stream_state *iterator = list; iterator; \
1305  iterator = iterator->next)
1306 
1307 static void validate_stream_config(const struct stream_state *stream,
1308  const struct AvxEncoderConfig *global) {
1309  const struct stream_state *streami;
1310  (void)global;
1311 
1312  if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1313  fatal(
1314  "Stream %d: Specify stream dimensions with --width (-w) "
1315  " and --height (-h)",
1316  stream->index);
1317 
1318  // Check that the codec bit depth is greater than the input bit depth.
1319  if (stream->config.cfg.g_input_bit_depth >
1320  (unsigned int)stream->config.cfg.g_bit_depth) {
1321  fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1322  stream->index, (int)stream->config.cfg.g_bit_depth,
1323  stream->config.cfg.g_input_bit_depth);
1324  }
1325 
1326  for (streami = stream; streami; streami = streami->next) {
1327  /* All streams require output files */
1328  if (!streami->config.out_fn)
1329  fatal("Stream %d: Output file is required (specify with -o)",
1330  streami->index);
1331 
1332  /* Check for two streams outputting to the same file */
1333  if (streami != stream) {
1334  const char *a = stream->config.out_fn;
1335  const char *b = streami->config.out_fn;
1336  if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1337  fatal("Stream %d: duplicate output file (from stream %d)",
1338  streami->index, stream->index);
1339  }
1340 
1341  /* Check for two streams sharing a stats file. */
1342  if (streami != stream) {
1343  const char *a = stream->config.stats_fn;
1344  const char *b = streami->config.stats_fn;
1345  if (a && b && !strcmp(a, b))
1346  fatal("Stream %d: duplicate stats file (from stream %d)",
1347  streami->index, stream->index);
1348  }
1349 
1350 #if CONFIG_FP_MB_STATS
1351  /* Check for two streams sharing a mb stats file. */
1352  if (streami != stream) {
1353  const char *a = stream->config.fpmb_stats_fn;
1354  const char *b = streami->config.fpmb_stats_fn;
1355  if (a && b && !strcmp(a, b))
1356  fatal("Stream %d: duplicate mb stats file (from stream %d)",
1357  streami->index, stream->index);
1358  }
1359 #endif
1360  }
1361 }
1362 
1363 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1364  unsigned int h) {
1365  if (!stream->config.cfg.g_w) {
1366  if (!stream->config.cfg.g_h)
1367  stream->config.cfg.g_w = w;
1368  else
1369  stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1370  }
1371  if (!stream->config.cfg.g_h) {
1372  stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1373  }
1374 }
1375 
1376 static const char *file_type_to_string(enum VideoFileType t) {
1377  switch (t) {
1378  case FILE_TYPE_RAW: return "RAW";
1379  case FILE_TYPE_Y4M: return "Y4M";
1380  default: return "Other";
1381  }
1382 }
1383 
1384 static const char *image_format_to_string(aom_img_fmt_t f) {
1385  switch (f) {
1386  case AOM_IMG_FMT_I420: return "I420";
1387  case AOM_IMG_FMT_I422: return "I422";
1388  case AOM_IMG_FMT_I444: return "I444";
1389  case AOM_IMG_FMT_YV12: return "YV12";
1390  case AOM_IMG_FMT_I42016: return "I42016";
1391  case AOM_IMG_FMT_I42216: return "I42216";
1392  case AOM_IMG_FMT_I44416: return "I44416";
1393  default: return "Other";
1394  }
1395 }
1396 
1397 static void show_stream_config(struct stream_state *stream,
1398  struct AvxEncoderConfig *global,
1399  struct AvxInputContext *input) {
1400 #define SHOW(field) \
1401  fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1402 
1403  if (stream->index == 0) {
1404  fprintf(stderr, "Codec: %s\n",
1405  aom_codec_iface_name(global->codec->codec_interface()));
1406  fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1407  input->filename, file_type_to_string(input->file_type),
1408  image_format_to_string(input->fmt));
1409  }
1410  if (stream->next || stream->index)
1411  fprintf(stderr, "\nStream Index: %d\n", stream->index);
1412  fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1413  fprintf(stderr, "Coding path: %s\n",
1414  stream->config.use_16bit_internal ? "HBD" : "LBD");
1415  fprintf(stderr, "Encoder parameters:\n");
1416 
1417  SHOW(g_usage);
1418  SHOW(g_threads);
1419  SHOW(g_profile);
1420  SHOW(g_w);
1421  SHOW(g_h);
1422  SHOW(g_bit_depth);
1423  SHOW(g_input_bit_depth);
1424  SHOW(g_timebase.num);
1425  SHOW(g_timebase.den);
1426  SHOW(g_error_resilient);
1427  SHOW(g_pass);
1428  SHOW(g_lag_in_frames);
1429  SHOW(large_scale_tile);
1430  SHOW(rc_dropframe_thresh);
1431  SHOW(rc_resize_mode);
1432  SHOW(rc_resize_denominator);
1433  SHOW(rc_resize_kf_denominator);
1434  SHOW(rc_superres_mode);
1435  SHOW(rc_superres_denominator);
1436  SHOW(rc_superres_kf_denominator);
1437  SHOW(rc_superres_qthresh);
1438  SHOW(rc_superres_kf_qthresh);
1439  SHOW(rc_end_usage);
1440  SHOW(rc_target_bitrate);
1441  SHOW(rc_min_quantizer);
1442  SHOW(rc_max_quantizer);
1443  SHOW(rc_undershoot_pct);
1444  SHOW(rc_overshoot_pct);
1445  SHOW(rc_buf_sz);
1446  SHOW(rc_buf_initial_sz);
1447  SHOW(rc_buf_optimal_sz);
1448  SHOW(rc_2pass_vbr_bias_pct);
1449  SHOW(rc_2pass_vbr_minsection_pct);
1450  SHOW(rc_2pass_vbr_maxsection_pct);
1451  SHOW(fwd_kf_enabled);
1452  SHOW(kf_mode);
1453  SHOW(kf_min_dist);
1454  SHOW(kf_max_dist);
1455 }
1456 
1457 static void open_output_file(struct stream_state *stream,
1458  struct AvxEncoderConfig *global,
1459  const struct AvxRational *pixel_aspect_ratio) {
1460  const char *fn = stream->config.out_fn;
1461  const struct aom_codec_enc_cfg *const cfg = &stream->config.cfg;
1462 
1463  if (cfg->g_pass == AOM_RC_FIRST_PASS) return;
1464 
1465  stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1466 
1467  if (!stream->file) fatal("Failed to open output file");
1468 
1469  if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1470  fatal("WebM output to pipes not supported.");
1471 
1472 #if CONFIG_WEBM_IO
1473  if (stream->config.write_webm) {
1474  stream->webm_ctx.stream = stream->file;
1475  write_webm_file_header(&stream->webm_ctx, &stream->encoder, cfg,
1476  stream->config.stereo_fmt, global->codec->fourcc,
1477  pixel_aspect_ratio);
1478  }
1479 #else
1480  (void)pixel_aspect_ratio;
1481 #endif
1482 
1483  if (!stream->config.write_webm && stream->config.write_ivf) {
1484  ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1485  }
1486 }
1487 
1488 static void close_output_file(struct stream_state *stream,
1489  unsigned int fourcc) {
1490  const struct aom_codec_enc_cfg *const cfg = &stream->config.cfg;
1491 
1492  if (cfg->g_pass == AOM_RC_FIRST_PASS) return;
1493 
1494 #if CONFIG_WEBM_IO
1495  if (stream->config.write_webm) {
1496  write_webm_file_footer(&stream->webm_ctx);
1497  }
1498 #endif
1499 
1500  if (!stream->config.write_webm && stream->config.write_ivf) {
1501  if (!fseek(stream->file, 0, SEEK_SET))
1502  ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1503  stream->frames_out);
1504  }
1505 
1506  fclose(stream->file);
1507 }
1508 
1509 static void setup_pass(struct stream_state *stream,
1510  struct AvxEncoderConfig *global, int pass) {
1511  if (stream->config.stats_fn) {
1512  if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1513  fatal("Failed to open statistics store");
1514  } else {
1515  if (!stats_open_mem(&stream->stats, pass))
1516  fatal("Failed to open statistics store");
1517  }
1518 
1519 #if CONFIG_FP_MB_STATS
1520  if (stream->config.fpmb_stats_fn) {
1521  if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
1522  pass))
1523  fatal("Failed to open mb statistics store");
1524  } else {
1525  if (!stats_open_mem(&stream->fpmb_stats, pass))
1526  fatal("Failed to open mb statistics store");
1527  }
1528 #endif
1529 
1530  stream->config.cfg.g_pass = global->passes == 2
1532  : AOM_RC_ONE_PASS;
1533  if (pass) {
1534  stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1535 #if CONFIG_FP_MB_STATS
1536  stream->config.cfg.rc_firstpass_mb_stats_in =
1537  stats_get(&stream->fpmb_stats);
1538 #endif
1539  }
1540 
1541  stream->cx_time = 0;
1542  stream->nbytes = 0;
1543  stream->frames_out = 0;
1544 }
1545 
1546 static void initialize_encoder(struct stream_state *stream,
1547  struct AvxEncoderConfig *global) {
1548  int i;
1549  int flags = 0;
1550 
1551  flags |= global->show_psnr ? AOM_CODEC_USE_PSNR : 0;
1552  flags |= stream->config.use_16bit_internal ? AOM_CODEC_USE_HIGHBITDEPTH : 0;
1553 
1554  /* Construct Encoder Context */
1555  aom_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1556  &stream->config.cfg, flags);
1557  ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1558 
1559  /* Note that we bypass the aom_codec_control wrapper macro because
1560  * we're being clever to store the control IDs in an array. Real
1561  * applications will want to make use of the enumerations directly
1562  */
1563  for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1564  int ctrl = stream->config.arg_ctrls[i][0];
1565  int value = stream->config.arg_ctrls[i][1];
1566  if (aom_codec_control_(&stream->encoder, ctrl, value))
1567  fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1568 
1569  ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1570  }
1571  if (stream->config.film_grain_filename) {
1573  stream->config.film_grain_filename);
1574  }
1575 
1576 #if CONFIG_AV1_DECODER
1577  if (global->test_decode != TEST_DECODE_OFF) {
1578  const AvxInterface *decoder = get_aom_decoder_by_name(global->codec->name);
1579  aom_codec_dec_cfg_t cfg = { 0, 0, 0, CONFIG_LOWBITDEPTH, { 1 } };
1580  aom_codec_dec_init(&stream->decoder, decoder->codec_interface(), &cfg, 0);
1581 
1582  if (strcmp(global->codec->name, "av1") == 0) {
1583  aom_codec_control(&stream->decoder, AV1_SET_TILE_MODE,
1584  stream->config.cfg.large_scale_tile);
1585  ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_mode");
1586 
1587  aom_codec_control(&stream->decoder, AV1D_SET_IS_ANNEXB,
1588  stream->config.cfg.save_as_annexb);
1589  ctx_exit_on_error(&stream->decoder, "Failed to set is_annexb");
1590 
1591  aom_codec_control(&stream->decoder, AV1_SET_DECODE_TILE_ROW, -1);
1592  ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_row");
1593 
1594  aom_codec_control(&stream->decoder, AV1_SET_DECODE_TILE_COL, -1);
1595  ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_col");
1596  }
1597  }
1598 #endif
1599 }
1600 
1601 static void encode_frame(struct stream_state *stream,
1602  struct AvxEncoderConfig *global, struct aom_image *img,
1603  unsigned int frames_in) {
1604  aom_codec_pts_t frame_start, next_frame_start;
1605  struct aom_codec_enc_cfg *cfg = &stream->config.cfg;
1606  struct aom_usec_timer timer;
1607 
1608  frame_start =
1609  (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1610  cfg->g_timebase.num / global->framerate.num;
1611  next_frame_start =
1612  (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1613  cfg->g_timebase.num / global->framerate.num;
1614 
1615  /* Scale if necessary */
1616  if (img) {
1617  if ((img->fmt & AOM_IMG_FMT_HIGHBITDEPTH) &&
1618  (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1619  if (img->fmt != AOM_IMG_FMT_I42016) {
1620  fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1621  exit(EXIT_FAILURE);
1622  }
1623 #if CONFIG_LIBYUV
1624  if (!stream->img) {
1625  stream->img =
1626  aom_img_alloc(NULL, AOM_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1627  }
1628  I420Scale_16(
1629  (uint16_t *)img->planes[AOM_PLANE_Y], img->stride[AOM_PLANE_Y] / 2,
1630  (uint16_t *)img->planes[AOM_PLANE_U], img->stride[AOM_PLANE_U] / 2,
1631  (uint16_t *)img->planes[AOM_PLANE_V], img->stride[AOM_PLANE_V] / 2,
1632  img->d_w, img->d_h, (uint16_t *)stream->img->planes[AOM_PLANE_Y],
1633  stream->img->stride[AOM_PLANE_Y] / 2,
1634  (uint16_t *)stream->img->planes[AOM_PLANE_U],
1635  stream->img->stride[AOM_PLANE_U] / 2,
1636  (uint16_t *)stream->img->planes[AOM_PLANE_V],
1637  stream->img->stride[AOM_PLANE_V] / 2, stream->img->d_w,
1638  stream->img->d_h, kFilterBox);
1639  img = stream->img;
1640 #else
1641  stream->encoder.err = 1;
1642  ctx_exit_on_error(&stream->encoder,
1643  "Stream %d: Failed to encode frame.\n"
1644  "libyuv is required for scaling but is currently "
1645  "disabled.\n"
1646  "Be sure to specify -DCONFIG_LIBYUV=1 when running "
1647  "cmake.\n",
1648  stream->index);
1649 #endif
1650  }
1651  }
1652  if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1653  if (img->fmt != AOM_IMG_FMT_I420 && img->fmt != AOM_IMG_FMT_YV12) {
1654  fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1655  exit(EXIT_FAILURE);
1656  }
1657 #if CONFIG_LIBYUV
1658  if (!stream->img)
1659  stream->img =
1660  aom_img_alloc(NULL, AOM_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
1661  I420Scale(
1662  img->planes[AOM_PLANE_Y], img->stride[AOM_PLANE_Y],
1663  img->planes[AOM_PLANE_U], img->stride[AOM_PLANE_U],
1664  img->planes[AOM_PLANE_V], img->stride[AOM_PLANE_V], img->d_w, img->d_h,
1665  stream->img->planes[AOM_PLANE_Y], stream->img->stride[AOM_PLANE_Y],
1666  stream->img->planes[AOM_PLANE_U], stream->img->stride[AOM_PLANE_U],
1667  stream->img->planes[AOM_PLANE_V], stream->img->stride[AOM_PLANE_V],
1668  stream->img->d_w, stream->img->d_h, kFilterBox);
1669  img = stream->img;
1670 #else
1671  stream->encoder.err = 1;
1672  ctx_exit_on_error(&stream->encoder,
1673  "Stream %d: Failed to encode frame.\n"
1674  "Scaling disabled in this configuration. \n"
1675  "To enable, configure with --enable-libyuv\n",
1676  stream->index);
1677 #endif
1678  }
1679 
1680  aom_usec_timer_start(&timer);
1681  aom_codec_encode(&stream->encoder, img, frame_start,
1682  (uint32_t)(next_frame_start - frame_start), 0);
1683  aom_usec_timer_mark(&timer);
1684  stream->cx_time += aom_usec_timer_elapsed(&timer);
1685  ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1686  stream->index);
1687 }
1688 
1689 static void update_quantizer_histogram(struct stream_state *stream) {
1690  if (stream->config.cfg.g_pass != AOM_RC_FIRST_PASS) {
1691  int q;
1692 
1693  aom_codec_control(&stream->encoder, AOME_GET_LAST_QUANTIZER_64, &q);
1694  ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1695  stream->counts[q]++;
1696  }
1697 }
1698 
1699 static void get_cx_data(struct stream_state *stream,
1700  struct AvxEncoderConfig *global, int *got_data) {
1701  const aom_codec_cx_pkt_t *pkt;
1702  const struct aom_codec_enc_cfg *cfg = &stream->config.cfg;
1703  aom_codec_iter_t iter = NULL;
1704 
1705  *got_data = 0;
1706  while ((pkt = aom_codec_get_cx_data(&stream->encoder, &iter))) {
1707  static size_t fsize = 0;
1708  static FileOffset ivf_header_pos = 0;
1709 
1710  switch (pkt->kind) {
1712  if (!(pkt->data.frame.flags & AOM_FRAME_IS_FRAGMENT)) {
1713  stream->frames_out++;
1714  }
1715  if (!global->quiet)
1716  fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1717 
1718  update_rate_histogram(stream->rate_hist, cfg, pkt);
1719 #if CONFIG_WEBM_IO
1720  if (stream->config.write_webm) {
1721  write_webm_block(&stream->webm_ctx, cfg, pkt);
1722  }
1723 #endif
1724  if (!stream->config.write_webm) {
1725  if (stream->config.write_ivf) {
1726  if (pkt->data.frame.partition_id <= 0) {
1727  ivf_header_pos = ftello(stream->file);
1728  fsize = pkt->data.frame.sz;
1729 
1730  ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1731  } else {
1732  fsize += pkt->data.frame.sz;
1733 
1734  if (!(pkt->data.frame.flags & AOM_FRAME_IS_FRAGMENT)) {
1735  const FileOffset currpos = ftello(stream->file);
1736  fseeko(stream->file, ivf_header_pos, SEEK_SET);
1737  ivf_write_frame_size(stream->file, fsize);
1738  fseeko(stream->file, currpos, SEEK_SET);
1739  }
1740  }
1741  }
1742 
1743  (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1744  stream->file);
1745  }
1746  stream->nbytes += pkt->data.raw.sz;
1747 
1748  *got_data = 1;
1749 #if CONFIG_AV1_DECODER
1750  if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1751  aom_codec_decode(&stream->decoder, pkt->data.frame.buf,
1752  pkt->data.frame.sz, NULL);
1753  if (stream->decoder.err) {
1754  warn_or_exit_on_error(&stream->decoder,
1755  global->test_decode == TEST_DECODE_FATAL,
1756  "Failed to decode frame %d in stream %d",
1757  stream->frames_out + 1, stream->index);
1758  stream->mismatch_seen = stream->frames_out + 1;
1759  }
1760  }
1761 #endif
1762  break;
1763  case AOM_CODEC_STATS_PKT:
1764  stream->frames_out++;
1765  stats_write(&stream->stats, pkt->data.twopass_stats.buf,
1766  pkt->data.twopass_stats.sz);
1767  stream->nbytes += pkt->data.raw.sz;
1768  break;
1769 #if CONFIG_FP_MB_STATS
1771  stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
1772  pkt->data.firstpass_mb_stats.sz);
1773  stream->nbytes += pkt->data.raw.sz;
1774  break;
1775 #endif
1776  case AOM_CODEC_PSNR_PKT:
1777 
1778  if (global->show_psnr) {
1779  int i;
1780 
1781  stream->psnr_sse_total += pkt->data.psnr.sse[0];
1782  stream->psnr_samples_total += pkt->data.psnr.samples[0];
1783  for (i = 0; i < 4; i++) {
1784  if (!global->quiet)
1785  fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1786  stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1787  }
1788  stream->psnr_count++;
1789  }
1790 
1791  break;
1792  default: break;
1793  }
1794  }
1795 }
1796 
1797 static void show_psnr(struct stream_state *stream, double peak, int64_t bps) {
1798  int i;
1799  double ovpsnr;
1800 
1801  if (!stream->psnr_count) return;
1802 
1803  fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1804  ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1805  (double)stream->psnr_sse_total);
1806  fprintf(stderr, " %.3f", ovpsnr);
1807 
1808  for (i = 0; i < 4; i++) {
1809  fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1810  }
1811  if (bps > 0) {
1812  fprintf(stderr, " %7" PRId64 " bps", bps);
1813  }
1814  fprintf(stderr, " %7" PRId64 " ms", stream->cx_time / 1000);
1815  fprintf(stderr, "\n");
1816 }
1817 
1818 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1819  return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1820 }
1821 
1822 static void test_decode(struct stream_state *stream,
1823  enum TestDecodeFatality fatal) {
1824  aom_image_t enc_img, dec_img;
1825 
1826  if (stream->mismatch_seen) return;
1827 
1828  /* Get the internal reference frame */
1829  aom_codec_control(&stream->encoder, AV1_GET_NEW_FRAME_IMAGE, &enc_img);
1830  aom_codec_control(&stream->decoder, AV1_GET_NEW_FRAME_IMAGE, &dec_img);
1831 
1832  if ((enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) !=
1833  (dec_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH)) {
1834  if (enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
1835  aom_image_t enc_hbd_img;
1836  aom_img_alloc(&enc_hbd_img, enc_img.fmt - AOM_IMG_FMT_HIGHBITDEPTH,
1837  enc_img.d_w, enc_img.d_h, 16);
1838  aom_img_truncate_16_to_8(&enc_hbd_img, &enc_img);
1839  enc_img = enc_hbd_img;
1840  }
1841  if (dec_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
1842  aom_image_t dec_hbd_img;
1843  aom_img_alloc(&dec_hbd_img, dec_img.fmt - AOM_IMG_FMT_HIGHBITDEPTH,
1844  dec_img.d_w, dec_img.d_h, 16);
1845  aom_img_truncate_16_to_8(&dec_hbd_img, &dec_img);
1846  dec_img = dec_hbd_img;
1847  }
1848  }
1849 
1850  ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1851  ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1852 
1853  if (!aom_compare_img(&enc_img, &dec_img)) {
1854  int y[4], u[4], v[4];
1855  if (enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
1856  aom_find_mismatch_high(&enc_img, &dec_img, y, u, v);
1857  } else {
1858  aom_find_mismatch(&enc_img, &dec_img, y, u, v);
1859  }
1860  stream->decoder.err = 1;
1861  warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1862  "Stream %d: Encode/decode mismatch on frame %d at"
1863  " Y[%d, %d] {%d/%d},"
1864  " U[%d, %d] {%d/%d},"
1865  " V[%d, %d] {%d/%d}",
1866  stream->index, stream->frames_out, y[0], y[1], y[2],
1867  y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
1868  stream->mismatch_seen = stream->frames_out;
1869  }
1870 
1871  aom_img_free(&enc_img);
1872  aom_img_free(&dec_img);
1873 }
1874 
1875 static void print_time(const char *label, int64_t etl) {
1876  int64_t hours;
1877  int64_t mins;
1878  int64_t secs;
1879 
1880  if (etl >= 0) {
1881  hours = etl / 3600;
1882  etl -= hours * 3600;
1883  mins = etl / 60;
1884  etl -= mins * 60;
1885  secs = etl;
1886 
1887  fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
1888  hours, mins, secs);
1889  } else {
1890  fprintf(stderr, "[%3s unknown] ", label);
1891  }
1892 }
1893 
1894 int main(int argc, const char **argv_) {
1895  int pass;
1896  aom_image_t raw;
1897  aom_image_t raw_shift;
1898  int allocated_raw_shift = 0;
1899  int use_16bit_internal = 0;
1900  int input_shift = 0;
1901  int frame_avail, got_data;
1902 
1903  struct AvxInputContext input;
1904  struct AvxEncoderConfig global;
1905  struct stream_state *streams = NULL;
1906  char **argv, **argi;
1907  uint64_t cx_time = 0;
1908  int stream_cnt = 0;
1909  int res = 0;
1910  int profile_updated = 0;
1911 
1912  memset(&input, 0, sizeof(input));
1913  exec_name = argv_[0];
1914 
1915  /* Setup default input stream settings */
1916  input.framerate.numerator = 30;
1917  input.framerate.denominator = 1;
1918  input.only_i420 = 1;
1919  input.bit_depth = 0;
1920 
1921  /* First parse the global configuration values, because we want to apply
1922  * other parameters on top of the default configuration provided by the
1923  * codec.
1924  */
1925  argv = argv_dup(argc - 1, argv_ + 1);
1926  parse_global_config(&global, argc, &argv);
1927 
1928 #if CONFIG_FILEOPTIONS
1929  if (argc < 2) usage_exit();
1930 #else
1931  if (argc < 3) usage_exit();
1932 #endif
1933 
1934  switch (global.color_type) {
1935  case I420: input.fmt = AOM_IMG_FMT_I420; break;
1936  case I422: input.fmt = AOM_IMG_FMT_I422; break;
1937  case I444: input.fmt = AOM_IMG_FMT_I444; break;
1938  case YV12: input.fmt = AOM_IMG_FMT_YV12; break;
1939  }
1940 
1941  {
1942  /* Now parse each stream's parameters. Using a local scope here
1943  * due to the use of 'stream' as loop variable in FOREACH_STREAM
1944  * loops
1945  */
1946  struct stream_state *stream = NULL;
1947 
1948  do {
1949  stream = new_stream(&global, stream);
1950  stream_cnt++;
1951  if (!streams) streams = stream;
1952  } while (parse_stream_params(&global, stream, argv));
1953  }
1954 
1955  /* Check for unrecognized options */
1956  for (argi = argv; *argi; argi++)
1957  if (argi[0][0] == '-' && argi[0][1])
1958  die("Error: Unrecognized option %s\n", *argi);
1959 
1960  FOREACH_STREAM(stream, streams) {
1961  check_encoder_config(global.disable_warning_prompt, &global,
1962  &stream->config.cfg);
1963  }
1964 
1965  /* Handle non-option arguments */
1966  input.filename = argv[0];
1967 
1968  if (!input.filename) {
1969  fprintf(stderr, "No input file specified!\n");
1970  usage_exit();
1971  }
1972 
1973  /* Decide if other chroma subsamplings than 4:2:0 are supported */
1974  if (global.codec->fourcc == AV1_FOURCC) input.only_i420 = 0;
1975 
1976  for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1977  int frames_in = 0, seen_frames = 0;
1978  int64_t estimated_time_left = -1;
1979  int64_t average_rate = -1;
1980  int64_t lagged_count = 0;
1981 
1982  open_input_file(&input, global.csp);
1983 
1984  /* If the input file doesn't specify its w/h (raw files), try to get
1985  * the data from the first stream's configuration.
1986  */
1987  if (!input.width || !input.height) {
1988  FOREACH_STREAM(stream, streams) {
1989  if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1990  input.width = stream->config.cfg.g_w;
1991  input.height = stream->config.cfg.g_h;
1992  break;
1993  }
1994  };
1995  }
1996 
1997  /* Update stream configurations from the input file's parameters */
1998  if (!input.width || !input.height)
1999  fatal(
2000  "Specify stream dimensions with --width (-w) "
2001  " and --height (-h)");
2002 
2003  /* If input file does not specify bit-depth but input-bit-depth parameter
2004  * exists, assume that to be the input bit-depth. However, if the
2005  * input-bit-depth paramter does not exist, assume the input bit-depth
2006  * to be the same as the codec bit-depth.
2007  */
2008  if (!input.bit_depth) {
2009  FOREACH_STREAM(stream, streams) {
2010  if (stream->config.cfg.g_input_bit_depth)
2011  input.bit_depth = stream->config.cfg.g_input_bit_depth;
2012  else
2013  input.bit_depth = stream->config.cfg.g_input_bit_depth =
2014  (int)stream->config.cfg.g_bit_depth;
2015  }
2016  if (input.bit_depth > 8) input.fmt |= AOM_IMG_FMT_HIGHBITDEPTH;
2017  } else {
2018  FOREACH_STREAM(stream, streams) {
2019  stream->config.cfg.g_input_bit_depth = input.bit_depth;
2020  }
2021  }
2022 
2023  FOREACH_STREAM(stream, streams) {
2024  if (input.fmt != AOM_IMG_FMT_I420 && input.fmt != AOM_IMG_FMT_I42016) {
2025  /* Automatically upgrade if input is non-4:2:0 but a 4:2:0 profile
2026  was selected. */
2027  switch (stream->config.cfg.g_profile) {
2028  case 0:
2029  if (input.bit_depth < 12 && (input.fmt == AOM_IMG_FMT_I444 ||
2030  input.fmt == AOM_IMG_FMT_I44416)) {
2031  if (!stream->config.cfg.monochrome) {
2032  stream->config.cfg.g_profile = 1;
2033  profile_updated = 1;
2034  }
2035  } else if (input.bit_depth == 12 || input.fmt == AOM_IMG_FMT_I422 ||
2036  input.fmt == AOM_IMG_FMT_I42216) {
2037  stream->config.cfg.g_profile = 2;
2038  profile_updated = 1;
2039  }
2040  break;
2041  case 1:
2042  if (input.bit_depth == 12 || input.fmt == AOM_IMG_FMT_I422 ||
2043  input.fmt == AOM_IMG_FMT_I42216) {
2044  stream->config.cfg.g_profile = 2;
2045  profile_updated = 1;
2046  } else if (input.bit_depth < 12 &&
2047  (input.fmt == AOM_IMG_FMT_I420 ||
2048  input.fmt == AOM_IMG_FMT_I42016)) {
2049  stream->config.cfg.g_profile = 0;
2050  profile_updated = 1;
2051  }
2052  break;
2053  case 2:
2054  if (input.bit_depth < 12 && (input.fmt == AOM_IMG_FMT_I444 ||
2055  input.fmt == AOM_IMG_FMT_I44416)) {
2056  stream->config.cfg.g_profile = 1;
2057  profile_updated = 1;
2058  } else if (input.bit_depth < 12 &&
2059  (input.fmt == AOM_IMG_FMT_I420 ||
2060  input.fmt == AOM_IMG_FMT_I42016)) {
2061  stream->config.cfg.g_profile = 0;
2062  profile_updated = 1;
2063  } else if (input.bit_depth == 12 &&
2064  input.file_type == FILE_TYPE_Y4M) {
2065  // Note that here the input file values for chroma subsampling
2066  // are used instead of those from the command line.
2068  input.y4m.dst_c_dec_h >> 1);
2070  input.y4m.dst_c_dec_v >> 1);
2071  } else if (input.bit_depth == 12 &&
2072  input.file_type == FILE_TYPE_RAW) {
2074  stream->chroma_subsampling_x);
2076  stream->chroma_subsampling_y);
2077  }
2078  break;
2079  default: break;
2080  }
2081  }
2082  if (stream->config.cfg.g_bit_depth > 10) {
2083  switch (stream->config.cfg.g_profile) {
2084  case 0:
2085  case 1:
2086  stream->config.cfg.g_profile = 2;
2087  profile_updated = 1;
2088  break;
2089  default: break;
2090  }
2091  }
2092  if (stream->config.cfg.g_bit_depth > 8) {
2093  stream->config.use_16bit_internal = 1;
2094  }
2095  if (profile_updated && !global.quiet) {
2096  fprintf(stderr,
2097  "Warning: automatically updating to profile %d to "
2098  "match input format.\n",
2099  stream->config.cfg.g_profile);
2100  }
2101  /* Set limit */
2102  stream->config.cfg.g_limit = global.limit;
2103  }
2104 
2105  FOREACH_STREAM(stream, streams) {
2106  set_stream_dimensions(stream, input.width, input.height);
2107  }
2108  FOREACH_STREAM(stream, streams) { validate_stream_config(stream, &global); }
2109 
2110  /* Ensure that --passes and --pass are consistent. If --pass is set and
2111  * --passes=2, ensure --fpf was set.
2112  */
2113  if (global.pass && global.passes == 2) {
2114  FOREACH_STREAM(stream, streams) {
2115  if (!stream->config.stats_fn)
2116  die("Stream %d: Must specify --fpf when --pass=%d"
2117  " and --passes=2\n",
2118  stream->index, global.pass);
2119  }
2120  }
2121 
2122 #if !CONFIG_WEBM_IO
2123  FOREACH_STREAM(stream, streams) {
2124  if (stream->config.write_webm) {
2125  stream->config.write_webm = 0;
2126  stream->config.write_ivf = 0;
2127  warn("aomenc compiled w/o WebM support. Writing OBU stream.");
2128  }
2129  }
2130 #endif
2131 
2132  /* Use the frame rate from the file only if none was specified
2133  * on the command-line.
2134  */
2135  if (!global.have_framerate) {
2136  global.framerate.num = input.framerate.numerator;
2137  global.framerate.den = input.framerate.denominator;
2138  }
2139  FOREACH_STREAM(stream, streams) {
2140  stream->config.cfg.g_timebase.den = global.framerate.num;
2141  stream->config.cfg.g_timebase.num = global.framerate.den;
2142  }
2143  /* Show configuration */
2144  if (global.verbose && pass == 0) {
2145  FOREACH_STREAM(stream, streams) {
2146  show_stream_config(stream, &global, &input);
2147  }
2148  }
2149 
2150  if (pass == (global.pass ? global.pass - 1 : 0)) {
2151  if (input.file_type == FILE_TYPE_Y4M)
2152  /*The Y4M reader does its own allocation.
2153  Just initialize this here to avoid problems if we never read any
2154  frames.*/
2155  memset(&raw, 0, sizeof(raw));
2156  else
2157  aom_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2158 
2159  FOREACH_STREAM(stream, streams) {
2160  stream->rate_hist =
2161  init_rate_histogram(&stream->config.cfg, &global.framerate);
2162  }
2163  }
2164 
2165  FOREACH_STREAM(stream, streams) { setup_pass(stream, &global, pass); }
2166  FOREACH_STREAM(stream, streams) { initialize_encoder(stream, &global); }
2167  FOREACH_STREAM(stream, streams) {
2168  open_output_file(stream, &global, &input.pixel_aspect_ratio);
2169  }
2170 
2171  if (strcmp(global.codec->name, "av1") == 0 ||
2172  strcmp(global.codec->name, "av1") == 0) {
2173  // Check to see if at least one stream uses 16 bit internal.
2174  // Currently assume that the bit_depths for all streams using
2175  // highbitdepth are the same.
2176  FOREACH_STREAM(stream, streams) {
2177  if (stream->config.use_16bit_internal) {
2178  use_16bit_internal = 1;
2179  }
2180  input_shift = (int)stream->config.cfg.g_bit_depth -
2181  stream->config.cfg.g_input_bit_depth;
2182  };
2183  }
2184 
2185  frame_avail = 1;
2186  got_data = 0;
2187 
2188  while (frame_avail || got_data) {
2189  struct aom_usec_timer timer;
2190 
2191  if (!global.limit || frames_in < global.limit) {
2192  frame_avail = read_frame(&input, &raw);
2193 
2194  if (frame_avail) frames_in++;
2195  seen_frames =
2196  frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2197 
2198  if (!global.quiet) {
2199  float fps = usec_to_fps(cx_time, seen_frames);
2200  fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2201 
2202  if (stream_cnt == 1)
2203  fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2204  streams->frames_out, (int64_t)streams->nbytes);
2205  else
2206  fprintf(stderr, "frame %4d ", frames_in);
2207 
2208  fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2209  cx_time > 9999999 ? cx_time / 1000 : cx_time,
2210  cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2211  fps >= 1.0 ? "fps" : "fpm");
2212  print_time("ETA", estimated_time_left);
2213  }
2214 
2215  } else {
2216  frame_avail = 0;
2217  }
2218 
2219  if (frames_in > global.skip_frames) {
2220  aom_image_t *frame_to_encode;
2221  if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2222  assert(use_16bit_internal);
2223  // Input bit depth and stream bit depth do not match, so up
2224  // shift frame to stream bit depth
2225  if (!allocated_raw_shift) {
2226  aom_img_alloc(&raw_shift, raw.fmt | AOM_IMG_FMT_HIGHBITDEPTH,
2227  input.width, input.height, 32);
2228  allocated_raw_shift = 1;
2229  }
2230  aom_img_upshift(&raw_shift, &raw, input_shift);
2231  frame_to_encode = &raw_shift;
2232  } else {
2233  frame_to_encode = &raw;
2234  }
2235  aom_usec_timer_start(&timer);
2236  if (use_16bit_internal) {
2237  assert(frame_to_encode->fmt & AOM_IMG_FMT_HIGHBITDEPTH);
2238  FOREACH_STREAM(stream, streams) {
2239  if (stream->config.use_16bit_internal)
2240  encode_frame(stream, &global,
2241  frame_avail ? frame_to_encode : NULL, frames_in);
2242  else
2243  assert(0);
2244  };
2245  } else {
2246  assert((frame_to_encode->fmt & AOM_IMG_FMT_HIGHBITDEPTH) == 0);
2247  FOREACH_STREAM(stream, streams) {
2248  encode_frame(stream, &global, frame_avail ? frame_to_encode : NULL,
2249  frames_in);
2250  }
2251  }
2252  aom_usec_timer_mark(&timer);
2253  cx_time += aom_usec_timer_elapsed(&timer);
2254 
2255  FOREACH_STREAM(stream, streams) { update_quantizer_histogram(stream); }
2256 
2257  got_data = 0;
2258  FOREACH_STREAM(stream, streams) {
2259  get_cx_data(stream, &global, &got_data);
2260  }
2261 
2262  if (!got_data && input.length && streams != NULL &&
2263  !streams->frames_out) {
2264  lagged_count = global.limit ? seen_frames : ftello(input.file);
2265  } else if (input.length) {
2266  int64_t remaining;
2267  int64_t rate;
2268 
2269  if (global.limit) {
2270  const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2271 
2272  rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2273  remaining = 1000 * (global.limit - global.skip_frames -
2274  seen_frames + lagged_count);
2275  } else {
2276  const int64_t input_pos = ftello(input.file);
2277  const int64_t input_pos_lagged = input_pos - lagged_count;
2278  const int64_t input_limit = input.length;
2279 
2280  rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2281  remaining = input_limit - input_pos + lagged_count;
2282  }
2283 
2284  average_rate =
2285  (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2286  estimated_time_left = average_rate ? remaining / average_rate : -1;
2287  }
2288 
2289  if (got_data && global.test_decode != TEST_DECODE_OFF) {
2290  FOREACH_STREAM(stream, streams) {
2291  test_decode(stream, global.test_decode);
2292  }
2293  }
2294  }
2295 
2296  fflush(stdout);
2297  if (!global.quiet) fprintf(stderr, "\033[K");
2298  }
2299 
2300  if (stream_cnt > 1) fprintf(stderr, "\n");
2301 
2302  if (!global.quiet) {
2303  FOREACH_STREAM(stream, streams) {
2304  const int64_t bpf =
2305  seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0;
2306  const int64_t bps = bpf * global.framerate.num / global.framerate.den;
2307  fprintf(stderr,
2308  "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64
2309  "b/f %7" PRId64
2310  "b/s"
2311  " %7" PRId64 " %s (%.2f fps)\033[K\n",
2312  pass + 1, global.passes, frames_in, stream->frames_out,
2313  (int64_t)stream->nbytes, bpf, bps,
2314  stream->cx_time > 9999999 ? stream->cx_time / 1000
2315  : stream->cx_time,
2316  stream->cx_time > 9999999 ? "ms" : "us",
2317  usec_to_fps(stream->cx_time, seen_frames));
2318  }
2319  }
2320 
2321  if (global.show_psnr) {
2322  if (global.codec->fourcc == AV1_FOURCC) {
2323  FOREACH_STREAM(stream, streams) {
2324  int64_t bps = 0;
2325  if (stream->psnr_count && seen_frames && global.framerate.den) {
2326  bps = (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2327  global.framerate.den / seen_frames;
2328  }
2329  show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1,
2330  bps);
2331  }
2332  } else {
2333  FOREACH_STREAM(stream, streams) { show_psnr(stream, 255.0, 0); }
2334  }
2335  }
2336 
2337  FOREACH_STREAM(stream, streams) { aom_codec_destroy(&stream->encoder); }
2338 
2339  if (global.test_decode != TEST_DECODE_OFF) {
2340  FOREACH_STREAM(stream, streams) { aom_codec_destroy(&stream->decoder); }
2341  }
2342 
2343  close_input_file(&input);
2344 
2345  if (global.test_decode == TEST_DECODE_FATAL) {
2346  FOREACH_STREAM(stream, streams) { res |= stream->mismatch_seen; }
2347  }
2348  FOREACH_STREAM(stream, streams) {
2349  close_output_file(stream, global.codec->fourcc);
2350  }
2351 
2352  FOREACH_STREAM(stream, streams) {
2353  stats_close(&stream->stats, global.passes - 1);
2354  }
2355 
2356 #if CONFIG_FP_MB_STATS
2357  FOREACH_STREAM(stream, streams) {
2358  stats_close(&stream->fpmb_stats, global.passes - 1);
2359  }
2360 #endif
2361 
2362  if (global.pass) break;
2363  }
2364 
2365  if (global.show_q_hist_buckets) {
2366  FOREACH_STREAM(stream, streams) {
2367  show_q_histogram(stream->counts, global.show_q_hist_buckets);
2368  }
2369  }
2370 
2371  if (global.show_rate_hist_buckets) {
2372  FOREACH_STREAM(stream, streams) {
2373  show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2374  global.show_rate_hist_buckets);
2375  }
2376  }
2377  FOREACH_STREAM(stream, streams) { destroy_rate_histogram(stream->rate_hist); }
2378 
2379 #if CONFIG_INTERNAL_STATS
2380  /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2381  * to match some existing utilities.
2382  */
2383  if (!(global.pass == 1 && global.passes == 2)) {
2384  FOREACH_STREAM(stream, streams) {
2385  FILE *f = fopen("opsnr.stt", "a");
2386  if (stream->mismatch_seen) {
2387  fprintf(f, "First mismatch occurred in frame %d\n",
2388  stream->mismatch_seen);
2389  } else {
2390  fprintf(f, "No mismatch detected in recon buffers\n");
2391  }
2392  fclose(f);
2393  }
2394  }
2395 #endif
2396 
2397  if (allocated_raw_shift) aom_img_free(&raw_shift);
2398  aom_img_free(&raw);
2399  free(argv);
2400  free(streams);
2401  return res ? EXIT_FAILURE : EXIT_SUCCESS;
2402 }
#define AOM_PLANE_U
Definition: aom_image.h:170
void * buf
Definition: aom_encoder.h:77
Definition: aom_image.h:86
Codec control function to set Max data rate for Intra frames.
Definition: aomcx.h:240
unsigned int d_h
Definition: aom_image.h:157
#define AOM_PLANE_V
Definition: aom_image.h:171
Codec control function to set an MTU size for a tile group.
Definition: aomcx.h:685
Codec control function to encode with CDEF.
Definition: aomcx.h:548
Definition: aom_encoder.h:189
unsigned int g_w
Width of the frame.
Definition: aom_encoder.h:269
Definition: aom_image.h:92
Codec control function to turn on / off frame order hint for a few tools:
Definition: aomcx.h:729
Describes the encoder algorithm interface to applications.
Definition: aom_image.h:133
Codec control function to set noise sensitivity.
Definition: aomcx.h:387
Codec control function to encode with quantisation matrices.
Definition: aomcx.h:583
Codec control function to signal picture timing info in the bitstream.
Definition: aomcx.h:844
#define aom_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for aom_codec_enc_init_ver()
Definition: aom_encoder.h:767
Encoder configuration structure.
Definition: aom_encoder.h:230
Definition: aom_image.h:66
aom_codec_err_t err
Definition: aom_codec.h:207
enum aom_img_fmt aom_img_fmt_t
List of supported image formats.
Codec control function to set chroma 4:2:0 sample position info.
Definition: aomcx.h:480
#define AOM_CODEC_USE_PSNR
Initialization-time Feature Enabling.
Definition: aom_encoder.h:68
Codec control function to encode without trellis quantization.
Definition: aomcx.h:569
Definition: aom_image.h:87
Definition: aom_image.h:114
Codec control function to set the max no of frames to create arf.
Definition: aomcx.h:211
int64_t aom_codec_pts_t
Time Stamp Type.
Definition: aom_encoder.h:86
Codec control function to set constrained quality level.
Definition: aomcx.h:227
Definition: aomdx.h:203
Definition: aom_encoder.h:195
Definition: aom_image.h:65
Definition: aom_image.h:50
Definition: aom_image.h:81
Definition: aom_image.h:96
Provides definitions for using AOM or AV1 encoder algorithm within the aom Codec Interface.
Rational Number.
Definition: aom_encoder.h:180
Definition: aom_image.h:117
Codec context structure.
Definition: aom_codec.h:204
Codec control function to set the min quant matrix flatness.
Definition: aomcx.h:597
Codec control function to enable frame parallel decoding feature.
Definition: aomcx.h:337
int stride[4]
Definition: aom_image.h:174
#define AOM_IMG_FMT_HIGHBITDEPTH
Definition: aom_image.h:38
Codec control function to turn on / off dual filter enabling/disabling.
Definition: aomcx.h:717
Codec control function to set transfer function info.
Definition: aomcx.h:471
Definition: aom_image.h:60
Describes the decoder algorithm interface to applications.
Definition: aom_image.h:72
Codec control function to add film grain parameters (one of several preset types) info in the bitstre...
Definition: aomcx.h:851
aom_codec_err_t aom_codec_enc_config_default(aom_codec_iface_t *iface, aom_codec_enc_cfg_t *cfg, unsigned int reserved)
Get a default configuration.
Codec control function to set max data rate for Inter frames.
Definition: aomcx.h:257
Definition: aom_image.h:49
Image Descriptor.
Definition: aom_image.h:141
Definition: aom_image.h:121
double psnr[4]
Definition: aom_encoder.h:163
Codec control function to set number of tile columns.
Definition: aomcx.h:309
aom_image_t * aom_img_alloc(aom_image_t *img, aom_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
aom_fixed_buf_t raw
Definition: aom_encoder.h:165
Definition: aom_image.h:54
Definition: aom_image.h:88
aom_codec_err_t aom_codec_decode(aom_codec_ctx_t *ctx, const uint8_t *data, size_t data_sz, void *user_priv)
Decode data.
Definition: aom_image.h:70
const aom_codec_cx_pkt_t * aom_codec_get_cx_data(aom_codec_ctx_t *ctx, aom_codec_iter_t *iter)
Encoded data iterator.
Codec control function to encode with dist_8x8.
Definition: aomcx.h:664
aom_codec_err_t aom_codec_control_(aom_codec_ctx_t *ctx, int ctrl_id,...)
Control algorithm.
aom_codec_err_t aom_codec_encode(aom_codec_ctx_t *ctx, const aom_image_t *img, aom_codec_pts_t pts, unsigned long duration, aom_enc_frame_flags_t flags)
Encode a frame.
Sets the denoisers block size.
Definition: aomcx.h:861
Definition: aom_codec.h:225
Codec control function to set sharpness.
Definition: aomcx.h:190
Sets the noise level.
Definition: aomcx.h:858
#define aom_codec_dec_init(ctx, iface, cfg, flags)
Convenience macro for aom_codec_dec_init_ver()
Definition: aom_decoder.h:142
const char * aom_codec_iface_name(aom_codec_iface_t *iface)
Return the name for a given interface.
struct aom_rational g_timebase
Stream timebase units.
Definition: aom_encoder.h:327
Definition: aom_encoder.h:131
Definition: aom_image.h:134
aom_codec_err_t aom_codec_destroy(aom_codec_ctx_t *ctx)
Destroy a codec instance.
Definition: aom_encoder.h:129
Definition: aom_image.h:64
const char * aom_codec_err_to_string(aom_codec_err_t err)
Convert error number to printable string.
Codec control function to set minimum interval between GF/ARF frames.
Definition: aomcx.h:486
Definition: aom_image.h:53
Definition: aom_image.h:98
Definition: aom_image.h:111
enum aom_codec_cx_pkt_kind kind
Definition: aom_encoder.h:141
Codec control function to enable error_resilient_mode.
Definition: aomcx.h:347
Codec control function to encode with Loop Restoration Filter.
Definition: aomcx.h:558
Codec control function to set visual tuning.
Definition: aomcx.h:219
Definition: aom_codec.h:227
Codec control function to set the path to the film grain parameters.
Definition: aomcx.h:855
void aom_img_free(aom_image_t *img)
Close an image descriptor.
Definition: aom_image.h:95
Codec control function to set minimum interval between GF/ARF frames.
Definition: aomcx.h:492
Codec control function to turn on / off joint compound mode at sequence level.
Definition: aomcx.h:738
Sets the chroma subsampling y value.
Definition: aomcx.h:867
Definition: aom_image.h:74
Definition: aom_image.h:90
struct aom_codec_cx_pkt::@1::@2 frame
Definition: aom_encoder.h:187
Definition: aom_encoder.h:128
Definition: aom_image.h:110
Definition: aom_image.h:107
Sets the chroma subsampling x value.
Definition: aomcx.h:864
Codec control function to turn on / off ref frame mvs (mfmv) usage at sequence level.
Definition: aomcx.h:747
#define AOM_FRAME_IS_FRAGMENT
this is a fragment of the encoded frame
Definition: aom_encoder.h:103
Initialization Configurations.
Definition: aom_decoder.h:103
Codec control function to get last quantizer chosen by the encoder.
Definition: aomcx.h:207
Definition: aom_image.h:99
#define MAX_TILE_WIDTHS
Maximum number of tile widths in tile widths array.
Definition: aom_encoder.h:708
#define aom_codec_control(ctx, id, data)
aom_codec_control wrapper macro
Definition: aom_codec.h:414
#define MAX_TILE_HEIGHTS
Maximum number of tile heights in tile heights array.
Definition: aom_encoder.h:721
#define AOM_CODEC_USE_HIGHBITDEPTH
Make the encoder output one partition at a time.
Definition: aom_encoder.h:70
Definition: aom_image.h:89
Definition: aom_encoder.h:130
Definition: aom_encoder.h:196
Definition: aom_encoder.h:194
Codec control function to set lossless encoding mode.
Definition: aomcx.h:283
Definition: aom.h:65
Codec control function to set encoder internal speed settings.
Definition: aomcx.h:182
Definition: aomcx.h:289
Codec control function to set the delta q mode.
Definition: aomcx.h:821
Codec control function to set the filter strength for the arf.
Definition: aomcx.h:215
Definition: aom_image.h:93
Definition: aom_codec.h:237
Codec control function to enable automatic set and use alf frames.
Definition: aomcx.h:186
Definition: aom_image.h:109
Definition: aomdx.h:171
const void * aom_codec_iter_t
Iterator.
Definition: aom_codec.h:194
Definition: aomdx.h:177
Definition: aom_image.h:113
cfg_options_t cfg
Options defined per config file.
Definition: aom_encoder.h:733
Definition: aom_image.h:136
Definition: aom_image.h:97
Definition: aom_codec.h:238
Codec control function to set number of tile rows.
Definition: aomcx.h:325
aom_codec_err_t
Algorithm return codes.
Definition: aom_codec.h:101
const char * aom_codec_error(aom_codec_ctx_t *ctx)
Retrieve error synopsis for codec context.
Definition: aom_image.h:52
enum aom_chroma_sample_position aom_chroma_sample_position_t
List of chroma sample positions.
Definition: aom_image.h:94
Provides definitions for using AOM or AV1 within the aom Decoder interface.
Definition: aom_image.h:106
aom_fixed_buf_t twopass_stats
Definition: aom_encoder.h:158
Definition: aom_encoder.h:197
int den
Definition: aom_encoder.h:182
Codec control function to set content type.
Definition: aomcx.h:394
Codec control function to set the max quant matrix flatness.
Definition: aomcx.h:610
Definition: aom_image.h:63
Definition: aom_image.h:116
Codec control function to set color space info.
Definition: aomcx.h:423
aom_fixed_buf_t firstpass_mb_stats
Definition: aom_encoder.h:159
Definition: aom_image.h:120
Codec control function to set adaptive quantization mode.
Definition: aomcx.h:368
Encoder output packet.
Definition: aom_encoder.h:140
Definition: aom_image.h:118
Definition: aom_image.h:85
Definition: aom_image.h:84
int num
Definition: aom_encoder.h:181
Boost percentage for Golden Frame in CBR mode.
Definition: aomcx.h:270
Definition: aom_image.h:45
Definition: aom_image.h:67
Definition: aom_codec.h:226
Codec control function to set CDF update mode.
Definition: aomcx.h:401
Definition: aom_image.h:105
Codec control function to set transfer function info.
Definition: aomcx.h:449
const char * aom_codec_error_detail(aom_codec_ctx_t *ctx)
Retrieve detailed error information for codec context.
Codec control function to turn on / off frame superresolution.
Definition: aomcx.h:780
Definition: aom_codec.h:239
union aom_codec_cx_pkt::@1 data
Codec control function to set the threshold for MBs treated static.
Definition: aomcx.h:194
size_t sz
Definition: aom_encoder.h:78
Codec control function to set intended superblock size.
Definition: aomcx.h:529
unsigned char * planes[4]
Definition: aom_image.h:173
unsigned int d_w
Definition: aom_image.h:156
Definition: aom_image.h:61
Codec control function to enable/disable periodic Q boost.
Definition: aomcx.h:381
Definition: aom_encoder.h:188
Codec control function to set a maximum number of tile groups.
Definition: aomcx.h:673
Definition: aom_encoder.h:211
unsigned int g_h
Height of the frame.
Definition: aom_encoder.h:278
Definition: aom_image.h:43
aom_img_fmt_t fmt
Definition: aom_image.h:142
Definition: aom_image.h:71
Definition: aom_image.h:69
#define AOM_PLANE_Y
Definition: aom_image.h:169