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