• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 */
wrap_fread(void * ptr,size_t size,size_t nmemb,FILE * stream)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 
wrap_fwrite(const void * ptr,size_t size,size_t nmemb,FILE * stream)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 
warn_or_exit_on_errorv(aom_codec_ctx_t * ctx,int fatal,const char * s,va_list ap)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 
ctx_exit_on_error(aom_codec_ctx_t * ctx,const char * s,...)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 
warn_or_exit_on_error(aom_codec_ctx_t * ctx,int fatal,const char * s,...)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 
read_frame(struct AvxInputContext * input_ctx,aom_image_t * img)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 
file_is_y4m(const char detect[4])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 
fourcc_is_ivf(const char detect[4])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 static const arg_def_t limit =
148     ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
149 static const arg_def_t skip =
150     ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
151 static const arg_def_t good_dl =
152     ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
153 static const arg_def_t rt_dl =
154     ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
155 static const arg_def_t quietarg =
156     ARG_DEF("q", "quiet", 0, "Do not print encode progress");
157 static const arg_def_t verbosearg =
158     ARG_DEF("v", "verbose", 0, "Show encoder parameters");
159 static const arg_def_t psnrarg =
160     ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
161 static const arg_def_t use_cfg = ARG_DEF("c", "cfg", 1, "Config file to use");
162 
163 static const struct arg_enum_list test_decode_enum[] = {
164   { "off", TEST_DECODE_OFF },
165   { "fatal", TEST_DECODE_FATAL },
166   { "warn", TEST_DECODE_WARN },
167   { NULL, 0 }
168 };
169 static const arg_def_t recontest = ARG_DEF_ENUM(
170     NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
171 static const arg_def_t framerate =
172     ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
173 static const arg_def_t use_webm =
174     ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
175 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
176 static const arg_def_t use_obu = ARG_DEF(NULL, "obu", 0, "Output OBU");
177 static const arg_def_t q_hist_n =
178     ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
179 static const arg_def_t rate_hist_n =
180     ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
181 static const arg_def_t disable_warnings =
182     ARG_DEF(NULL, "disable-warnings", 0,
183             "Disable warnings about potentially incorrect encode settings.");
184 static const arg_def_t disable_warning_prompt =
185     ARG_DEF("y", "disable-warning-prompt", 0,
186             "Display warnings, but do not prompt user to continue.");
187 static const struct arg_enum_list bitdepth_enum[] = {
188   { "8", AOM_BITS_8 }, { "10", AOM_BITS_10 }, { "12", AOM_BITS_12 }, { NULL, 0 }
189 };
190 
191 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
192     "b", "bit-depth", 1,
193     "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
194     bitdepth_enum);
195 static const arg_def_t inbitdeptharg =
196     ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
197 
198 static const arg_def_t input_chroma_subsampling_x = ARG_DEF(
199     NULL, "input-chroma-subsampling-x", 1, "chroma subsampling x value.");
200 static const arg_def_t input_chroma_subsampling_y = ARG_DEF(
201     NULL, "input-chroma-subsampling-y", 1, "chroma subsampling y value.");
202 
203 static const arg_def_t *main_args[] = { &help,
204                                         &use_cfg,
205                                         &debugmode,
206                                         &outputfile,
207                                         &codecarg,
208                                         &passes,
209                                         &pass_arg,
210                                         &fpf_name,
211                                         &limit,
212                                         &skip,
213                                         &good_dl,
214                                         &rt_dl,
215                                         &quietarg,
216                                         &verbosearg,
217                                         &psnrarg,
218                                         &use_webm,
219                                         &use_ivf,
220                                         &use_obu,
221                                         &q_hist_n,
222                                         &rate_hist_n,
223                                         &disable_warnings,
224                                         &disable_warning_prompt,
225                                         &recontest,
226                                         NULL };
227 
228 static const arg_def_t usage =
229     ARG_DEF("u", "usage", 1, "Usage profile number to use");
230 static const arg_def_t threads =
231     ARG_DEF("t", "threads", 1, "Max number of threads to use");
232 static const arg_def_t profile =
233     ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
234 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
235 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
236 static const arg_def_t forced_max_frame_width = ARG_DEF(
237     NULL, "forced_max_frame_width", 1, "Maximum frame width value to force");
238 static const arg_def_t forced_max_frame_height = ARG_DEF(
239     NULL, "forced_max_frame_height", 1, "Maximum frame height value to force");
240 #if CONFIG_WEBM_IO
241 static const struct arg_enum_list stereo_mode_enum[] = {
242   { "mono", STEREO_FORMAT_MONO },
243   { "left-right", STEREO_FORMAT_LEFT_RIGHT },
244   { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
245   { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
246   { "right-left", STEREO_FORMAT_RIGHT_LEFT },
247   { NULL, 0 }
248 };
249 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
250     NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
251 #endif
252 static const arg_def_t timebase = ARG_DEF(
253     NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
254 static const arg_def_t global_error_resilient =
255     ARG_DEF(NULL, "global-error-resilient", 1,
256             "Enable global error resiliency features");
257 static const arg_def_t lag_in_frames =
258     ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
259 static const arg_def_t large_scale_tile = ARG_DEF(
260     NULL, "large-scale-tile", 1,
261     "Large scale tile coding (0: off (default), 1: on (ivf output only))");
262 static const arg_def_t monochrome =
263     ARG_DEF(NULL, "monochrome", 0, "Monochrome video (no chroma planes)");
264 static const arg_def_t full_still_picture_hdr = ARG_DEF(
265     NULL, "full-still-picture-hdr", 0, "Use full header for still picture");
266 
267 static const arg_def_t *global_args[] = { &use_yv12,
268                                           &use_i420,
269                                           &use_i422,
270                                           &use_i444,
271                                           &usage,
272                                           &threads,
273                                           &profile,
274                                           &width,
275                                           &height,
276                                           &forced_max_frame_width,
277                                           &forced_max_frame_height,
278 #if CONFIG_WEBM_IO
279                                           &stereo_mode,
280 #endif
281                                           &timebase,
282                                           &framerate,
283                                           &global_error_resilient,
284                                           &bitdeptharg,
285                                           &lag_in_frames,
286                                           &large_scale_tile,
287                                           &monochrome,
288                                           &full_still_picture_hdr,
289                                           NULL };
290 
291 static const arg_def_t dropframe_thresh =
292     ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
293 static const arg_def_t resize_mode =
294     ARG_DEF(NULL, "resize-mode", 1, "Frame resize mode");
295 static const arg_def_t resize_denominator =
296     ARG_DEF(NULL, "resize-denominator", 1, "Frame resize denominator");
297 static const arg_def_t resize_kf_denominator = ARG_DEF(
298     NULL, "resize-kf-denominator", 1, "Frame resize keyframe denominator");
299 static const arg_def_t superres_mode =
300     ARG_DEF(NULL, "superres-mode", 1, "Frame super-resolution mode");
301 static const arg_def_t superres_denominator = ARG_DEF(
302     NULL, "superres-denominator", 1, "Frame super-resolution denominator");
303 static const arg_def_t superres_kf_denominator =
304     ARG_DEF(NULL, "superres-kf-denominator", 1,
305             "Frame super-resolution keyframe denominator");
306 static const arg_def_t superres_qthresh = ARG_DEF(
307     NULL, "superres-qthresh", 1, "Frame super-resolution qindex threshold");
308 static const arg_def_t superres_kf_qthresh =
309     ARG_DEF(NULL, "superres-kf-qthresh", 1,
310             "Frame super-resolution keyframe qindex threshold");
311 static const struct arg_enum_list end_usage_enum[] = { { "vbr", AOM_VBR },
312                                                        { "cbr", AOM_CBR },
313                                                        { "cq", AOM_CQ },
314                                                        { "q", AOM_Q },
315                                                        { NULL, 0 } };
316 static const arg_def_t end_usage =
317     ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
318 static const arg_def_t target_bitrate =
319     ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
320 static const arg_def_t min_quantizer =
321     ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
322 static const arg_def_t max_quantizer =
323     ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
324 static const arg_def_t undershoot_pct =
325     ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
326 static const arg_def_t overshoot_pct =
327     ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
328 static const arg_def_t buf_sz =
329     ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
330 static const arg_def_t buf_initial_sz =
331     ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
332 static const arg_def_t buf_optimal_sz =
333     ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
334 static const arg_def_t *rc_args[] = { &dropframe_thresh,
335                                       &resize_mode,
336                                       &resize_denominator,
337                                       &resize_kf_denominator,
338                                       &superres_mode,
339                                       &superres_denominator,
340                                       &superres_kf_denominator,
341                                       &superres_qthresh,
342                                       &superres_kf_qthresh,
343                                       &end_usage,
344                                       &target_bitrate,
345                                       &min_quantizer,
346                                       &max_quantizer,
347                                       &undershoot_pct,
348                                       &overshoot_pct,
349                                       &buf_sz,
350                                       &buf_initial_sz,
351                                       &buf_optimal_sz,
352                                       NULL };
353 
354 static const arg_def_t bias_pct =
355     ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
356 static const arg_def_t minsection_pct =
357     ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
358 static const arg_def_t maxsection_pct =
359     ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
360 static const arg_def_t *rc_twopass_args[] = { &bias_pct, &minsection_pct,
361                                               &maxsection_pct, NULL };
362 static const arg_def_t fwd_kf_enabled =
363     ARG_DEF(NULL, "enable-fwd-kf", 1, "Enable forward reference keyframes");
364 static const arg_def_t kf_min_dist =
365     ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
366 static const arg_def_t kf_max_dist =
367     ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
368 static const arg_def_t kf_disabled =
369     ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
370 static const arg_def_t *kf_args[] = { &fwd_kf_enabled, &kf_min_dist,
371                                       &kf_max_dist, &kf_disabled, NULL };
372 static const arg_def_t sframe_dist =
373     ARG_DEF(NULL, "sframe-dist", 1, "S-Frame interval (frames)");
374 static const arg_def_t sframe_mode =
375     ARG_DEF(NULL, "sframe-mode", 1, "S-Frame insertion mode (1..2)");
376 static const arg_def_t save_as_annexb =
377     ARG_DEF(NULL, "annexb", 1, "Save as Annex-B");
378 static const arg_def_t noise_sens =
379     ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
380 static const arg_def_t sharpness =
381     ARG_DEF(NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
382 static const arg_def_t static_thresh =
383     ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
384 static const arg_def_t auto_altref =
385     ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
386 static const arg_def_t arnr_maxframes =
387     ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
388 static const arg_def_t arnr_strength =
389     ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
390 static const struct arg_enum_list tuning_enum[] = {
391   { "psnr", AOM_TUNE_PSNR },
392   { "ssim", AOM_TUNE_SSIM },
393   { "vmaf_with_preprocessing", AOM_TUNE_VMAF_WITH_PREPROCESSING },
394   { "vmaf_without_preprocessing", AOM_TUNE_VMAF_WITHOUT_PREPROCESSING },
395   { "vmaf", AOM_TUNE_VMAF_MAX_GAIN },
396   { NULL, 0 }
397 };
398 static const arg_def_t tune_metric =
399     ARG_DEF_ENUM(NULL, "tune", 1, "Distortion metric tuned with", tuning_enum);
400 static const arg_def_t cq_level =
401     ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
402 static const arg_def_t max_intra_rate_pct =
403     ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
404 
405 #if CONFIG_AV1_ENCODER
406 static const arg_def_t cpu_used_av1 =
407     ARG_DEF(NULL, "cpu-used", 1,
408             "Speed setting (0..6 in good mode, 6..8 in realtime mode)");
409 static const arg_def_t rowmtarg =
410     ARG_DEF(NULL, "row-mt", 1,
411             "Enable row based multi-threading (0: off, 1: on (default))");
412 static const arg_def_t tile_cols =
413     ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
414 static const arg_def_t tile_rows =
415     ARG_DEF(NULL, "tile-rows", 1, "Number of tile rows to use, log2");
416 static const arg_def_t enable_tpl_model =
417     ARG_DEF(NULL, "enable-tpl-model", 1,
418             "RDO based on frame temporal dependency "
419             "(0: off, 1: backward source based). "
420             "This is required for deltaq mode.");
421 static const arg_def_t enable_keyframe_filtering =
422     ARG_DEF(NULL, "enable-keyframe-filtering", 1,
423             "Apply temporal filtering on key frame "
424             "(0: false, 1: true (default)");
425 static const arg_def_t tile_width =
426     ARG_DEF(NULL, "tile-width", 1, "Tile widths (comma separated)");
427 static const arg_def_t tile_height =
428     ARG_DEF(NULL, "tile-height", 1, "Tile heights (command separated)");
429 static const arg_def_t lossless =
430     ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
431 static const arg_def_t enable_cdef =
432     ARG_DEF(NULL, "enable-cdef", 1,
433             "Enable the constrained directional enhancement filter (0: false, "
434             "1: true (default))");
435 static const arg_def_t enable_restoration = ARG_DEF(
436     NULL, "enable-restoration", 1,
437     "Enable the loop restoration filter (0: false (default in Realtime mode), "
438     "1: true (default in Non-realtime mode))");
439 static const arg_def_t enable_rect_partitions =
440     ARG_DEF(NULL, "enable-rect-partitions", 1,
441             "Enable rectangular partitions "
442             "(0: false, 1: true (default))");
443 static const arg_def_t enable_ab_partitions =
444     ARG_DEF(NULL, "enable-ab-partitions", 1,
445             "Enable ab partitions (0: false, 1: true (default))");
446 static const arg_def_t enable_1to4_partitions =
447     ARG_DEF(NULL, "enable-1to4-partitions", 1,
448             "Enable 1:4 and 4:1 partitions "
449             "(0: false, 1: true (default))");
450 static const arg_def_t min_partition_size =
451     ARG_DEF(NULL, "min-partition-size", 4,
452             "Set min partition size "
453             "(4:4x4, 8:8x8, 16:16x16, 32:32x32, 64:64x64, 128:128x128). "
454             "On frame with 4k+ resolutions or higher speed settings, the min "
455             "partition size will have a minimum of 8.");
456 static const arg_def_t max_partition_size =
457     ARG_DEF(NULL, "max-partition-size", 128,
458             "Set max partition size "
459             "(4:4x4, 8:8x8, 16:16x16, 32:32x32, 64:64x64, 128:128x128)");
460 static const arg_def_t enable_dual_filter =
461     ARG_DEF(NULL, "enable-dual-filter", 1,
462             "Enable dual filter "
463             "(0: false, 1: true (default))");
464 static const arg_def_t enable_chroma_deltaq =
465     ARG_DEF(NULL, "enable-chroma-deltaq", 1,
466             "Enable chroma delta quant "
467             "(0: false (default), 1: true)");
468 static const arg_def_t enable_intra_edge_filter =
469     ARG_DEF(NULL, "enable-intra-edge-filter", 1,
470             "Enable intra edge filtering "
471             "(0: false, 1: true (default))");
472 static const arg_def_t enable_order_hint =
473     ARG_DEF(NULL, "enable-order-hint", 1,
474             "Enable order hint "
475             "(0: false, 1: true (default))");
476 static const arg_def_t enable_tx64 =
477     ARG_DEF(NULL, "enable-tx64", 1,
478             "Enable 64-pt transform (0: false, 1: true (default))");
479 static const arg_def_t enable_flip_idtx =
480     ARG_DEF(NULL, "enable-flip-idtx", 1,
481             "Enable extended transform type (0: false, 1: true (default)) "
482             "including FLIPADST_DCT, DCT_FLIPADST, FLIPADST_FLIPADST, "
483             "ADST_FLIPADST, FLIPADST_ADST, IDTX, V_DCT, H_DCT, V_ADST, "
484             "H_ADST, V_FLIPADST, H_FLIPADST");
485 static const arg_def_t enable_dist_wtd_comp =
486     ARG_DEF(NULL, "enable-dist-wtd-comp", 1,
487             "Enable distance-weighted compound "
488             "(0: false, 1: true (default))");
489 static const arg_def_t enable_masked_comp =
490     ARG_DEF(NULL, "enable-masked-comp", 1,
491             "Enable masked (wedge/diff-wtd) compound "
492             "(0: false, 1: true (default))");
493 static const arg_def_t enable_onesided_comp =
494     ARG_DEF(NULL, "enable-onesided-comp", 1,
495             "Enable one sided compound "
496             "(0: false, 1: true (default))");
497 static const arg_def_t enable_interintra_comp =
498     ARG_DEF(NULL, "enable-interintra-comp", 1,
499             "Enable interintra compound "
500             "(0: false, 1: true (default))");
501 static const arg_def_t enable_smooth_interintra =
502     ARG_DEF(NULL, "enable-smooth-interintra", 1,
503             "Enable smooth interintra mode "
504             "(0: false, 1: true (default))");
505 static const arg_def_t enable_diff_wtd_comp =
506     ARG_DEF(NULL, "enable-diff-wtd-comp", 1,
507             "Enable difference-weighted compound "
508             "(0: false, 1: true (default))");
509 static const arg_def_t enable_interinter_wedge =
510     ARG_DEF(NULL, "enable-interinter-wedge", 1,
511             "Enable interinter wedge compound "
512             "(0: false, 1: true (default))");
513 static const arg_def_t enable_interintra_wedge =
514     ARG_DEF(NULL, "enable-interintra-wedge", 1,
515             "Enable interintra wedge compound "
516             "(0: false, 1: true (default))");
517 static const arg_def_t enable_global_motion =
518     ARG_DEF(NULL, "enable-global-motion", 1,
519             "Enable global motion "
520             "(0: false, 1: true (default))");
521 static const arg_def_t enable_warped_motion =
522     ARG_DEF(NULL, "enable-warped-motion", 1,
523             "Enable local warped motion "
524             "(0: false, 1: true (default))");
525 static const arg_def_t enable_filter_intra =
526     ARG_DEF(NULL, "enable-filter-intra", 1,
527             "Enable filter intra prediction mode "
528             "(0: false, 1: true (default))");
529 static const arg_def_t enable_smooth_intra =
530     ARG_DEF(NULL, "enable-smooth-intra", 1,
531             "Enable smooth intra prediction modes "
532             "(0: false, 1: true (default))");
533 static const arg_def_t enable_paeth_intra =
534     ARG_DEF(NULL, "enable-paeth-intra", 1,
535             "Enable Paeth intra prediction mode (0: false, 1: true (default))");
536 static const arg_def_t enable_cfl_intra =
537     ARG_DEF(NULL, "enable-cfl-intra", 1,
538             "Enable chroma from luma intra prediction mode "
539             "(0: false, 1: true (default))");
540 static const arg_def_t force_video_mode =
541     ARG_DEF(NULL, "force-video-mode", 1,
542             "Force video mode (0: false, 1: true (default))");
543 static const arg_def_t enable_obmc = ARG_DEF(
544     NULL, "enable-obmc", 1, "Enable OBMC (0: false, 1: true (default))");
545 static const arg_def_t enable_overlay =
546     ARG_DEF(NULL, "enable-overlay", 1,
547             "Enable coding overlay frames (0: false, 1: true (default))");
548 static const arg_def_t enable_palette =
549     ARG_DEF(NULL, "enable-palette", 1,
550             "Enable palette prediction mode (0: false, 1: true (default))");
551 static const arg_def_t enable_intrabc =
552     ARG_DEF(NULL, "enable-intrabc", 1,
553             "Enable intra block copy prediction mode "
554             "(0: false, 1: true (default))");
555 static const arg_def_t enable_angle_delta =
556     ARG_DEF(NULL, "enable-angle-delta", 1,
557             "Enable intra angle delta (0: false, 1: true (default))");
558 static const arg_def_t disable_trellis_quant =
559     ARG_DEF(NULL, "disable-trellis-quant", 1,
560             "Disable trellis optimization of quantized coefficients (0: false "
561             "1: true  2: true for rd search 3: true for estimate yrd serch "
562             "(default))");
563 static const arg_def_t enable_qm =
564     ARG_DEF(NULL, "enable-qm", 1,
565             "Enable quantisation matrices (0: false (default), 1: true)");
566 static const arg_def_t qm_min = ARG_DEF(
567     NULL, "qm-min", 1, "Min quant matrix flatness (0..15), default is 8");
568 static const arg_def_t qm_max = ARG_DEF(
569     NULL, "qm-max", 1, "Max quant matrix flatness (0..15), default is 15");
570 static const arg_def_t reduced_tx_type_set = ARG_DEF(
571     NULL, "reduced-tx-type-set", 1, "Use reduced set of transform types");
572 static const arg_def_t use_intra_dct_only =
573     ARG_DEF(NULL, "use-intra-dct-only", 1, "Use DCT only for INTRA modes");
574 static const arg_def_t use_inter_dct_only =
575     ARG_DEF(NULL, "use-inter-dct-only", 1, "Use DCT only for INTER modes");
576 static const arg_def_t use_intra_default_tx_only =
577     ARG_DEF(NULL, "use-intra-default-tx-only", 1,
578             "Use Default-transform only for INTRA modes");
579 static const arg_def_t quant_b_adapt =
580     ARG_DEF(NULL, "quant-b-adapt", 1, "Use adaptive quantize_b");
581 static const arg_def_t coeff_cost_upd_freq =
582     ARG_DEF(NULL, "coeff-cost-upd-freq", 1,
583             "Update freq for coeff costs"
584             "0: SB, 1: SB Row per Tile, 2: Tile");
585 static const arg_def_t mode_cost_upd_freq =
586     ARG_DEF(NULL, "mode-cost-upd-freq", 1,
587             "Update freq for mode costs"
588             "0: SB, 1: SB Row per Tile, 2: Tile");
589 static const arg_def_t mv_cost_upd_freq =
590     ARG_DEF(NULL, "mv-cost-upd-freq", 1,
591             "Update freq for mv costs"
592             "0: SB, 1: SB Row per Tile, 2: Tile, 3: Off");
593 static const arg_def_t num_tg = ARG_DEF(
594     NULL, "num-tile-groups", 1, "Maximum number of tile groups, default is 1");
595 static const arg_def_t mtu_size =
596     ARG_DEF(NULL, "mtu-size", 1,
597             "MTU size for a tile group, default is 0 (no MTU targeting), "
598             "overrides maximum number of tile groups");
599 static const struct arg_enum_list timing_info_enum[] = {
600   { "unspecified", AOM_TIMING_UNSPECIFIED },
601   { "constant", AOM_TIMING_EQUAL },
602   { "model", AOM_TIMING_DEC_MODEL },
603   { NULL, 0 }
604 };
605 static const arg_def_t timing_info =
606     ARG_DEF_ENUM(NULL, "timing-info", 1,
607                  "Signal timing info in the bitstream (model unly works for no "
608                  "hidden frames, no super-res yet):",
609                  timing_info_enum);
610 #if CONFIG_TUNE_VMAF
611 static const arg_def_t vmaf_model_path =
612     ARG_DEF(NULL, "vmaf-model-path", 1, "Path to the VMAF model file");
613 #endif
614 static const arg_def_t film_grain_test =
615     ARG_DEF(NULL, "film-grain-test", 1,
616             "Film grain test vectors (0: none (default), 1: test-1  2: test-2, "
617             "... 16: test-16)");
618 static const arg_def_t film_grain_table =
619     ARG_DEF(NULL, "film-grain-table", 1,
620             "Path to file containing film grain parameters");
621 #if CONFIG_DENOISE
622 static const arg_def_t denoise_noise_level =
623     ARG_DEF(NULL, "denoise-noise-level", 1,
624             "Amount of noise (from 0 = don't denoise, to 50)");
625 static const arg_def_t denoise_block_size =
626     ARG_DEF(NULL, "denoise-block-size", 1, "Denoise block size (default = 32)");
627 #endif
628 static const arg_def_t enable_ref_frame_mvs =
629     ARG_DEF(NULL, "enable-ref-frame-mvs", 1,
630             "Enable temporal mv prediction (default is 1)");
631 static const arg_def_t frame_parallel_decoding =
632     ARG_DEF(NULL, "frame-parallel", 1,
633             "Enable frame parallel decodability features "
634             "(0: false (default), 1: true)");
635 static const arg_def_t error_resilient_mode =
636     ARG_DEF(NULL, "error-resilient", 1,
637             "Enable error resilient features "
638             "(0: false (default), 1: true)");
639 static const arg_def_t aq_mode = ARG_DEF(
640     NULL, "aq-mode", 1,
641     "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
642     "3: cyclic refresh)");
643 static const arg_def_t deltaq_mode =
644     ARG_DEF(NULL, "deltaq-mode", 1,
645             "Delta qindex mode (0: off, 1: deltaq objective (default), "
646             "2: deltaq perceptual). "
647             "Currently this requires enable-tpl-model as a prerequisite.");
648 static const arg_def_t deltalf_mode = ARG_DEF(
649     NULL, "delta-lf-mode", 1, "Enable delta-lf-mode (0: off (default), 1: on)");
650 static const arg_def_t frame_periodic_boost =
651     ARG_DEF(NULL, "frame-boost", 1,
652             "Enable frame periodic boost (0: off (default), 1: on)");
653 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
654     NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
655 static const arg_def_t max_inter_rate_pct =
656     ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
657 static const arg_def_t min_gf_interval = ARG_DEF(
658     NULL, "min-gf-interval", 1,
659     "min gf/arf frame interval (default 0, indicating in-built behavior)");
660 static const arg_def_t max_gf_interval = ARG_DEF(
661     NULL, "max-gf-interval", 1,
662     "max gf/arf frame interval (default 0, indicating in-built behavior)");
663 static const arg_def_t gf_min_pyr_height =
664     ARG_DEF(NULL, "gf-min-pyr-height", 1,
665             "Min height for GF group pyramid structure (0 (default) to 5)");
666 static const arg_def_t gf_max_pyr_height =
667     ARG_DEF(NULL, "gf-max-pyr-height", 1,
668             "maximum height for GF group pyramid structure (0 to 5 (default))");
669 static const arg_def_t max_reference_frames = ARG_DEF(
670     NULL, "max-reference-frames", 1,
671     "maximum number of reference frames allowed per frame (3 to 7 (default))");
672 static const arg_def_t reduced_reference_set =
673     ARG_DEF(NULL, "reduced-reference-set", 1,
674             "Use reduced set of single and compound references (0: off "
675             "(default), 1: on)");
676 static const arg_def_t target_seq_level_idx =
677     ARG_DEF(NULL, "target-seq-level-idx", 1,
678             "Target sequence level index. "
679             "Possible values are in the form of \"ABxy\"(pad leading zeros if "
680             "less than 4 digits). "
681             "AB: Operating point(OP) index; "
682             "xy: Target level index for the OP. "
683             "E.g. \"0\" means target level index 0 for the 0th OP; "
684             "\"1021\" means target level index 21 for the 10th OP.");
685 static const arg_def_t set_min_cr =
686     ARG_DEF(NULL, "min-cr", 1,
687             "Set minimum compression ratio. Take integer values. Default is 0. "
688             "If non-zero, encoder will try to keep the compression ratio of "
689             "each frame to be higher than the given value divided by 100.");
690 
691 static const struct arg_enum_list color_primaries_enum[] = {
692   { "bt709", AOM_CICP_CP_BT_709 },
693   { "unspecified", AOM_CICP_CP_UNSPECIFIED },
694   { "bt601", AOM_CICP_CP_BT_601 },
695   { "bt470m", AOM_CICP_CP_BT_470_M },
696   { "bt470bg", AOM_CICP_CP_BT_470_B_G },
697   { "smpte240", AOM_CICP_CP_SMPTE_240 },
698   { "film", AOM_CICP_CP_GENERIC_FILM },
699   { "bt2020", AOM_CICP_CP_BT_2020 },
700   { "xyz", AOM_CICP_CP_XYZ },
701   { "smpte431", AOM_CICP_CP_SMPTE_431 },
702   { "smpte432", AOM_CICP_CP_SMPTE_432 },
703   { "ebu3213", AOM_CICP_CP_EBU_3213 },
704   { NULL, 0 }
705 };
706 
707 static const arg_def_t input_color_primaries = ARG_DEF_ENUM(
708     NULL, "color-primaries", 1,
709     "Color primaries (CICP) of input content:", color_primaries_enum);
710 
711 static const struct arg_enum_list transfer_characteristics_enum[] = {
712   { "unspecified", AOM_CICP_CP_UNSPECIFIED },
713   { "bt709", AOM_CICP_TC_BT_709 },
714   { "bt470m", AOM_CICP_TC_BT_470_M },
715   { "bt470bg", AOM_CICP_TC_BT_470_B_G },
716   { "bt601", AOM_CICP_TC_BT_601 },
717   { "smpte240", AOM_CICP_TC_SMPTE_240 },
718   { "lin", AOM_CICP_TC_LINEAR },
719   { "log100", AOM_CICP_TC_LOG_100 },
720   { "log100sq10", AOM_CICP_TC_LOG_100_SQRT10 },
721   { "iec61966", AOM_CICP_TC_IEC_61966 },
722   { "bt1361", AOM_CICP_TC_BT_1361 },
723   { "srgb", AOM_CICP_TC_SRGB },
724   { "bt2020-10bit", AOM_CICP_TC_BT_2020_10_BIT },
725   { "bt2020-12bit", AOM_CICP_TC_BT_2020_12_BIT },
726   { "smpte2084", AOM_CICP_TC_SMPTE_2084 },
727   { "hlg", AOM_CICP_TC_HLG },
728   { "smpte428", AOM_CICP_TC_SMPTE_428 },
729   { NULL, 0 }
730 };
731 
732 static const arg_def_t input_transfer_characteristics =
733     ARG_DEF_ENUM(NULL, "transfer-characteristics", 1,
734                  "Transfer characteristics (CICP) of input content:",
735                  transfer_characteristics_enum);
736 
737 static const struct arg_enum_list matrix_coefficients_enum[] = {
738   { "identity", AOM_CICP_MC_IDENTITY },
739   { "bt709", AOM_CICP_MC_BT_709 },
740   { "unspecified", AOM_CICP_MC_UNSPECIFIED },
741   { "fcc73", AOM_CICP_MC_FCC },
742   { "bt470bg", AOM_CICP_MC_BT_470_B_G },
743   { "bt601", AOM_CICP_MC_BT_601 },
744   { "smpte240", AOM_CICP_CP_SMPTE_240 },
745   { "ycgco", AOM_CICP_MC_SMPTE_YCGCO },
746   { "bt2020ncl", AOM_CICP_MC_BT_2020_NCL },
747   { "bt2020cl", AOM_CICP_MC_BT_2020_CL },
748   { "smpte2085", AOM_CICP_MC_SMPTE_2085 },
749   { "chromncl", AOM_CICP_MC_CHROMAT_NCL },
750   { "chromcl", AOM_CICP_MC_CHROMAT_CL },
751   { "ictcp", AOM_CICP_MC_ICTCP },
752   { NULL, 0 }
753 };
754 
755 static const arg_def_t input_matrix_coefficients = ARG_DEF_ENUM(
756     NULL, "matrix-coefficients", 1,
757     "Matrix coefficients (CICP) of input content:", matrix_coefficients_enum);
758 
759 static const struct arg_enum_list chroma_sample_position_enum[] = {
760   { "unknown", AOM_CSP_UNKNOWN },
761   { "vertical", AOM_CSP_VERTICAL },
762   { "colocated", AOM_CSP_COLOCATED },
763   { NULL, 0 }
764 };
765 
766 static const arg_def_t input_chroma_sample_position =
767     ARG_DEF_ENUM(NULL, "chroma-sample-position", 1,
768                  "The chroma sample position when chroma 4:2:0 is signaled:",
769                  chroma_sample_position_enum);
770 
771 static const struct arg_enum_list tune_content_enum[] = {
772   { "default", AOM_CONTENT_DEFAULT },
773   { "screen", AOM_CONTENT_SCREEN },
774   { NULL, 0 }
775 };
776 
777 static const arg_def_t tune_content = ARG_DEF_ENUM(
778     NULL, "tune-content", 1, "Tune content type", tune_content_enum);
779 
780 static const arg_def_t cdf_update_mode =
781     ARG_DEF(NULL, "cdf-update-mode", 1,
782             "CDF update mode for entropy coding "
783             "(0: no CDF update; 1: update CDF on all frames(default); "
784             "2: selectively update CDF on some frames");
785 
786 static const struct arg_enum_list superblock_size_enum[] = {
787   { "dynamic", AOM_SUPERBLOCK_SIZE_DYNAMIC },
788   { "64", AOM_SUPERBLOCK_SIZE_64X64 },
789   { "128", AOM_SUPERBLOCK_SIZE_128X128 },
790   { NULL, 0 }
791 };
792 static const arg_def_t superblock_size = ARG_DEF_ENUM(
793     NULL, "sb-size", 1, "Superblock size to use", superblock_size_enum);
794 
795 static const arg_def_t set_tier_mask =
796     ARG_DEF(NULL, "set-tier-mask", 1,
797             "Set bit mask to specify which tier each of the 32 possible "
798             "operating points conforms to. "
799             "Bit value 0(defualt): Main Tier; 1: High Tier.");
800 
801 static const arg_def_t use_fixed_qp_offsets =
802     ARG_DEF(NULL, "use-fixed-qp-offsets", 1,
803             "Enable fixed QP offsets for frames at different levels of the "
804             "pyramid. Selected automatically from --cq-level if "
805             "--fixed-qp-offsets is not provided. If this option is not "
806             "specified (default), offsets are adaptively chosen by the "
807             "encoder.");
808 
809 static const arg_def_t fixed_qp_offsets =
810     ARG_DEF(NULL, "fixed-qp-offsets", 1,
811             "Set fixed QP offsets for frames at different levels of the "
812             "pyramid. Comma-separated list of 5 offsets for keyframe, ALTREF, "
813             "and 3 levels of internal alt-refs. If this option is not "
814             "specified (default), offsets are adaptively chosen by the "
815             "encoder.");
816 
817 static const arg_def_t *av1_args[] = { &cpu_used_av1,
818                                        &auto_altref,
819                                        &sharpness,
820                                        &static_thresh,
821                                        &rowmtarg,
822                                        &tile_cols,
823                                        &tile_rows,
824                                        &enable_tpl_model,
825                                        &enable_keyframe_filtering,
826                                        &arnr_maxframes,
827                                        &arnr_strength,
828                                        &tune_metric,
829                                        &cq_level,
830                                        &max_intra_rate_pct,
831                                        &max_inter_rate_pct,
832                                        &gf_cbr_boost_pct,
833                                        &lossless,
834                                        &enable_cdef,
835                                        &enable_restoration,
836                                        &enable_rect_partitions,
837                                        &enable_ab_partitions,
838                                        &enable_1to4_partitions,
839                                        &min_partition_size,
840                                        &max_partition_size,
841                                        &enable_dual_filter,
842                                        &enable_chroma_deltaq,
843                                        &enable_intra_edge_filter,
844                                        &enable_order_hint,
845                                        &enable_tx64,
846                                        &enable_flip_idtx,
847                                        &enable_dist_wtd_comp,
848                                        &enable_masked_comp,
849                                        &enable_onesided_comp,
850                                        &enable_interintra_comp,
851                                        &enable_smooth_interintra,
852                                        &enable_diff_wtd_comp,
853                                        &enable_interinter_wedge,
854                                        &enable_interintra_wedge,
855                                        &enable_global_motion,
856                                        &enable_warped_motion,
857                                        &enable_filter_intra,
858                                        &enable_smooth_intra,
859                                        &enable_paeth_intra,
860                                        &enable_cfl_intra,
861                                        &force_video_mode,
862                                        &enable_obmc,
863                                        &enable_overlay,
864                                        &enable_palette,
865                                        &enable_intrabc,
866                                        &enable_angle_delta,
867                                        &disable_trellis_quant,
868                                        &enable_qm,
869                                        &qm_min,
870                                        &qm_max,
871                                        &reduced_tx_type_set,
872                                        &use_intra_dct_only,
873                                        &use_inter_dct_only,
874                                        &use_intra_default_tx_only,
875                                        &quant_b_adapt,
876                                        &coeff_cost_upd_freq,
877                                        &mode_cost_upd_freq,
878                                        &mv_cost_upd_freq,
879                                        &frame_parallel_decoding,
880                                        &error_resilient_mode,
881                                        &aq_mode,
882                                        &deltaq_mode,
883                                        &deltalf_mode,
884                                        &frame_periodic_boost,
885                                        &noise_sens,
886                                        &tune_content,
887                                        &cdf_update_mode,
888                                        &input_color_primaries,
889                                        &input_transfer_characteristics,
890                                        &input_matrix_coefficients,
891                                        &input_chroma_sample_position,
892                                        &min_gf_interval,
893                                        &max_gf_interval,
894                                        &gf_min_pyr_height,
895                                        &gf_max_pyr_height,
896                                        &superblock_size,
897                                        &num_tg,
898                                        &mtu_size,
899                                        &timing_info,
900                                        &film_grain_test,
901                                        &film_grain_table,
902 #if CONFIG_DENOISE
903                                        &denoise_noise_level,
904                                        &denoise_block_size,
905 #endif  // CONFIG_DENOISE
906                                        &max_reference_frames,
907                                        &reduced_reference_set,
908                                        &enable_ref_frame_mvs,
909                                        &target_seq_level_idx,
910                                        &set_tier_mask,
911                                        &set_min_cr,
912                                        &bitdeptharg,
913                                        &inbitdeptharg,
914                                        &input_chroma_subsampling_x,
915                                        &input_chroma_subsampling_y,
916                                        &sframe_dist,
917                                        &sframe_mode,
918                                        &save_as_annexb,
919 #if CONFIG_TUNE_VMAF
920                                        &vmaf_model_path,
921 #endif
922                                        NULL };
923 static const int av1_arg_ctrl_map[] = { AOME_SET_CPUUSED,
924                                         AOME_SET_ENABLEAUTOALTREF,
925                                         AOME_SET_SHARPNESS,
926                                         AOME_SET_STATIC_THRESHOLD,
927                                         AV1E_SET_ROW_MT,
928                                         AV1E_SET_TILE_COLUMNS,
929                                         AV1E_SET_TILE_ROWS,
930                                         AV1E_SET_ENABLE_TPL_MODEL,
931                                         AV1E_SET_ENABLE_KEYFRAME_FILTERING,
932                                         AOME_SET_ARNR_MAXFRAMES,
933                                         AOME_SET_ARNR_STRENGTH,
934                                         AOME_SET_TUNING,
935                                         AOME_SET_CQ_LEVEL,
936                                         AOME_SET_MAX_INTRA_BITRATE_PCT,
937                                         AV1E_SET_MAX_INTER_BITRATE_PCT,
938                                         AV1E_SET_GF_CBR_BOOST_PCT,
939                                         AV1E_SET_LOSSLESS,
940                                         AV1E_SET_ENABLE_CDEF,
941                                         AV1E_SET_ENABLE_RESTORATION,
942                                         AV1E_SET_ENABLE_RECT_PARTITIONS,
943                                         AV1E_SET_ENABLE_AB_PARTITIONS,
944                                         AV1E_SET_ENABLE_1TO4_PARTITIONS,
945                                         AV1E_SET_MIN_PARTITION_SIZE,
946                                         AV1E_SET_MAX_PARTITION_SIZE,
947                                         AV1E_SET_ENABLE_DUAL_FILTER,
948                                         AV1E_SET_ENABLE_CHROMA_DELTAQ,
949                                         AV1E_SET_ENABLE_INTRA_EDGE_FILTER,
950                                         AV1E_SET_ENABLE_ORDER_HINT,
951                                         AV1E_SET_ENABLE_TX64,
952                                         AV1E_SET_ENABLE_FLIP_IDTX,
953                                         AV1E_SET_ENABLE_DIST_WTD_COMP,
954                                         AV1E_SET_ENABLE_MASKED_COMP,
955                                         AV1E_SET_ENABLE_ONESIDED_COMP,
956                                         AV1E_SET_ENABLE_INTERINTRA_COMP,
957                                         AV1E_SET_ENABLE_SMOOTH_INTERINTRA,
958                                         AV1E_SET_ENABLE_DIFF_WTD_COMP,
959                                         AV1E_SET_ENABLE_INTERINTER_WEDGE,
960                                         AV1E_SET_ENABLE_INTERINTRA_WEDGE,
961                                         AV1E_SET_ENABLE_GLOBAL_MOTION,
962                                         AV1E_SET_ENABLE_WARPED_MOTION,
963                                         AV1E_SET_ENABLE_FILTER_INTRA,
964                                         AV1E_SET_ENABLE_SMOOTH_INTRA,
965                                         AV1E_SET_ENABLE_PAETH_INTRA,
966                                         AV1E_SET_ENABLE_CFL_INTRA,
967                                         AV1E_SET_FORCE_VIDEO_MODE,
968                                         AV1E_SET_ENABLE_OBMC,
969                                         AV1E_SET_ENABLE_OVERLAY,
970                                         AV1E_SET_ENABLE_PALETTE,
971                                         AV1E_SET_ENABLE_INTRABC,
972                                         AV1E_SET_ENABLE_ANGLE_DELTA,
973                                         AV1E_SET_DISABLE_TRELLIS_QUANT,
974                                         AV1E_SET_ENABLE_QM,
975                                         AV1E_SET_QM_MIN,
976                                         AV1E_SET_QM_MAX,
977                                         AV1E_SET_REDUCED_TX_TYPE_SET,
978                                         AV1E_SET_INTRA_DCT_ONLY,
979                                         AV1E_SET_INTER_DCT_ONLY,
980                                         AV1E_SET_INTRA_DEFAULT_TX_ONLY,
981                                         AV1E_SET_QUANT_B_ADAPT,
982                                         AV1E_SET_COEFF_COST_UPD_FREQ,
983                                         AV1E_SET_MODE_COST_UPD_FREQ,
984                                         AV1E_SET_MV_COST_UPD_FREQ,
985                                         AV1E_SET_FRAME_PARALLEL_DECODING,
986                                         AV1E_SET_ERROR_RESILIENT_MODE,
987                                         AV1E_SET_AQ_MODE,
988                                         AV1E_SET_DELTAQ_MODE,
989                                         AV1E_SET_DELTALF_MODE,
990                                         AV1E_SET_FRAME_PERIODIC_BOOST,
991                                         AV1E_SET_NOISE_SENSITIVITY,
992                                         AV1E_SET_TUNE_CONTENT,
993                                         AV1E_SET_CDF_UPDATE_MODE,
994                                         AV1E_SET_COLOR_PRIMARIES,
995                                         AV1E_SET_TRANSFER_CHARACTERISTICS,
996                                         AV1E_SET_MATRIX_COEFFICIENTS,
997                                         AV1E_SET_CHROMA_SAMPLE_POSITION,
998                                         AV1E_SET_MIN_GF_INTERVAL,
999                                         AV1E_SET_MAX_GF_INTERVAL,
1000                                         AV1E_SET_GF_MIN_PYRAMID_HEIGHT,
1001                                         AV1E_SET_GF_MAX_PYRAMID_HEIGHT,
1002                                         AV1E_SET_SUPERBLOCK_SIZE,
1003                                         AV1E_SET_NUM_TG,
1004                                         AV1E_SET_MTU,
1005                                         AV1E_SET_TIMING_INFO_TYPE,
1006                                         AV1E_SET_FILM_GRAIN_TEST_VECTOR,
1007                                         AV1E_SET_FILM_GRAIN_TABLE,
1008 #if CONFIG_DENOISE
1009                                         AV1E_SET_DENOISE_NOISE_LEVEL,
1010                                         AV1E_SET_DENOISE_BLOCK_SIZE,
1011 #endif  // CONFIG_DENOISE
1012                                         AV1E_SET_MAX_REFERENCE_FRAMES,
1013                                         AV1E_SET_REDUCED_REFERENCE_SET,
1014                                         AV1E_SET_ENABLE_REF_FRAME_MVS,
1015                                         AV1E_SET_TARGET_SEQ_LEVEL_IDX,
1016                                         AV1E_SET_TIER_MASK,
1017                                         AV1E_SET_MIN_CR,
1018 #if CONFIG_TUNE_VMAF
1019                                         AV1E_SET_VMAF_MODEL_PATH,
1020 #endif
1021                                         0 };
1022 #endif  // CONFIG_AV1_ENCODER
1023 
1024 static const arg_def_t *no_args[] = { NULL };
1025 
show_help(FILE * fout,int shorthelp)1026 static void show_help(FILE *fout, int shorthelp) {
1027   fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
1028           exec_name);
1029 
1030   if (shorthelp) {
1031     fprintf(fout, "Use --help to see the full list of options.\n");
1032     return;
1033   }
1034 
1035   fprintf(fout, "\nOptions:\n");
1036   arg_show_usage(fout, main_args);
1037   fprintf(fout, "\nEncoder Global Options:\n");
1038   arg_show_usage(fout, global_args);
1039   fprintf(fout, "\nRate Control Options:\n");
1040   arg_show_usage(fout, rc_args);
1041   fprintf(fout, "\nTwopass Rate Control Options:\n");
1042   arg_show_usage(fout, rc_twopass_args);
1043   fprintf(fout, "\nKeyframe Placement Options:\n");
1044   arg_show_usage(fout, kf_args);
1045 #if CONFIG_AV1_ENCODER
1046   fprintf(fout, "\nAV1 Specific Options:\n");
1047   arg_show_usage(fout, av1_args);
1048 #endif
1049   fprintf(fout,
1050           "\nStream timebase (--timebase):\n"
1051           "  The desired precision of timestamps in the output, expressed\n"
1052           "  in fractional seconds. Default is 1/1000.\n");
1053   fprintf(fout, "\nIncluded encoders:\n\n");
1054 
1055   const int num_encoder = get_aom_encoder_count();
1056   for (int i = 0; i < num_encoder; ++i) {
1057     const AvxInterface *const encoder = get_aom_encoder_by_index(i);
1058     const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
1059     fprintf(fout, "    %-6s - %s %s\n", encoder->name,
1060             aom_codec_iface_name(encoder->codec_interface()), defstr);
1061   }
1062   fprintf(fout, "\n        ");
1063   fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
1064 }
1065 
usage_exit(void)1066 void usage_exit(void) {
1067   show_help(stderr, 1);
1068   exit(EXIT_FAILURE);
1069 }
1070 
1071 #if CONFIG_AV1_ENCODER
1072 #define ARG_CTRL_CNT_MAX NELEMENTS(av1_arg_ctrl_map)
1073 #endif
1074 
1075 #if !CONFIG_WEBM_IO
1076 typedef int stereo_format_t;
1077 struct WebmOutputContext {
1078   int debug;
1079 };
1080 #endif
1081 
1082 /* Per-stream configuration */
1083 struct stream_config {
1084   struct aom_codec_enc_cfg cfg;
1085   const char *out_fn;
1086   const char *stats_fn;
1087   stereo_format_t stereo_fmt;
1088   int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1089   int arg_ctrl_cnt;
1090   int write_webm;
1091   const char *film_grain_filename;
1092   int write_ivf;
1093   // whether to use 16bit internal buffers
1094   int use_16bit_internal;
1095 #if CONFIG_TUNE_VMAF
1096   const char *vmaf_model_path;
1097 #endif
1098 };
1099 
1100 struct stream_state {
1101   int index;
1102   struct stream_state *next;
1103   struct stream_config config;
1104   FILE *file;
1105   struct rate_hist *rate_hist;
1106   struct WebmOutputContext webm_ctx;
1107   uint64_t psnr_sse_total;
1108   uint64_t psnr_samples_total;
1109   double psnr_totals[4];
1110   int psnr_count;
1111   int counts[64];
1112   aom_codec_ctx_t encoder;
1113   unsigned int frames_out;
1114   uint64_t cx_time;
1115   size_t nbytes;
1116   stats_io_t stats;
1117   struct aom_image *img;
1118   aom_codec_ctx_t decoder;
1119   int mismatch_seen;
1120   unsigned int chroma_subsampling_x;
1121   unsigned int chroma_subsampling_y;
1122 };
1123 
validate_positive_rational(const char * msg,struct aom_rational * rat)1124 static void validate_positive_rational(const char *msg,
1125                                        struct aom_rational *rat) {
1126   if (rat->den < 0) {
1127     rat->num *= -1;
1128     rat->den *= -1;
1129   }
1130 
1131   if (rat->num < 0) die("Error: %s must be positive\n", msg);
1132 
1133   if (!rat->den) die("Error: %s has zero denominator\n", msg);
1134 }
1135 
init_config(cfg_options_t * config)1136 static void init_config(cfg_options_t *config) {
1137   memset(config, 0, sizeof(cfg_options_t));
1138   config->super_block_size = 0;  // Dynamic
1139   config->max_partition_size = 128;
1140   config->min_partition_size = 4;
1141   config->disable_trellis_quant = 3;
1142 }
1143 
1144 /* Parses global config arguments into the AvxEncoderConfig. Note that
1145  * argv is modified and overwrites all parsed arguments.
1146  */
parse_global_config(struct AvxEncoderConfig * global,char *** argv)1147 static void parse_global_config(struct AvxEncoderConfig *global, char ***argv) {
1148   char **argi, **argj;
1149   struct arg arg;
1150   const int num_encoder = get_aom_encoder_count();
1151   char **argv_local = (char **)*argv;
1152   if (num_encoder < 1) die("Error: no valid encoder available\n");
1153 
1154   /* Initialize default parameters */
1155   memset(global, 0, sizeof(*global));
1156   global->codec = get_aom_encoder_by_index(num_encoder - 1);
1157   global->passes = 0;
1158   global->color_type = I420;
1159   global->csp = AOM_CSP_UNKNOWN;
1160 
1161   int cfg_included = 0;
1162   init_config(&global->encoder_config);
1163 
1164   for (argi = argj = argv_local; (*argj = *argi); argi += arg.argv_step) {
1165     arg.argv_step = 1;
1166 
1167     if (arg_match(&arg, &use_cfg, argi)) {
1168       if (cfg_included) continue;
1169       parse_cfg(arg.val, &global->encoder_config);
1170       cfg_included = 1;
1171       continue;
1172     }
1173     if (arg_match(&arg, &help, argi)) {
1174       show_help(stdout, 0);
1175       exit(EXIT_SUCCESS);
1176     } else if (arg_match(&arg, &codecarg, argi)) {
1177       global->codec = get_aom_encoder_by_name(arg.val);
1178       if (!global->codec)
1179         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
1180     } else if (arg_match(&arg, &passes, argi)) {
1181       global->passes = arg_parse_uint(&arg);
1182 
1183       if (global->passes < 1 || global->passes > 2)
1184         die("Error: Invalid number of passes (%d)\n", global->passes);
1185     } else if (arg_match(&arg, &pass_arg, argi)) {
1186       global->pass = arg_parse_uint(&arg);
1187 
1188       if (global->pass < 1 || global->pass > 2)
1189         die("Error: Invalid pass selected (%d)\n", global->pass);
1190     } else if (arg_match(&arg, &input_chroma_sample_position, argi)) {
1191       global->csp = arg_parse_enum(&arg);
1192       /* Flag is used by later code as well, preserve it. */
1193       argj++;
1194     } else if (arg_match(&arg, &usage, argi))
1195       global->usage = arg_parse_uint(&arg);
1196     else if (arg_match(&arg, &good_dl, argi))
1197       global->usage = AOM_USAGE_GOOD_QUALITY;  // Good quality usage
1198     else if (arg_match(&arg, &rt_dl, argi))
1199       global->usage = AOM_USAGE_REALTIME;  // Real-time usage
1200     else if (arg_match(&arg, &use_yv12, argi))
1201       global->color_type = YV12;
1202     else if (arg_match(&arg, &use_i420, argi))
1203       global->color_type = I420;
1204     else if (arg_match(&arg, &use_i422, argi))
1205       global->color_type = I422;
1206     else if (arg_match(&arg, &use_i444, argi))
1207       global->color_type = I444;
1208     else if (arg_match(&arg, &quietarg, argi))
1209       global->quiet = 1;
1210     else if (arg_match(&arg, &verbosearg, argi))
1211       global->verbose = 1;
1212     else if (arg_match(&arg, &limit, argi))
1213       global->limit = arg_parse_uint(&arg);
1214     else if (arg_match(&arg, &skip, argi))
1215       global->skip_frames = arg_parse_uint(&arg);
1216     else if (arg_match(&arg, &psnrarg, argi))
1217       global->show_psnr = 1;
1218     else if (arg_match(&arg, &recontest, argi))
1219       global->test_decode = arg_parse_enum_or_int(&arg);
1220     else if (arg_match(&arg, &framerate, argi)) {
1221       global->framerate = arg_parse_rational(&arg);
1222       validate_positive_rational(arg.name, &global->framerate);
1223       global->have_framerate = 1;
1224     } else if (arg_match(&arg, &debugmode, argi))
1225       global->debug = 1;
1226     else if (arg_match(&arg, &q_hist_n, argi))
1227       global->show_q_hist_buckets = arg_parse_uint(&arg);
1228     else if (arg_match(&arg, &rate_hist_n, argi))
1229       global->show_rate_hist_buckets = arg_parse_uint(&arg);
1230     else if (arg_match(&arg, &disable_warnings, argi))
1231       global->disable_warnings = 1;
1232     else if (arg_match(&arg, &disable_warning_prompt, argi))
1233       global->disable_warning_prompt = 1;
1234     else
1235       argj++;
1236   }
1237 
1238   if (global->pass) {
1239     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1240     if (global->pass > global->passes) {
1241       warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
1242            global->pass);
1243       global->passes = global->pass;
1244     }
1245   }
1246   /* Validate global config */
1247   if (global->passes == 0) {
1248 #if CONFIG_AV1_ENCODER
1249     // Make default AV1 passes = 2 until there is a better quality 1-pass
1250     // encoder
1251     if (global->codec != NULL && global->codec->name != NULL)
1252       global->passes = (strcmp(global->codec->name, "av1") == 0 &&
1253                         global->usage != AOM_USAGE_REALTIME)
1254                            ? 2
1255                            : 1;
1256 #else
1257     global->passes = 1;
1258 #endif
1259   }
1260 
1261   if (global->usage == AOM_USAGE_REALTIME && global->passes > 1) {
1262     warn("Enforcing one-pass encoding in realtime mode\n");
1263     global->passes = 1;
1264   }
1265 }
1266 
open_input_file(struct AvxInputContext * input,aom_chroma_sample_position_t csp)1267 static void open_input_file(struct AvxInputContext *input,
1268                             aom_chroma_sample_position_t csp) {
1269   /* Parse certain options from the input file, if possible */
1270   input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
1271                                              : set_binary_mode(stdin);
1272 
1273   if (!input->file) fatal("Failed to open input file");
1274 
1275   if (!fseeko(input->file, 0, SEEK_END)) {
1276     /* Input file is seekable. Figure out how long it is, so we can get
1277      * progress info.
1278      */
1279     input->length = ftello(input->file);
1280     rewind(input->file);
1281   }
1282 
1283   /* Default to 1:1 pixel aspect ratio. */
1284   input->pixel_aspect_ratio.numerator = 1;
1285   input->pixel_aspect_ratio.denominator = 1;
1286 
1287   /* For RAW input sources, these bytes will applied on the first frame
1288    *  in read_frame().
1289    */
1290   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1291   input->detect.position = 0;
1292 
1293   if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
1294     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4, csp,
1295                        input->only_i420) >= 0) {
1296       input->file_type = FILE_TYPE_Y4M;
1297       input->width = input->y4m.pic_w;
1298       input->height = input->y4m.pic_h;
1299       input->pixel_aspect_ratio.numerator = input->y4m.par_n;
1300       input->pixel_aspect_ratio.denominator = input->y4m.par_d;
1301       input->framerate.numerator = input->y4m.fps_n;
1302       input->framerate.denominator = input->y4m.fps_d;
1303       input->fmt = input->y4m.aom_fmt;
1304       input->bit_depth = input->y4m.bit_depth;
1305     } else
1306       fatal("Unsupported Y4M stream.");
1307   } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
1308     fatal("IVF is not supported as input.");
1309   } else {
1310     input->file_type = FILE_TYPE_RAW;
1311   }
1312 }
1313 
close_input_file(struct AvxInputContext * input)1314 static void close_input_file(struct AvxInputContext *input) {
1315   fclose(input->file);
1316   if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
1317 }
1318 
new_stream(struct AvxEncoderConfig * global,struct stream_state * prev)1319 static struct stream_state *new_stream(struct AvxEncoderConfig *global,
1320                                        struct stream_state *prev) {
1321   struct stream_state *stream;
1322 
1323   stream = calloc(1, sizeof(*stream));
1324   if (stream == NULL) {
1325     fatal("Failed to allocate new stream.");
1326   }
1327 
1328   if (prev) {
1329     memcpy(stream, prev, sizeof(*stream));
1330     stream->index++;
1331     prev->next = stream;
1332   } else {
1333     aom_codec_err_t res;
1334 
1335     /* Populate encoder configuration */
1336     res = aom_codec_enc_config_default(global->codec->codec_interface(),
1337                                        &stream->config.cfg, global->usage);
1338     if (res) fatal("Failed to get config: %s\n", aom_codec_err_to_string(res));
1339 
1340     /* Change the default timebase to a high enough value so that the
1341      * encoder will always create strictly increasing timestamps.
1342      */
1343     stream->config.cfg.g_timebase.den = 1000;
1344 
1345     /* Never use the library's default resolution, require it be parsed
1346      * from the file or set on the command line.
1347      */
1348     stream->config.cfg.g_w = 0;
1349     stream->config.cfg.g_h = 0;
1350 
1351     /* Initialize remaining stream parameters */
1352     stream->config.write_webm = 1;
1353     stream->config.write_ivf = 0;
1354 
1355 #if CONFIG_WEBM_IO
1356     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1357     stream->webm_ctx.last_pts_ns = -1;
1358     stream->webm_ctx.writer = NULL;
1359     stream->webm_ctx.segment = NULL;
1360 #endif
1361 
1362     /* Allows removal of the application version from the EBML tags */
1363     stream->webm_ctx.debug = global->debug;
1364     memcpy(&stream->config.cfg.encoder_cfg, &global->encoder_config,
1365            sizeof(stream->config.cfg.encoder_cfg));
1366   }
1367 
1368   /* Output files must be specified for each stream */
1369   stream->config.out_fn = NULL;
1370 
1371   stream->next = NULL;
1372   return stream;
1373 }
1374 
set_config_arg_ctrls(struct stream_config * config,int key,const struct arg * arg)1375 static void set_config_arg_ctrls(struct stream_config *config, int key,
1376                                  const struct arg *arg) {
1377   int j;
1378   if (key == AV1E_SET_FILM_GRAIN_TABLE) {
1379     config->film_grain_filename = arg->val;
1380     return;
1381   }
1382 
1383   // For target level, the settings should accumulate rather than overwrite,
1384   // so we simply append it.
1385   if (key == AV1E_SET_TARGET_SEQ_LEVEL_IDX) {
1386     j = config->arg_ctrl_cnt;
1387     assert(j < (int)ARG_CTRL_CNT_MAX);
1388     config->arg_ctrls[j][0] = key;
1389     config->arg_ctrls[j][1] = arg_parse_enum_or_int(arg);
1390     ++config->arg_ctrl_cnt;
1391     return;
1392   }
1393 
1394   /* Point either to the next free element or the first instance of this
1395    * control.
1396    */
1397   for (j = 0; j < config->arg_ctrl_cnt; j++)
1398     if (config->arg_ctrls[j][0] == key) break;
1399 
1400   /* Update/insert */
1401   assert(j < (int)ARG_CTRL_CNT_MAX);
1402   config->arg_ctrls[j][0] = key;
1403   config->arg_ctrls[j][1] = arg_parse_enum_or_int(arg);
1404 
1405   if (key == AOME_SET_ENABLEAUTOALTREF && config->arg_ctrls[j][1] > 1) {
1406     warn("auto-alt-ref > 1 is deprecated... setting auto-alt-ref=1\n");
1407     config->arg_ctrls[j][1] = 1;
1408   }
1409   if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1410 }
1411 
parse_stream_params(struct AvxEncoderConfig * global,struct stream_state * stream,char ** argv)1412 static int parse_stream_params(struct AvxEncoderConfig *global,
1413                                struct stream_state *stream, char **argv) {
1414   char **argi, **argj;
1415   struct arg arg;
1416   static const arg_def_t **ctrl_args = no_args;
1417   static const int *ctrl_args_map = NULL;
1418   struct stream_config *config = &stream->config;
1419   int eos_mark_found = 0;
1420   int webm_forced = 0;
1421 
1422   // Handle codec specific options
1423   if (0) {
1424 #if CONFIG_AV1_ENCODER
1425   } else if (strcmp(global->codec->name, "av1") == 0) {
1426     // TODO(jingning): Reuse AV1 specific encoder configuration parameters.
1427     // Consider to expand this set for AV1 encoder control.
1428     ctrl_args = av1_args;
1429     ctrl_args_map = av1_arg_ctrl_map;
1430 #endif
1431   }
1432 
1433   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1434     arg.argv_step = 1;
1435 
1436     /* Once we've found an end-of-stream marker (--) we want to continue
1437      * shifting arguments but not consuming them.
1438      */
1439     if (eos_mark_found) {
1440       argj++;
1441       continue;
1442     } else if (!strcmp(*argj, "--")) {
1443       eos_mark_found = 1;
1444       continue;
1445     }
1446 
1447     if (arg_match(&arg, &outputfile, argi)) {
1448       config->out_fn = arg.val;
1449       if (!webm_forced) {
1450         const size_t out_fn_len = strlen(config->out_fn);
1451         if (out_fn_len >= 4 &&
1452             !strcmp(config->out_fn + out_fn_len - 4, ".ivf")) {
1453           config->write_webm = 0;
1454           config->write_ivf = 1;
1455         } else if (out_fn_len >= 4 &&
1456                    !strcmp(config->out_fn + out_fn_len - 4, ".obu")) {
1457           config->write_webm = 0;
1458           config->write_ivf = 0;
1459         }
1460       }
1461     } else if (arg_match(&arg, &fpf_name, argi)) {
1462       config->stats_fn = arg.val;
1463     } else if (arg_match(&arg, &use_webm, argi)) {
1464 #if CONFIG_WEBM_IO
1465       config->write_webm = 1;
1466       webm_forced = 1;
1467 #else
1468       die("Error: --webm specified but webm is disabled.");
1469 #endif
1470     } else if (arg_match(&arg, &use_ivf, argi)) {
1471       config->write_webm = 0;
1472       config->write_ivf = 1;
1473     } else if (arg_match(&arg, &use_obu, argi)) {
1474       config->write_webm = 0;
1475       config->write_ivf = 0;
1476     } else if (arg_match(&arg, &threads, argi)) {
1477       config->cfg.g_threads = arg_parse_uint(&arg);
1478     } else if (arg_match(&arg, &profile, argi)) {
1479       config->cfg.g_profile = arg_parse_uint(&arg);
1480     } else if (arg_match(&arg, &width, argi)) {
1481       config->cfg.g_w = arg_parse_uint(&arg);
1482     } else if (arg_match(&arg, &height, argi)) {
1483       config->cfg.g_h = arg_parse_uint(&arg);
1484     } else if (arg_match(&arg, &forced_max_frame_width, argi)) {
1485       config->cfg.g_forced_max_frame_width = arg_parse_uint(&arg);
1486     } else if (arg_match(&arg, &forced_max_frame_height, argi)) {
1487       config->cfg.g_forced_max_frame_height = arg_parse_uint(&arg);
1488     } else if (arg_match(&arg, &bitdeptharg, argi)) {
1489       config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1490     } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1491       config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1492     } else if (arg_match(&arg, &input_chroma_subsampling_x, argi)) {
1493       stream->chroma_subsampling_x = arg_parse_uint(&arg);
1494     } else if (arg_match(&arg, &input_chroma_subsampling_y, argi)) {
1495       stream->chroma_subsampling_y = arg_parse_uint(&arg);
1496 #if CONFIG_WEBM_IO
1497     } else if (arg_match(&arg, &stereo_mode, argi)) {
1498       config->stereo_fmt = arg_parse_enum_or_int(&arg);
1499 #endif
1500     } else if (arg_match(&arg, &timebase, argi)) {
1501       config->cfg.g_timebase = arg_parse_rational(&arg);
1502       validate_positive_rational(arg.name, &config->cfg.g_timebase);
1503     } else if (arg_match(&arg, &global_error_resilient, argi)) {
1504       config->cfg.g_error_resilient = arg_parse_uint(&arg);
1505     } else if (arg_match(&arg, &lag_in_frames, argi)) {
1506       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1507       if (global->usage == AOM_USAGE_REALTIME &&
1508           config->cfg.rc_end_usage == AOM_CBR &&
1509           config->cfg.g_lag_in_frames != 0) {
1510         warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
1511         config->cfg.g_lag_in_frames = 0;
1512       }
1513     } else if (arg_match(&arg, &large_scale_tile, argi)) {
1514       config->cfg.large_scale_tile = arg_parse_uint(&arg);
1515       if (config->cfg.large_scale_tile) global->codec = get_aom_lst_encoder();
1516     } else if (arg_match(&arg, &monochrome, argi)) {
1517       config->cfg.monochrome = 1;
1518     } else if (arg_match(&arg, &full_still_picture_hdr, argi)) {
1519       config->cfg.full_still_picture_hdr = 1;
1520     } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1521       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1522     } else if (arg_match(&arg, &resize_mode, argi)) {
1523       config->cfg.rc_resize_mode = arg_parse_uint(&arg);
1524     } else if (arg_match(&arg, &resize_denominator, argi)) {
1525       config->cfg.rc_resize_denominator = arg_parse_uint(&arg);
1526     } else if (arg_match(&arg, &resize_kf_denominator, argi)) {
1527       config->cfg.rc_resize_kf_denominator = arg_parse_uint(&arg);
1528     } else if (arg_match(&arg, &superres_mode, argi)) {
1529       config->cfg.rc_superres_mode = arg_parse_uint(&arg);
1530     } else if (arg_match(&arg, &superres_denominator, argi)) {
1531       config->cfg.rc_superres_denominator = arg_parse_uint(&arg);
1532     } else if (arg_match(&arg, &superres_kf_denominator, argi)) {
1533       config->cfg.rc_superres_kf_denominator = arg_parse_uint(&arg);
1534     } else if (arg_match(&arg, &superres_qthresh, argi)) {
1535       config->cfg.rc_superres_qthresh = arg_parse_uint(&arg);
1536     } else if (arg_match(&arg, &superres_kf_qthresh, argi)) {
1537       config->cfg.rc_superres_kf_qthresh = arg_parse_uint(&arg);
1538     } else if (arg_match(&arg, &end_usage, argi)) {
1539       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1540     } else if (arg_match(&arg, &target_bitrate, argi)) {
1541       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1542     } else if (arg_match(&arg, &min_quantizer, argi)) {
1543       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1544     } else if (arg_match(&arg, &max_quantizer, argi)) {
1545       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1546     } else if (arg_match(&arg, &undershoot_pct, argi)) {
1547       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1548     } else if (arg_match(&arg, &overshoot_pct, argi)) {
1549       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1550     } else if (arg_match(&arg, &buf_sz, argi)) {
1551       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1552     } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1553       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1554     } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1555       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1556     } else if (arg_match(&arg, &bias_pct, argi)) {
1557       config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1558       if (global->passes < 2)
1559         warn("option %s ignored in one-pass mode.\n", arg.name);
1560     } else if (arg_match(&arg, &minsection_pct, argi)) {
1561       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1562 
1563       if (global->passes < 2)
1564         warn("option %s ignored in one-pass mode.\n", arg.name);
1565     } else if (arg_match(&arg, &maxsection_pct, argi)) {
1566       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1567 
1568       if (global->passes < 2)
1569         warn("option %s ignored in one-pass mode.\n", arg.name);
1570     } else if (arg_match(&arg, &fwd_kf_enabled, argi)) {
1571       config->cfg.fwd_kf_enabled = arg_parse_uint(&arg);
1572     } else if (arg_match(&arg, &kf_min_dist, argi)) {
1573       config->cfg.kf_min_dist = arg_parse_uint(&arg);
1574     } else if (arg_match(&arg, &kf_max_dist, argi)) {
1575       config->cfg.kf_max_dist = arg_parse_uint(&arg);
1576     } else if (arg_match(&arg, &kf_disabled, argi)) {
1577       config->cfg.kf_mode = AOM_KF_DISABLED;
1578     } else if (arg_match(&arg, &sframe_dist, argi)) {
1579       config->cfg.sframe_dist = arg_parse_uint(&arg);
1580     } else if (arg_match(&arg, &sframe_mode, argi)) {
1581       config->cfg.sframe_mode = arg_parse_uint(&arg);
1582     } else if (arg_match(&arg, &save_as_annexb, argi)) {
1583       config->cfg.save_as_annexb = arg_parse_uint(&arg);
1584     } else if (arg_match(&arg, &tile_width, argi)) {
1585       config->cfg.tile_width_count =
1586           arg_parse_list(&arg, config->cfg.tile_widths, MAX_TILE_WIDTHS);
1587     } else if (arg_match(&arg, &tile_height, argi)) {
1588       config->cfg.tile_height_count =
1589           arg_parse_list(&arg, config->cfg.tile_heights, MAX_TILE_HEIGHTS);
1590 #if CONFIG_TUNE_VMAF
1591     } else if (arg_match(&arg, &vmaf_model_path, argi)) {
1592       config->vmaf_model_path = arg.val;
1593 #endif
1594     } else if (arg_match(&arg, &use_fixed_qp_offsets, argi)) {
1595       config->cfg.use_fixed_qp_offsets = arg_parse_uint(&arg);
1596     } else if (arg_match(&arg, &fixed_qp_offsets, argi)) {
1597       const int fixed_qp_offset_count = arg_parse_list(
1598           &arg, config->cfg.fixed_qp_offsets, FIXED_QP_OFFSET_COUNT);
1599       if (fixed_qp_offset_count < FIXED_QP_OFFSET_COUNT) {
1600         die("Option --fixed_qp_offsets requires %d comma-separated values, but "
1601             "only %d values were provided.\n",
1602             FIXED_QP_OFFSET_COUNT, fixed_qp_offset_count);
1603       }
1604       config->cfg.use_fixed_qp_offsets = 1;
1605     } else if (global->usage == AOM_USAGE_REALTIME &&
1606                arg_match(&arg, &enable_restoration, argi)) {
1607       if (arg_parse_uint(&arg) == 1) {
1608         warn("non-zero %s option ignored in realtime mode.\n", arg.name);
1609       }
1610     } else {
1611       int i, match = 0;
1612       for (i = 0; ctrl_args[i]; i++) {
1613         if (arg_match(&arg, ctrl_args[i], argi)) {
1614           match = 1;
1615           if (ctrl_args_map) {
1616             set_config_arg_ctrls(config, ctrl_args_map[i], &arg);
1617           }
1618         }
1619       }
1620       if (!match) argj++;
1621     }
1622   }
1623   config->use_16bit_internal =
1624       config->cfg.g_bit_depth > AOM_BITS_8 || FORCE_HIGHBITDEPTH_DECODING;
1625   return eos_mark_found;
1626 }
1627 
1628 #define FOREACH_STREAM(iterator, list)                 \
1629   for (struct stream_state *iterator = list; iterator; \
1630        iterator = iterator->next)
1631 
validate_stream_config(const struct stream_state * stream,const struct AvxEncoderConfig * global)1632 static void validate_stream_config(const struct stream_state *stream,
1633                                    const struct AvxEncoderConfig *global) {
1634   const struct stream_state *streami;
1635   (void)global;
1636 
1637   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1638     fatal(
1639         "Stream %d: Specify stream dimensions with --width (-w) "
1640         " and --height (-h)",
1641         stream->index);
1642 
1643   /* Even if bit depth is set on the command line flag to be lower,
1644    * it is upgraded to at least match the input bit depth.
1645    */
1646   assert(stream->config.cfg.g_input_bit_depth <=
1647          (unsigned int)stream->config.cfg.g_bit_depth);
1648 
1649   for (streami = stream; streami; streami = streami->next) {
1650     /* All streams require output files */
1651     if (!streami->config.out_fn)
1652       fatal("Stream %d: Output file is required (specify with -o)",
1653             streami->index);
1654 
1655     /* Check for two streams outputting to the same file */
1656     if (streami != stream) {
1657       const char *a = stream->config.out_fn;
1658       const char *b = streami->config.out_fn;
1659       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1660         fatal("Stream %d: duplicate output file (from stream %d)",
1661               streami->index, stream->index);
1662     }
1663 
1664     /* Check for two streams sharing a stats file. */
1665     if (streami != stream) {
1666       const char *a = stream->config.stats_fn;
1667       const char *b = streami->config.stats_fn;
1668       if (a && b && !strcmp(a, b))
1669         fatal("Stream %d: duplicate stats file (from stream %d)",
1670               streami->index, stream->index);
1671     }
1672   }
1673 }
1674 
set_stream_dimensions(struct stream_state * stream,unsigned int w,unsigned int h)1675 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1676                                   unsigned int h) {
1677   if (!stream->config.cfg.g_w) {
1678     if (!stream->config.cfg.g_h)
1679       stream->config.cfg.g_w = w;
1680     else
1681       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1682   }
1683   if (!stream->config.cfg.g_h) {
1684     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1685   }
1686 }
1687 
file_type_to_string(enum VideoFileType t)1688 static const char *file_type_to_string(enum VideoFileType t) {
1689   switch (t) {
1690     case FILE_TYPE_RAW: return "RAW";
1691     case FILE_TYPE_Y4M: return "Y4M";
1692     default: return "Other";
1693   }
1694 }
1695 
image_format_to_string(aom_img_fmt_t f)1696 static const char *image_format_to_string(aom_img_fmt_t f) {
1697   switch (f) {
1698     case AOM_IMG_FMT_I420: return "I420";
1699     case AOM_IMG_FMT_I422: return "I422";
1700     case AOM_IMG_FMT_I444: return "I444";
1701     case AOM_IMG_FMT_YV12: return "YV12";
1702     case AOM_IMG_FMT_YV1216: return "YV1216";
1703     case AOM_IMG_FMT_I42016: return "I42016";
1704     case AOM_IMG_FMT_I42216: return "I42216";
1705     case AOM_IMG_FMT_I44416: return "I44416";
1706     default: return "Other";
1707   }
1708 }
1709 
show_stream_config(struct stream_state * stream,struct AvxEncoderConfig * global,struct AvxInputContext * input)1710 static void show_stream_config(struct stream_state *stream,
1711                                struct AvxEncoderConfig *global,
1712                                struct AvxInputContext *input) {
1713 #define SHOW(field) \
1714   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
1715 
1716   if (stream->index == 0) {
1717     fprintf(stderr, "Codec: %s\n",
1718             aom_codec_iface_name(global->codec->codec_interface()));
1719     fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1720             input->filename, file_type_to_string(input->file_type),
1721             image_format_to_string(input->fmt));
1722   }
1723   if (stream->next || stream->index)
1724     fprintf(stderr, "\nStream Index: %d\n", stream->index);
1725   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1726   fprintf(stderr, "Coding path: %s\n",
1727           stream->config.use_16bit_internal ? "HBD" : "LBD");
1728   fprintf(stderr, "Encoder parameters:\n");
1729 
1730   SHOW(g_usage);
1731   SHOW(g_threads);
1732   SHOW(g_profile);
1733   SHOW(g_w);
1734   SHOW(g_h);
1735   SHOW(g_bit_depth);
1736   SHOW(g_input_bit_depth);
1737   SHOW(g_timebase.num);
1738   SHOW(g_timebase.den);
1739   SHOW(g_error_resilient);
1740   SHOW(g_pass);
1741   SHOW(g_lag_in_frames);
1742   SHOW(large_scale_tile);
1743   SHOW(rc_dropframe_thresh);
1744   SHOW(rc_resize_mode);
1745   SHOW(rc_resize_denominator);
1746   SHOW(rc_resize_kf_denominator);
1747   SHOW(rc_superres_mode);
1748   SHOW(rc_superres_denominator);
1749   SHOW(rc_superres_kf_denominator);
1750   SHOW(rc_superres_qthresh);
1751   SHOW(rc_superres_kf_qthresh);
1752   SHOW(rc_end_usage);
1753   SHOW(rc_target_bitrate);
1754   SHOW(rc_min_quantizer);
1755   SHOW(rc_max_quantizer);
1756   SHOW(rc_undershoot_pct);
1757   SHOW(rc_overshoot_pct);
1758   SHOW(rc_buf_sz);
1759   SHOW(rc_buf_initial_sz);
1760   SHOW(rc_buf_optimal_sz);
1761   SHOW(rc_2pass_vbr_bias_pct);
1762   SHOW(rc_2pass_vbr_minsection_pct);
1763   SHOW(rc_2pass_vbr_maxsection_pct);
1764   SHOW(fwd_kf_enabled);
1765   SHOW(kf_mode);
1766   SHOW(kf_min_dist);
1767   SHOW(kf_max_dist);
1768 
1769 #define SHOW_PARAMS(field)                    \
1770   fprintf(stderr, "    %-28s = %d\n", #field, \
1771           stream->config.cfg.encoder_cfg.field)
1772   SHOW_PARAMS(super_block_size);
1773   SHOW_PARAMS(max_partition_size);
1774   SHOW_PARAMS(min_partition_size);
1775   SHOW_PARAMS(disable_ab_partition_type);
1776   SHOW_PARAMS(disable_rect_partition_type);
1777   SHOW_PARAMS(disable_1to4_partition_type);
1778   SHOW_PARAMS(disable_flip_idtx);
1779   SHOW_PARAMS(disable_cdef);
1780   SHOW_PARAMS(disable_lr);
1781   SHOW_PARAMS(disable_obmc);
1782   SHOW_PARAMS(disable_warp_motion);
1783   SHOW_PARAMS(disable_global_motion);
1784   SHOW_PARAMS(disable_dist_wtd_comp);
1785   SHOW_PARAMS(disable_diff_wtd_comp);
1786   SHOW_PARAMS(disable_inter_intra_comp);
1787   SHOW_PARAMS(disable_masked_comp);
1788   SHOW_PARAMS(disable_one_sided_comp);
1789   SHOW_PARAMS(disable_palette);
1790   SHOW_PARAMS(disable_intrabc);
1791   SHOW_PARAMS(disable_cfl);
1792   SHOW_PARAMS(disable_smooth_intra);
1793   SHOW_PARAMS(disable_filter_intra);
1794   SHOW_PARAMS(disable_dual_filter);
1795   SHOW_PARAMS(disable_intra_angle_delta);
1796   SHOW_PARAMS(disable_intra_edge_filter);
1797   SHOW_PARAMS(disable_tx_64x64);
1798   SHOW_PARAMS(disable_smooth_inter_intra);
1799   SHOW_PARAMS(disable_inter_inter_wedge);
1800   SHOW_PARAMS(disable_inter_intra_wedge);
1801   SHOW_PARAMS(disable_paeth_intra);
1802   SHOW_PARAMS(disable_trellis_quant);
1803   SHOW_PARAMS(disable_ref_frame_mv);
1804   SHOW_PARAMS(reduced_reference_set);
1805   SHOW_PARAMS(reduced_tx_type_set);
1806 }
1807 
open_output_file(struct stream_state * stream,struct AvxEncoderConfig * global,const struct AvxRational * pixel_aspect_ratio)1808 static void open_output_file(struct stream_state *stream,
1809                              struct AvxEncoderConfig *global,
1810                              const struct AvxRational *pixel_aspect_ratio) {
1811   const char *fn = stream->config.out_fn;
1812   const struct aom_codec_enc_cfg *const cfg = &stream->config.cfg;
1813 
1814   if (cfg->g_pass == AOM_RC_FIRST_PASS) return;
1815 
1816   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1817 
1818   if (!stream->file) fatal("Failed to open output file");
1819 
1820   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1821     fatal("WebM output to pipes not supported.");
1822 
1823 #if CONFIG_WEBM_IO
1824   if (stream->config.write_webm) {
1825     stream->webm_ctx.stream = stream->file;
1826     if (write_webm_file_header(&stream->webm_ctx, &stream->encoder, cfg,
1827                                stream->config.stereo_fmt, global->codec->fourcc,
1828                                pixel_aspect_ratio) != 0) {
1829       fatal("WebM writer initialization failed.");
1830     }
1831   }
1832 #else
1833   (void)pixel_aspect_ratio;
1834 #endif
1835 
1836   if (!stream->config.write_webm && stream->config.write_ivf) {
1837     ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1838   }
1839 }
1840 
close_output_file(struct stream_state * stream,unsigned int fourcc)1841 static void close_output_file(struct stream_state *stream,
1842                               unsigned int fourcc) {
1843   const struct aom_codec_enc_cfg *const cfg = &stream->config.cfg;
1844 
1845   if (cfg->g_pass == AOM_RC_FIRST_PASS) return;
1846 
1847 #if CONFIG_WEBM_IO
1848   if (stream->config.write_webm) {
1849     if (write_webm_file_footer(&stream->webm_ctx) != 0) {
1850       fatal("WebM writer finalization failed.");
1851     }
1852   }
1853 #endif
1854 
1855   if (!stream->config.write_webm && stream->config.write_ivf) {
1856     if (!fseek(stream->file, 0, SEEK_SET))
1857       ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1858                             stream->frames_out);
1859   }
1860 
1861   fclose(stream->file);
1862 }
1863 
setup_pass(struct stream_state * stream,struct AvxEncoderConfig * global,int pass)1864 static void setup_pass(struct stream_state *stream,
1865                        struct AvxEncoderConfig *global, int pass) {
1866   if (stream->config.stats_fn) {
1867     if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1868       fatal("Failed to open statistics store");
1869   } else {
1870     if (!stats_open_mem(&stream->stats, pass))
1871       fatal("Failed to open statistics store");
1872   }
1873 
1874   stream->config.cfg.g_pass = global->passes == 2
1875                                   ? pass ? AOM_RC_LAST_PASS : AOM_RC_FIRST_PASS
1876                                   : AOM_RC_ONE_PASS;
1877   if (pass) {
1878     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1879   }
1880 
1881   stream->cx_time = 0;
1882   stream->nbytes = 0;
1883   stream->frames_out = 0;
1884 }
1885 
initialize_encoder(struct stream_state * stream,struct AvxEncoderConfig * global)1886 static void initialize_encoder(struct stream_state *stream,
1887                                struct AvxEncoderConfig *global) {
1888   int i;
1889   int flags = 0;
1890 
1891   flags |= global->show_psnr ? AOM_CODEC_USE_PSNR : 0;
1892   flags |= stream->config.use_16bit_internal ? AOM_CODEC_USE_HIGHBITDEPTH : 0;
1893 
1894   /* Construct Encoder Context */
1895   aom_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1896                      &stream->config.cfg, flags);
1897   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1898 
1899   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1900     int ctrl = stream->config.arg_ctrls[i][0];
1901     int value = stream->config.arg_ctrls[i][1];
1902     if (aom_codec_control(&stream->encoder, ctrl, value))
1903       fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1904 
1905     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1906   }
1907 
1908 #if CONFIG_TUNE_VMAF
1909   if (stream->config.vmaf_model_path) {
1910     AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder, AV1E_SET_VMAF_MODEL_PATH,
1911                                   stream->config.vmaf_model_path);
1912   }
1913 #endif
1914 
1915   if (stream->config.film_grain_filename) {
1916     AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder, AV1E_SET_FILM_GRAIN_TABLE,
1917                                   stream->config.film_grain_filename);
1918   }
1919 
1920 #if CONFIG_AV1_DECODER
1921   if (global->test_decode != TEST_DECODE_OFF) {
1922     const AvxInterface *decoder = get_aom_decoder_by_name(global->codec->name);
1923     aom_codec_dec_cfg_t cfg = { 0, 0, 0, !FORCE_HIGHBITDEPTH_DECODING };
1924     aom_codec_dec_init(&stream->decoder, decoder->codec_interface(), &cfg, 0);
1925 
1926     if (strcmp(global->codec->name, "av1") == 0) {
1927       AOM_CODEC_CONTROL_TYPECHECKED(&stream->decoder, AV1_SET_TILE_MODE,
1928                                     stream->config.cfg.large_scale_tile);
1929       ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_mode");
1930 
1931       AOM_CODEC_CONTROL_TYPECHECKED(&stream->decoder, AV1D_SET_IS_ANNEXB,
1932                                     stream->config.cfg.save_as_annexb);
1933       ctx_exit_on_error(&stream->decoder, "Failed to set is_annexb");
1934 
1935       AOM_CODEC_CONTROL_TYPECHECKED(&stream->decoder, AV1_SET_DECODE_TILE_ROW,
1936                                     -1);
1937       ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_row");
1938 
1939       AOM_CODEC_CONTROL_TYPECHECKED(&stream->decoder, AV1_SET_DECODE_TILE_COL,
1940                                     -1);
1941       ctx_exit_on_error(&stream->decoder, "Failed to set decode_tile_col");
1942     }
1943   }
1944 #endif
1945 }
1946 
encode_frame(struct stream_state * stream,struct AvxEncoderConfig * global,struct aom_image * img,unsigned int frames_in)1947 static void encode_frame(struct stream_state *stream,
1948                          struct AvxEncoderConfig *global, struct aom_image *img,
1949                          unsigned int frames_in) {
1950   aom_codec_pts_t frame_start, next_frame_start;
1951   struct aom_codec_enc_cfg *cfg = &stream->config.cfg;
1952   struct aom_usec_timer timer;
1953 
1954   frame_start =
1955       (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1956       cfg->g_timebase.num / global->framerate.num;
1957   next_frame_start =
1958       (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1959       cfg->g_timebase.num / global->framerate.num;
1960 
1961   /* Scale if necessary */
1962   if (img) {
1963     if ((img->fmt & AOM_IMG_FMT_HIGHBITDEPTH) &&
1964         (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1965       if (img->fmt != AOM_IMG_FMT_I42016) {
1966         fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1967         exit(EXIT_FAILURE);
1968       }
1969 #if CONFIG_LIBYUV
1970       if (!stream->img) {
1971         stream->img =
1972             aom_img_alloc(NULL, AOM_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1973       }
1974       I420Scale_16(
1975           (uint16_t *)img->planes[AOM_PLANE_Y], img->stride[AOM_PLANE_Y] / 2,
1976           (uint16_t *)img->planes[AOM_PLANE_U], img->stride[AOM_PLANE_U] / 2,
1977           (uint16_t *)img->planes[AOM_PLANE_V], img->stride[AOM_PLANE_V] / 2,
1978           img->d_w, img->d_h, (uint16_t *)stream->img->planes[AOM_PLANE_Y],
1979           stream->img->stride[AOM_PLANE_Y] / 2,
1980           (uint16_t *)stream->img->planes[AOM_PLANE_U],
1981           stream->img->stride[AOM_PLANE_U] / 2,
1982           (uint16_t *)stream->img->planes[AOM_PLANE_V],
1983           stream->img->stride[AOM_PLANE_V] / 2, stream->img->d_w,
1984           stream->img->d_h, kFilterBox);
1985       img = stream->img;
1986 #else
1987       stream->encoder.err = 1;
1988       ctx_exit_on_error(&stream->encoder,
1989                         "Stream %d: Failed to encode frame.\n"
1990                         "libyuv is required for scaling but is currently "
1991                         "disabled.\n"
1992                         "Be sure to specify -DCONFIG_LIBYUV=1 when running "
1993                         "cmake.\n",
1994                         stream->index);
1995 #endif
1996     }
1997   }
1998   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1999     if (img->fmt != AOM_IMG_FMT_I420 && img->fmt != AOM_IMG_FMT_YV12) {
2000       fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
2001       exit(EXIT_FAILURE);
2002     }
2003 #if CONFIG_LIBYUV
2004     if (!stream->img)
2005       stream->img =
2006           aom_img_alloc(NULL, AOM_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
2007     I420Scale(
2008         img->planes[AOM_PLANE_Y], img->stride[AOM_PLANE_Y],
2009         img->planes[AOM_PLANE_U], img->stride[AOM_PLANE_U],
2010         img->planes[AOM_PLANE_V], img->stride[AOM_PLANE_V], img->d_w, img->d_h,
2011         stream->img->planes[AOM_PLANE_Y], stream->img->stride[AOM_PLANE_Y],
2012         stream->img->planes[AOM_PLANE_U], stream->img->stride[AOM_PLANE_U],
2013         stream->img->planes[AOM_PLANE_V], stream->img->stride[AOM_PLANE_V],
2014         stream->img->d_w, stream->img->d_h, kFilterBox);
2015     img = stream->img;
2016 #else
2017     stream->encoder.err = 1;
2018     ctx_exit_on_error(&stream->encoder,
2019                       "Stream %d: Failed to encode frame.\n"
2020                       "Scaling disabled in this configuration. \n"
2021                       "To enable, configure with --enable-libyuv\n",
2022                       stream->index);
2023 #endif
2024   }
2025 
2026   aom_usec_timer_start(&timer);
2027   aom_codec_encode(&stream->encoder, img, frame_start,
2028                    (uint32_t)(next_frame_start - frame_start), 0);
2029   aom_usec_timer_mark(&timer);
2030   stream->cx_time += aom_usec_timer_elapsed(&timer);
2031   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2032                     stream->index);
2033 }
2034 
update_quantizer_histogram(struct stream_state * stream)2035 static void update_quantizer_histogram(struct stream_state *stream) {
2036   if (stream->config.cfg.g_pass != AOM_RC_FIRST_PASS) {
2037     int q;
2038 
2039     AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder, AOME_GET_LAST_QUANTIZER_64,
2040                                   &q);
2041     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2042     stream->counts[q]++;
2043   }
2044 }
2045 
get_cx_data(struct stream_state * stream,struct AvxEncoderConfig * global,int * got_data)2046 static void get_cx_data(struct stream_state *stream,
2047                         struct AvxEncoderConfig *global, int *got_data) {
2048   const aom_codec_cx_pkt_t *pkt;
2049   const struct aom_codec_enc_cfg *cfg = &stream->config.cfg;
2050   aom_codec_iter_t iter = NULL;
2051 
2052   *got_data = 0;
2053   while ((pkt = aom_codec_get_cx_data(&stream->encoder, &iter))) {
2054     static size_t fsize = 0;
2055     static FileOffset ivf_header_pos = 0;
2056 
2057     switch (pkt->kind) {
2058       case AOM_CODEC_CX_FRAME_PKT:
2059         ++stream->frames_out;
2060         if (!global->quiet)
2061           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
2062 
2063         update_rate_histogram(stream->rate_hist, cfg, pkt);
2064 #if CONFIG_WEBM_IO
2065         if (stream->config.write_webm) {
2066           if (write_webm_block(&stream->webm_ctx, cfg, pkt) != 0) {
2067             fatal("WebM writer failed.");
2068           }
2069         }
2070 #endif
2071         if (!stream->config.write_webm) {
2072           if (stream->config.write_ivf) {
2073             if (pkt->data.frame.partition_id <= 0) {
2074               ivf_header_pos = ftello(stream->file);
2075               fsize = pkt->data.frame.sz;
2076 
2077               ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
2078             } else {
2079               fsize += pkt->data.frame.sz;
2080 
2081               const FileOffset currpos = ftello(stream->file);
2082               fseeko(stream->file, ivf_header_pos, SEEK_SET);
2083               ivf_write_frame_size(stream->file, fsize);
2084               fseeko(stream->file, currpos, SEEK_SET);
2085             }
2086           }
2087 
2088           (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2089                        stream->file);
2090         }
2091         stream->nbytes += pkt->data.raw.sz;
2092 
2093         *got_data = 1;
2094 #if CONFIG_AV1_DECODER
2095         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
2096           aom_codec_decode(&stream->decoder, pkt->data.frame.buf,
2097                            pkt->data.frame.sz, NULL);
2098           if (stream->decoder.err) {
2099             warn_or_exit_on_error(&stream->decoder,
2100                                   global->test_decode == TEST_DECODE_FATAL,
2101                                   "Failed to decode frame %d in stream %d",
2102                                   stream->frames_out + 1, stream->index);
2103             stream->mismatch_seen = stream->frames_out + 1;
2104           }
2105         }
2106 #endif
2107         break;
2108       case AOM_CODEC_STATS_PKT:
2109         stream->frames_out++;
2110         stats_write(&stream->stats, pkt->data.twopass_stats.buf,
2111                     pkt->data.twopass_stats.sz);
2112         stream->nbytes += pkt->data.raw.sz;
2113         break;
2114       case AOM_CODEC_PSNR_PKT:
2115 
2116         if (global->show_psnr) {
2117           int i;
2118 
2119           stream->psnr_sse_total += pkt->data.psnr.sse[0];
2120           stream->psnr_samples_total += pkt->data.psnr.samples[0];
2121           for (i = 0; i < 4; i++) {
2122             if (!global->quiet)
2123               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
2124             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2125           }
2126           stream->psnr_count++;
2127         }
2128 
2129         break;
2130       default: break;
2131     }
2132   }
2133 }
2134 
show_psnr(struct stream_state * stream,double peak,int64_t bps)2135 static void show_psnr(struct stream_state *stream, double peak, int64_t bps) {
2136   int i;
2137   double ovpsnr;
2138 
2139   if (!stream->psnr_count) return;
2140 
2141   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2142   ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
2143                        (double)stream->psnr_sse_total);
2144   fprintf(stderr, " %.3f", ovpsnr);
2145 
2146   for (i = 0; i < 4; i++) {
2147     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
2148   }
2149   if (bps > 0) {
2150     fprintf(stderr, " %7" PRId64 " bps", bps);
2151   }
2152   fprintf(stderr, " %7" PRId64 " ms", stream->cx_time / 1000);
2153   fprintf(stderr, "\n");
2154 }
2155 
usec_to_fps(uint64_t usec,unsigned int frames)2156 static float usec_to_fps(uint64_t usec, unsigned int frames) {
2157   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
2158 }
2159 
test_decode(struct stream_state * stream,enum TestDecodeFatality fatal)2160 static void test_decode(struct stream_state *stream,
2161                         enum TestDecodeFatality fatal) {
2162   aom_image_t enc_img, dec_img;
2163 
2164   if (stream->mismatch_seen) return;
2165 
2166   /* Get the internal reference frame */
2167   AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder, AV1_GET_NEW_FRAME_IMAGE,
2168                                 &enc_img);
2169   AOM_CODEC_CONTROL_TYPECHECKED(&stream->decoder, AV1_GET_NEW_FRAME_IMAGE,
2170                                 &dec_img);
2171 
2172   if ((enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) !=
2173       (dec_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH)) {
2174     if (enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
2175       aom_image_t enc_hbd_img;
2176       aom_img_alloc(&enc_hbd_img, enc_img.fmt - AOM_IMG_FMT_HIGHBITDEPTH,
2177                     enc_img.d_w, enc_img.d_h, 16);
2178       aom_img_truncate_16_to_8(&enc_hbd_img, &enc_img);
2179       enc_img = enc_hbd_img;
2180     }
2181     if (dec_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
2182       aom_image_t dec_hbd_img;
2183       aom_img_alloc(&dec_hbd_img, dec_img.fmt - AOM_IMG_FMT_HIGHBITDEPTH,
2184                     dec_img.d_w, dec_img.d_h, 16);
2185       aom_img_truncate_16_to_8(&dec_hbd_img, &dec_img);
2186       dec_img = dec_hbd_img;
2187     }
2188   }
2189 
2190   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
2191   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
2192 
2193   if (!aom_compare_img(&enc_img, &dec_img)) {
2194     int y[4], u[4], v[4];
2195     if (enc_img.fmt & AOM_IMG_FMT_HIGHBITDEPTH) {
2196       aom_find_mismatch_high(&enc_img, &dec_img, y, u, v);
2197     } else {
2198       aom_find_mismatch(&enc_img, &dec_img, y, u, v);
2199     }
2200     stream->decoder.err = 1;
2201     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
2202                           "Stream %d: Encode/decode mismatch on frame %d at"
2203                           " Y[%d, %d] {%d/%d},"
2204                           " U[%d, %d] {%d/%d},"
2205                           " V[%d, %d] {%d/%d}",
2206                           stream->index, stream->frames_out, y[0], y[1], y[2],
2207                           y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
2208     stream->mismatch_seen = stream->frames_out;
2209   }
2210 
2211   aom_img_free(&enc_img);
2212   aom_img_free(&dec_img);
2213 }
2214 
print_time(const char * label,int64_t etl)2215 static void print_time(const char *label, int64_t etl) {
2216   int64_t hours;
2217   int64_t mins;
2218   int64_t secs;
2219 
2220   if (etl >= 0) {
2221     hours = etl / 3600;
2222     etl -= hours * 3600;
2223     mins = etl / 60;
2224     etl -= mins * 60;
2225     secs = etl;
2226 
2227     fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
2228             hours, mins, secs);
2229   } else {
2230     fprintf(stderr, "[%3s  unknown] ", label);
2231   }
2232 }
2233 
main(int argc,const char ** argv_)2234 int main(int argc, const char **argv_) {
2235   int pass;
2236   aom_image_t raw;
2237   aom_image_t raw_shift;
2238   int allocated_raw_shift = 0;
2239   int use_16bit_internal = 0;
2240   int input_shift = 0;
2241   int frame_avail, got_data;
2242 
2243   struct AvxInputContext input;
2244   struct AvxEncoderConfig global;
2245   struct stream_state *streams = NULL;
2246   char **argv, **argi;
2247   uint64_t cx_time = 0;
2248   int stream_cnt = 0;
2249   int res = 0;
2250   int profile_updated = 0;
2251 
2252   memset(&input, 0, sizeof(input));
2253   exec_name = argv_[0];
2254 
2255   /* Setup default input stream settings */
2256   input.framerate.numerator = 30;
2257   input.framerate.denominator = 1;
2258   input.only_i420 = 1;
2259   input.bit_depth = 0;
2260 
2261   /* First parse the global configuration values, because we want to apply
2262    * other parameters on top of the default configuration provided by the
2263    * codec.
2264    */
2265   argv = argv_dup(argc - 1, argv_ + 1);
2266   parse_global_config(&global, &argv);
2267 
2268   if (argc < 2) usage_exit();
2269 
2270   switch (global.color_type) {
2271     case I420: input.fmt = AOM_IMG_FMT_I420; break;
2272     case I422: input.fmt = AOM_IMG_FMT_I422; break;
2273     case I444: input.fmt = AOM_IMG_FMT_I444; break;
2274     case YV12: input.fmt = AOM_IMG_FMT_YV12; break;
2275   }
2276 
2277   {
2278     /* Now parse each stream's parameters. Using a local scope here
2279      * due to the use of 'stream' as loop variable in FOREACH_STREAM
2280      * loops
2281      */
2282     struct stream_state *stream = NULL;
2283 
2284     do {
2285       stream = new_stream(&global, stream);
2286       stream_cnt++;
2287       if (!streams) streams = stream;
2288     } while (parse_stream_params(&global, stream, argv));
2289   }
2290 
2291   /* Check for unrecognized options */
2292   for (argi = argv; *argi; argi++)
2293     if (argi[0][0] == '-' && argi[0][1])
2294       die("Error: Unrecognized option %s\n", *argi);
2295 
2296   FOREACH_STREAM(stream, streams) {
2297     check_encoder_config(global.disable_warning_prompt, &global,
2298                          &stream->config.cfg);
2299 
2300     // If large_scale_tile = 1, only support to output to ivf format.
2301     if (stream->config.cfg.large_scale_tile && !stream->config.write_ivf)
2302       die("only support ivf output format while large-scale-tile=1\n");
2303   }
2304 
2305   /* Handle non-option arguments */
2306   input.filename = argv[0];
2307 
2308   if (!input.filename) {
2309     fprintf(stderr, "No input file specified!\n");
2310     usage_exit();
2311   }
2312 
2313   /* Decide if other chroma subsamplings than 4:2:0 are supported */
2314   if (global.codec->fourcc == AV1_FOURCC) input.only_i420 = 0;
2315 
2316   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2317     int frames_in = 0, seen_frames = 0;
2318     int64_t estimated_time_left = -1;
2319     int64_t average_rate = -1;
2320     int64_t lagged_count = 0;
2321 
2322     open_input_file(&input, global.csp);
2323 
2324     /* If the input file doesn't specify its w/h (raw files), try to get
2325      * the data from the first stream's configuration.
2326      */
2327     if (!input.width || !input.height) {
2328       FOREACH_STREAM(stream, streams) {
2329         if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2330           input.width = stream->config.cfg.g_w;
2331           input.height = stream->config.cfg.g_h;
2332           break;
2333         }
2334       };
2335     }
2336 
2337     /* Update stream configurations from the input file's parameters */
2338     if (!input.width || !input.height)
2339       fatal(
2340           "Specify stream dimensions with --width (-w) "
2341           " and --height (-h)");
2342 
2343     /* If input file does not specify bit-depth but input-bit-depth parameter
2344      * exists, assume that to be the input bit-depth. However, if the
2345      * input-bit-depth paramter does not exist, assume the input bit-depth
2346      * to be the same as the codec bit-depth.
2347      */
2348     if (!input.bit_depth) {
2349       FOREACH_STREAM(stream, streams) {
2350         if (stream->config.cfg.g_input_bit_depth)
2351           input.bit_depth = stream->config.cfg.g_input_bit_depth;
2352         else
2353           input.bit_depth = stream->config.cfg.g_input_bit_depth =
2354               (int)stream->config.cfg.g_bit_depth;
2355       }
2356       if (input.bit_depth > 8) input.fmt |= AOM_IMG_FMT_HIGHBITDEPTH;
2357     } else {
2358       FOREACH_STREAM(stream, streams) {
2359         stream->config.cfg.g_input_bit_depth = input.bit_depth;
2360       }
2361     }
2362 
2363     FOREACH_STREAM(stream, streams) {
2364       if (input.fmt != AOM_IMG_FMT_I420 && input.fmt != AOM_IMG_FMT_I42016) {
2365         /* Automatically upgrade if input is non-4:2:0 but a 4:2:0 profile
2366            was selected. */
2367         switch (stream->config.cfg.g_profile) {
2368           case 0:
2369             if (input.bit_depth < 12 && (input.fmt == AOM_IMG_FMT_I444 ||
2370                                          input.fmt == AOM_IMG_FMT_I44416)) {
2371               if (!stream->config.cfg.monochrome) {
2372                 stream->config.cfg.g_profile = 1;
2373                 profile_updated = 1;
2374               }
2375             } else if (input.bit_depth == 12 || input.fmt == AOM_IMG_FMT_I422 ||
2376                        input.fmt == AOM_IMG_FMT_I42216) {
2377               stream->config.cfg.g_profile = 2;
2378               profile_updated = 1;
2379             }
2380             break;
2381           case 1:
2382             if (input.bit_depth == 12 || input.fmt == AOM_IMG_FMT_I422 ||
2383                 input.fmt == AOM_IMG_FMT_I42216) {
2384               stream->config.cfg.g_profile = 2;
2385               profile_updated = 1;
2386             } else if (input.bit_depth < 12 &&
2387                        (input.fmt == AOM_IMG_FMT_I420 ||
2388                         input.fmt == AOM_IMG_FMT_I42016)) {
2389               stream->config.cfg.g_profile = 0;
2390               profile_updated = 1;
2391             }
2392             break;
2393           case 2:
2394             if (input.bit_depth < 12 && (input.fmt == AOM_IMG_FMT_I444 ||
2395                                          input.fmt == AOM_IMG_FMT_I44416)) {
2396               stream->config.cfg.g_profile = 1;
2397               profile_updated = 1;
2398             } else if (input.bit_depth < 12 &&
2399                        (input.fmt == AOM_IMG_FMT_I420 ||
2400                         input.fmt == AOM_IMG_FMT_I42016)) {
2401               stream->config.cfg.g_profile = 0;
2402               profile_updated = 1;
2403             } else if (input.bit_depth == 12 &&
2404                        input.file_type == FILE_TYPE_Y4M) {
2405               // Note that here the input file values for chroma subsampling
2406               // are used instead of those from the command line.
2407               AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder,
2408                                             AV1E_SET_CHROMA_SUBSAMPLING_X,
2409                                             input.y4m.dst_c_dec_h >> 1);
2410               AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder,
2411                                             AV1E_SET_CHROMA_SUBSAMPLING_Y,
2412                                             input.y4m.dst_c_dec_v >> 1);
2413             } else if (input.bit_depth == 12 &&
2414                        input.file_type == FILE_TYPE_RAW) {
2415               AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder,
2416                                             AV1E_SET_CHROMA_SUBSAMPLING_X,
2417                                             stream->chroma_subsampling_x);
2418               AOM_CODEC_CONTROL_TYPECHECKED(&stream->encoder,
2419                                             AV1E_SET_CHROMA_SUBSAMPLING_Y,
2420                                             stream->chroma_subsampling_y);
2421             }
2422             break;
2423           default: break;
2424         }
2425       }
2426       /* Automatically set the codec bit depth to match the input bit depth.
2427        * Upgrade the profile if required. */
2428       if (stream->config.cfg.g_input_bit_depth >
2429           (unsigned int)stream->config.cfg.g_bit_depth) {
2430         stream->config.cfg.g_bit_depth = stream->config.cfg.g_input_bit_depth;
2431         if (!global.quiet) {
2432           fprintf(stderr,
2433                   "Warning: automatically updating bit depth to %d to "
2434                   "match input format.\n",
2435                   stream->config.cfg.g_input_bit_depth);
2436         }
2437       }
2438       if (stream->config.cfg.g_bit_depth > 10) {
2439         switch (stream->config.cfg.g_profile) {
2440           case 0:
2441           case 1:
2442             stream->config.cfg.g_profile = 2;
2443             profile_updated = 1;
2444             break;
2445           default: break;
2446         }
2447       }
2448       if (stream->config.cfg.g_bit_depth > 8) {
2449         stream->config.use_16bit_internal = 1;
2450       }
2451       if (profile_updated && !global.quiet) {
2452         fprintf(stderr,
2453                 "Warning: automatically updating to profile %d to "
2454                 "match input format.\n",
2455                 stream->config.cfg.g_profile);
2456       }
2457       /* Set limit */
2458       stream->config.cfg.g_limit = global.limit;
2459     }
2460 
2461     FOREACH_STREAM(stream, streams) {
2462       set_stream_dimensions(stream, input.width, input.height);
2463     }
2464     FOREACH_STREAM(stream, streams) { validate_stream_config(stream, &global); }
2465 
2466     /* Ensure that --passes and --pass are consistent. If --pass is set and
2467      * --passes=2, ensure --fpf was set.
2468      */
2469     if (global.pass && global.passes == 2) {
2470       FOREACH_STREAM(stream, streams) {
2471         if (!stream->config.stats_fn)
2472           die("Stream %d: Must specify --fpf when --pass=%d"
2473               " and --passes=2\n",
2474               stream->index, global.pass);
2475       }
2476     }
2477 
2478 #if !CONFIG_WEBM_IO
2479     FOREACH_STREAM(stream, streams) {
2480       if (stream->config.write_webm) {
2481         stream->config.write_webm = 0;
2482         stream->config.write_ivf = 0;
2483         warn("aomenc compiled w/o WebM support. Writing OBU stream.");
2484       }
2485     }
2486 #endif
2487 
2488     /* Use the frame rate from the file only if none was specified
2489      * on the command-line.
2490      */
2491     if (!global.have_framerate) {
2492       global.framerate.num = input.framerate.numerator;
2493       global.framerate.den = input.framerate.denominator;
2494     }
2495     FOREACH_STREAM(stream, streams) {
2496       stream->config.cfg.g_timebase.den = global.framerate.num;
2497       stream->config.cfg.g_timebase.num = global.framerate.den;
2498     }
2499     /* Show configuration */
2500     if (global.verbose && pass == 0) {
2501       FOREACH_STREAM(stream, streams) {
2502         show_stream_config(stream, &global, &input);
2503       }
2504     }
2505 
2506     if (pass == (global.pass ? global.pass - 1 : 0)) {
2507       if (input.file_type == FILE_TYPE_Y4M)
2508         /*The Y4M reader does its own allocation.
2509           Just initialize this here to avoid problems if we never read any
2510           frames.*/
2511         memset(&raw, 0, sizeof(raw));
2512       else
2513         aom_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2514 
2515       FOREACH_STREAM(stream, streams) {
2516         stream->rate_hist =
2517             init_rate_histogram(&stream->config.cfg, &global.framerate);
2518       }
2519     }
2520 
2521     FOREACH_STREAM(stream, streams) { setup_pass(stream, &global, pass); }
2522     FOREACH_STREAM(stream, streams) { initialize_encoder(stream, &global); }
2523     FOREACH_STREAM(stream, streams) {
2524       open_output_file(stream, &global, &input.pixel_aspect_ratio);
2525     }
2526 
2527     if (strcmp(global.codec->name, "av1") == 0 ||
2528         strcmp(global.codec->name, "av1") == 0) {
2529       // Check to see if at least one stream uses 16 bit internal.
2530       // Currently assume that the bit_depths for all streams using
2531       // highbitdepth are the same.
2532       FOREACH_STREAM(stream, streams) {
2533         if (stream->config.use_16bit_internal) {
2534           use_16bit_internal = 1;
2535         }
2536         input_shift = (int)stream->config.cfg.g_bit_depth -
2537                       stream->config.cfg.g_input_bit_depth;
2538       };
2539     }
2540 
2541     frame_avail = 1;
2542     got_data = 0;
2543 
2544     while (frame_avail || got_data) {
2545       struct aom_usec_timer timer;
2546 
2547       if (!global.limit || frames_in < global.limit) {
2548         frame_avail = read_frame(&input, &raw);
2549 
2550         if (frame_avail) frames_in++;
2551         seen_frames =
2552             frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2553 
2554         if (!global.quiet) {
2555           float fps = usec_to_fps(cx_time, seen_frames);
2556           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2557 
2558           if (stream_cnt == 1)
2559             fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2560                     streams->frames_out, (int64_t)streams->nbytes);
2561           else
2562             fprintf(stderr, "frame %4d ", frames_in);
2563 
2564           fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2565                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
2566                   cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2567                   fps >= 1.0 ? "fps" : "fpm");
2568           print_time("ETA", estimated_time_left);
2569         }
2570 
2571       } else {
2572         frame_avail = 0;
2573       }
2574 
2575       if (frames_in > global.skip_frames) {
2576         aom_image_t *frame_to_encode;
2577         if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2578           assert(use_16bit_internal);
2579           // Input bit depth and stream bit depth do not match, so up
2580           // shift frame to stream bit depth
2581           if (!allocated_raw_shift) {
2582             aom_img_alloc(&raw_shift, raw.fmt | AOM_IMG_FMT_HIGHBITDEPTH,
2583                           input.width, input.height, 32);
2584             allocated_raw_shift = 1;
2585           }
2586           aom_img_upshift(&raw_shift, &raw, input_shift);
2587           frame_to_encode = &raw_shift;
2588         } else {
2589           frame_to_encode = &raw;
2590         }
2591         aom_usec_timer_start(&timer);
2592         if (use_16bit_internal) {
2593           assert(frame_to_encode->fmt & AOM_IMG_FMT_HIGHBITDEPTH);
2594           FOREACH_STREAM(stream, streams) {
2595             if (stream->config.use_16bit_internal)
2596               encode_frame(stream, &global,
2597                            frame_avail ? frame_to_encode : NULL, frames_in);
2598             else
2599               assert(0);
2600           };
2601         } else {
2602           assert((frame_to_encode->fmt & AOM_IMG_FMT_HIGHBITDEPTH) == 0);
2603           FOREACH_STREAM(stream, streams) {
2604             encode_frame(stream, &global, frame_avail ? frame_to_encode : NULL,
2605                          frames_in);
2606           }
2607         }
2608         aom_usec_timer_mark(&timer);
2609         cx_time += aom_usec_timer_elapsed(&timer);
2610 
2611         FOREACH_STREAM(stream, streams) { update_quantizer_histogram(stream); }
2612 
2613         got_data = 0;
2614         FOREACH_STREAM(stream, streams) {
2615           get_cx_data(stream, &global, &got_data);
2616         }
2617 
2618         if (!got_data && input.length && streams != NULL &&
2619             !streams->frames_out) {
2620           lagged_count = global.limit ? seen_frames : ftello(input.file);
2621         } else if (input.length) {
2622           int64_t remaining;
2623           int64_t rate;
2624 
2625           if (global.limit) {
2626             const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2627 
2628             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2629             remaining = 1000 * (global.limit - global.skip_frames -
2630                                 seen_frames + lagged_count);
2631           } else {
2632             const int64_t input_pos = ftello(input.file);
2633             const int64_t input_pos_lagged = input_pos - lagged_count;
2634             const int64_t input_limit = input.length;
2635 
2636             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2637             remaining = input_limit - input_pos + lagged_count;
2638           }
2639 
2640           average_rate =
2641               (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2642           estimated_time_left = average_rate ? remaining / average_rate : -1;
2643         }
2644 
2645         if (got_data && global.test_decode != TEST_DECODE_OFF) {
2646           FOREACH_STREAM(stream, streams) {
2647             test_decode(stream, global.test_decode);
2648           }
2649         }
2650       }
2651 
2652       fflush(stdout);
2653       if (!global.quiet) fprintf(stderr, "\033[K");
2654     }
2655 
2656     if (stream_cnt > 1) fprintf(stderr, "\n");
2657 
2658     if (!global.quiet) {
2659       FOREACH_STREAM(stream, streams) {
2660         const int64_t bpf =
2661             seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0;
2662         const int64_t bps = bpf * global.framerate.num / global.framerate.den;
2663         fprintf(stderr,
2664                 "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64
2665                 "b/f %7" PRId64
2666                 "b/s"
2667                 " %7" PRId64 " %s (%.2f fps)\033[K\n",
2668                 pass + 1, global.passes, frames_in, stream->frames_out,
2669                 (int64_t)stream->nbytes, bpf, bps,
2670                 stream->cx_time > 9999999 ? stream->cx_time / 1000
2671                                           : stream->cx_time,
2672                 stream->cx_time > 9999999 ? "ms" : "us",
2673                 usec_to_fps(stream->cx_time, seen_frames));
2674       }
2675     }
2676 
2677     if (global.show_psnr) {
2678       if (global.codec->fourcc == AV1_FOURCC) {
2679         FOREACH_STREAM(stream, streams) {
2680           int64_t bps = 0;
2681           if (stream->psnr_count && seen_frames && global.framerate.den) {
2682             bps = (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2683                   global.framerate.den / seen_frames;
2684           }
2685           show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1,
2686                     bps);
2687         }
2688       } else {
2689         FOREACH_STREAM(stream, streams) { show_psnr(stream, 255.0, 0); }
2690       }
2691     }
2692 
2693     FOREACH_STREAM(stream, streams) { aom_codec_destroy(&stream->encoder); }
2694 
2695     if (global.test_decode != TEST_DECODE_OFF) {
2696       FOREACH_STREAM(stream, streams) { aom_codec_destroy(&stream->decoder); }
2697     }
2698 
2699     close_input_file(&input);
2700 
2701     if (global.test_decode == TEST_DECODE_FATAL) {
2702       FOREACH_STREAM(stream, streams) { res |= stream->mismatch_seen; }
2703     }
2704     FOREACH_STREAM(stream, streams) {
2705       close_output_file(stream, global.codec->fourcc);
2706     }
2707 
2708     FOREACH_STREAM(stream, streams) {
2709       stats_close(&stream->stats, global.passes - 1);
2710     }
2711 
2712     if (global.pass) break;
2713   }
2714 
2715   if (global.show_q_hist_buckets) {
2716     FOREACH_STREAM(stream, streams) {
2717       show_q_histogram(stream->counts, global.show_q_hist_buckets);
2718     }
2719   }
2720 
2721   if (global.show_rate_hist_buckets) {
2722     FOREACH_STREAM(stream, streams) {
2723       show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2724                           global.show_rate_hist_buckets);
2725     }
2726   }
2727   FOREACH_STREAM(stream, streams) { destroy_rate_histogram(stream->rate_hist); }
2728 
2729 #if CONFIG_INTERNAL_STATS
2730   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2731    * to match some existing utilities.
2732    */
2733   if (!(global.pass == 1 && global.passes == 2)) {
2734     FOREACH_STREAM(stream, streams) {
2735       FILE *f = fopen("opsnr.stt", "a");
2736       if (stream->mismatch_seen) {
2737         fprintf(f, "First mismatch occurred in frame %d\n",
2738                 stream->mismatch_seen);
2739       } else {
2740         fprintf(f, "No mismatch detected in recon buffers\n");
2741       }
2742       fclose(f);
2743     }
2744   }
2745 #endif
2746 
2747   if (allocated_raw_shift) aom_img_free(&raw_shift);
2748   aom_img_free(&raw);
2749   free(argv);
2750   free(streams);
2751   return res ? EXIT_FAILURE : EXIT_SUCCESS;
2752 }
2753