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