Debian Codegraph @

.cargo/vendor/rav1e/src/bin/common.rs

raw
1 // Copyright (c) 2017-2023, The rav1e contributors. All rights reserved
2 //
3 // This source code is subject to the terms of the BSD 2 Clause License and
4 // the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
5 // was not distributed with this source code in the LICENSE file, you can
6 // obtain it at www.aomedia.org/license/software. If the Alliance for Open
7 // Media Patent License 1.0 was not distributed with this source code in the
8 // PATENTS file, you can obtain it at www.aomedia.org/license/patent.
9
10 use crate::error::*;
11 use crate::muxer::{create_muxer, Muxer};
12 use crate::stats::MetricsEnabled;
13 use clap::builder::styling::AnsiColor;
14 use clap::builder::Styles;
15 use clap::{CommandFactory, Parser as Clap, Subcommand};
16 use clap_complete::{generate, Shell};
17 use rav1e::prelude::*;
18 use scan_fmt::scan_fmt;
19
20 use rav1e::config::CpuFeatureLevel;
21 use std::fs::File;
22 use std::io;
23 use std::io::prelude::*;
24 use std::path::PathBuf;
25 use std::sync::OnceLock;
26
27 pub mod built_info {
28 // The file has been placed there by the build script.
29 include!(concat!(env!("OUT_DIR"), "/built.rs"));
30 }
31
32 #[derive(Clap)]
33 #[clap(
34 name = "rav1e",
35 styles = get_styles(),
36 version = get_version(),
37 long_version = get_long_version(),
38 about = "AV1 video encoder",
39 long_about = None
40 )]
41 pub struct CliOptions {
42 /// Uncompressed YUV4MPEG2 video input
43 #[clap(value_parser, help_heading = "INPUT/OUTPUT")]
44 pub input: PathBuf,
45 /// Compressed AV1 in IVF video output
46 #[clap(long, short, value_parser, help_heading = "INPUT/OUTPUT")]
47 pub output: PathBuf,
48 /// Overwrite output file.
49 #[clap(short = 'y', help_heading = "INPUT/OUTPUT")]
50 pub overwrite: bool,
51
52 /// Set the threadpool size. If 0, will use the number of logical CPUs.
53 /// rav1e will use up to this many threads. Additional tiles may be needed to
54 /// increase thread utilization.
55 #[clap(long, value_parser, default_value_t = 0, help_heading = "THREADING")]
56 pub threads: usize,
57 /// Number of tile rows. Must be a power of 2. rav1e may override this based on video resolution.
58 #[clap(long, value_parser, default_value_t = 0, help_heading = "THREADING")]
59 pub tile_rows: usize,
60 /// Number of tile columns. Must be a power of 2. rav1e may override this based on video resolution.
61 #[clap(long, value_parser, default_value_t = 0, help_heading = "THREADING")]
62 pub tile_cols: usize,
63 /// Number of tiles. Tile-cols and tile-rows are overridden
64 /// so that the video has at least this many tiles.
65 #[clap(
66 long,
67 value_parser,
68 conflicts_with = "tile_rows",
69 conflicts_with = "tile_cols",
70 help_heading = "THREADING"
71 )]
72 pub tiles: Option<usize>,
73 /// Maximum number of GOPs that can be encoded in parallel
74 #[cfg(feature = "unstable")]
75 #[clap(long, value_parser, default_value_t = 0, help_heading = "THREADING")]
76 pub slots: usize,
77
78 /// Perform the first pass of a two-pass encode,
79 /// saving the pass data to the specified file for future passes
80 #[clap(
81 long,
82 value_parser,
83 value_name = "STATS_FILE",
84 help_heading = "ENCODE SETTINGS"
85 )]
86 pub first_pass: Option<PathBuf>,
87 /// Perform the second pass of a two-pass encode,
88 /// reading the pass data saved from a previous pass from the specified file
89 #[clap(
90 long,
91 value_parser,
92 value_name = "STATS_FILE",
93 help_heading = "ENCODE SETTINGS"
94 )]
95 pub second_pass: Option<PathBuf>,
96 /// Maximum number of frames to encode
97 #[clap(
98 long,
99 short,
100 value_parser,
101 default_value_t = 0,
102 help_heading = "ENCODE SETTINGS"
103 )]
104 pub limit: usize,
105 /// Skip n number of frames and encode
106 #[clap(
107 long,
108 value_parser,
109 default_value_t = 0,
110 help_heading = "ENCODE SETTINGS"
111 )]
112 pub skip: usize,
113 /// Quantizer (0-255), smaller values are higher quality [default: 100]
114 #[clap(long, value_parser, help_heading = "ENCODE SETTINGS")]
115 pub quantizer: Option<u8>,
116 /// Minimum quantizer (0-255) to use in bitrate mode [default: 0]
117 #[clap(long, value_parser, help_heading = "ENCODE SETTINGS")]
118 pub min_quantizer: Option<u8>,
119 /// Bitrate (kbps)
120 #[clap(long, short, value_parser, help_heading = "ENCODE SETTINGS")]
121 pub bitrate: Option<i32>,
122 /// Speed level (0 is best quality, 10 is fastest).
123 /// Speeds 10 and 0 are extremes and are generally not recommended.
124 #[clap(long, short, value_parser = clap::value_parser!(u8).range(0..=10), default_value_t = 6, help_heading = "ENCODE SETTINGS", long_help = build_speed_long_help())]
125 pub speed: u8,
126 /// Speed level for scene-change detection, 0: best quality, 1: fastest mode.
127 /// [default: 0 for s0-s9, 1 for s10]
128 #[clap(long, value_parser = clap::value_parser!(u8).range(0..=1), help_heading = "ENCODE SETTINGS")]
129 pub scd_speed: Option<u8>,
130 /// Minimum interval between keyframes
131 #[clap(
132 long,
133 short = 'i',
134 value_parser,
135 default_value_t = 12,
136 help_heading = "ENCODE SETTINGS"
137 )]
138 pub min_keyint: u64,
139 /// Maximum interval between keyframes. When set to 0, disables fixed-interval keyframes.
140 #[clap(
141 long,
142 short = 'I',
143 value_parser,
144 default_value_t = 240,
145 help_heading = "ENCODE SETTINGS"
146 )]
147 pub keyint: u64,
148 /// Maximum interval between switch frames. When set to 0, disables switch frames.
149 #[clap(
150 long,
151 short = 'S',
152 value_parser,
153 default_value_t = 0,
154 help_heading = "ENCODE SETTINGS"
155 )]
156 pub switch_frame_interval: u64,
157 /// "Number of frames over which rate control should distribute the reservoir
158 /// [default: min(240, 1.5x keyint)]
159 /// A minimum value of 12 is enforced.
160 #[clap(long, value_parser = clap::value_parser!(i32).range(12..), help_heading = "ENCODE SETTINGS")]
161 pub reservoir_frame_delay: Option<i32>,
162 /// Low latency mode; disables frame reordering.
163 /// Has a significant speed-to-quality trade-off
164 #[clap(long, help_heading = "ENCODE SETTINGS")]
165 pub low_latency: bool,
166 /// Disables scene detection entirely.
167 /// Has a significant speed-to-quality trade-off in full encodes.
168 /// Useful for chunked encoding.
169 #[clap(long, help_heading = "ENCODE SETTINGS")]
170 pub no_scene_detection: bool,
171 /// Number of frames encoder should lookahead for RDO purposes\n\
172 /// [default value for speed levels: 10,9 - 10; 8,7,6 - 20; 5,4,3 - 30; 2,1,0 - 40]
173 #[clap(long, value_parser, help_heading = "ENCODE SETTINGS")]
174 pub rdo_lookahead_frames: Option<usize>,
175 /// Quality tuning
176 #[clap(long, value_parser, default_value_t = Tune::Psychovisual, help_heading = "ENCODE SETTINGS")]
177 pub tune: Tune,
178 /// Still picture mode
179 #[clap(long, help_heading = "ENCODE SETTINGS")]
180 pub still_picture: bool,
181 /// Uses grain synthesis to add photon noise to the resulting encode.
182 /// Takes a strength value 0-64.
183 #[clap(
184 long,
185 conflicts_with = "film_grain_table",
186 value_parser = clap::value_parser!(u8).range(0..=64),
187 default_value_t = 0,
188 help_heading = "ENCODE SETTINGS"
189 )]
190 pub photon_noise: u8,
191 /// Uses a film grain table file to apply grain synthesis to the encode.
192 /// Uses the same table file format as aomenc and svt-av1.
193 #[clap(
194 long,
195 alias = "photon-noise-table",
196 value_parser,
197 help_heading = "ENCODE SETTINGS"
198 )]
199 pub film_grain_table: Option<PathBuf>,
200 /// Force the high bitdepth codepath even for 8bit content.
201 /// Mainly for debugging purposes.
202 #[clap(long, help_heading = "ENCODE SETTINGS")]
203 pub high_bitdepth: bool,
204
205 /// Pixel range
206 #[clap(long, value_parser, help_heading = "VIDEO METADATA")]
207 pub range: Option<PixelRange>,
208 /// Color primaries used to describe color parameters
209 #[clap(long, value_parser, help_heading = "VIDEO METADATA")]
210 pub primaries: Option<ColorPrimaries>,
211 /// Transfer characteristics used to describe color parameters
212 #[clap(long, value_parser, help_heading = "VIDEO METADATA")]
213 pub transfer: Option<TransferCharacteristics>,
214 /// Matrix coefficients used to describe color parameters
215 #[clap(long, value_parser, help_heading = "VIDEO METADATA")]
216 pub matrix: Option<MatrixCoefficients>,
217 /// Mastering display primaries in the form of G(x,y)B(x,y)R(x,y)WP(x,y)L(max,min)
218 #[clap(long, help_heading = "VIDEO METADATA")]
219 pub mastering_display: Option<String>,
220 /// Content light level used to describe content luminosity (cll,fall)
221 #[clap(long, help_heading = "VIDEO METADATA")]
222 pub content_light: Option<String>,
223 /// AV1 level to target in the form <major>.<minor>, e.g. 3.1.
224 /// Specify "unconstrained" for no level constraints or "auto" to let
225 /// the encoder choose (default)
226 #[clap(long, help_heading = "LEVEL")]
227 pub level: Option<String>,
228 /// Constant frame rate to set at the output (inferred from input when omitted)
229 #[clap(long, value_parser, help_heading = "VIDEO METADATA")]
230 pub frame_rate: Option<u64>,
231 /// The time scale associated with the frame rate if provided (ignored otherwise)
232 #[clap(
233 long,
234 value_parser,
235 default_value_t = 0,
236 help_heading = "VIDEO METADATA"
237 )]
238 pub time_scale: u64,
239
240 /// Provide a benchmark report at the end of the encoding
241 #[clap(long, help_heading = "DEBUGGING")]
242 pub benchmark: bool,
243 /// Verbose logging; outputs info for every frame
244 #[clap(long, short, help_heading = "DEBUGGING")]
245 pub verbose: bool,
246 /// Do not output any status message
247 #[clap(long, short, conflicts_with = "verbose", help_heading = "DEBUGGING")]
248 pub quiet: bool,
249 /// Calculate and display PSNR metrics
250 #[clap(long, help_heading = "DEBUGGING")]
251 pub psnr: bool,
252 /// Calculate and display several metrics including PSNR, SSIM, CIEDE2000 etc
253 #[clap(long, conflicts_with = "psnr", help_heading = "DEBUGGING")]
254 pub metrics: bool,
255 /// Outputs a Y4M file containing the output from the decoder
256 #[clap(long, short, value_parser, help_heading = "DEBUGGING")]
257 pub reconstruction: Option<PathBuf>,
258
259 #[clap(subcommand)]
260 pub command: Option<Commands>,
261 }
262
263 static VERSION_STR: OnceLock<String> = OnceLock::new();
264 static LONG_VERSION_STR: OnceLock<String> = OnceLock::new();
265
266 fn get_styles() -> Styles {
267 Styles::styled()
268 .header(AnsiColor::Yellow.on_default())
269 .usage(AnsiColor::Green.on_default())
270 .literal(AnsiColor::Green.on_default())
271 .placeholder(AnsiColor::Green.on_default())
272 }
273
274 fn get_version() -> &'static str {
275 VERSION_STR.get_or_init(|| {
276 format!(
277 "{} ({})",
278 rav1e::version::full(),
279 // We cannot use `built_info::DEBUG` because that tells us if there are debug symbols,
280 // not if there are optimizations.
281 if cfg!(debug_assertions) { "debug" } else { "release" }
282 )
283 })
284 }
285
286 fn get_long_version() -> &'static str {
287 LONG_VERSION_STR.get_or_init(|| {
288 let rustflags = env!("CARGO_ENCODED_RUSTFLAGS");
289 let rustflags = if rustflags.trim().is_empty() {
290 "(None)".to_string()
291 } else {
292 // Replace non-printable ASCII Unit Separator with whitespace
293 rustflags.replace(0x1F as char, " ")
294 };
295 format!(
296 "{}\n{} {}\nCompiled CPU Features: {}\nRuntime Assembly Support: {}{}\nThreading: {}\nUnstable Features: {}\nCompiler Flags: {}",
297 get_version(),
298 built_info::RUSTC_VERSION,
299 built_info::TARGET,
300 option_env!("CARGO_CFG_TARGET_FEATURE").unwrap_or("(None)"),
301 if cfg!(feature = "asm") { "Enabled" } else { "Disabled" },
302 if cfg!(feature = "asm") {
303 format!("\nRuntime Assembly Level: {}", CpuFeatureLevel::default())
304 } else {
305 String::new()
306 },
307 if cfg!(feature = "threading") { "Enabled" } else { "Disabled" },
308 if cfg!(feature = "unstable") { "Enabled" } else { "Disabled" },
309 rustflags
310 )
311 })
312 }
313
314 #[derive(Subcommand)]
315 pub enum Commands {
316 /// Advanced features
317 Advanced {
318 /// Output to stdout the completion definition for the shell
319 #[clap(long, short, value_parser)]
320 completion: Option<Shell>,
321 /// Save the current configuration in a toml file
322 #[clap(long, short, value_parser)]
323 save_config: Option<PathBuf>,
324 /// Load the encoder configuration from a toml file
325 #[clap(long, short, value_parser, conflicts_with = "save-config")]
326 load_config: Option<PathBuf>,
327 },
328 }
329
330 pub struct EncoderIO {
331 pub input: Box<dyn Read + Send>,
332 pub output: Box<dyn Muxer + Send>,
333 pub rec: Option<Box<dyn Write + Send>>,
334 }
335
336 #[derive(Clone, Copy, PartialEq, Eq)]
337 pub enum Verboseness {
338 Quiet,
339 Normal,
340 Verbose,
341 }
342
343 pub struct ParsedCliOptions {
344 pub io: EncoderIO,
345 pub enc: EncoderConfig,
346 pub limit: usize,
347 pub color_range_specified: bool,
348 pub override_time_base: bool,
349 pub skip: usize,
350 pub verbose: Verboseness,
351 pub benchmark: bool,
352 pub threads: usize,
353 pub metrics_enabled: MetricsEnabled,
354 pub pass1file_name: Option<PathBuf>,
355 pub pass2file_name: Option<PathBuf>,
356 #[cfg(feature = "serialize")]
357 pub save_config: Option<PathBuf>,
358 pub photon_noise: u8,
359 #[cfg(feature = "unstable")]
360 #[allow(unused)]
361 pub slots: usize,
362 pub force_highbitdepth: bool,
363 }
364
365 #[cfg(feature = "serialize")]
366 static HELP_TEXT: OnceLock<String> = OnceLock::new();
367
368 #[cfg(feature = "serialize")]
369 fn build_speed_long_help() -> Option<&'static str> {
370 let help = HELP_TEXT.get_or_init(|| {
371 let levels = (0..=10)
372 .map(|speed| {
373 let s = SpeedSettings::from_preset(speed);
374 let o = crate::kv::to_string(&s).unwrap().replace(", ", "\n ");
375 format!("{:2} :\n {}", speed, o)
376 })
377 .collect::<Vec<String>>()
378 .join("\n");
379
380 format!(
381 "Speed level (0 is best quality, 10 is fastest)\n\
382 Speeds 10 and 0 are extremes and are generally not recommended\n\
383 {}",
384 levels
385 )
386 });
387
388 Some(&help)
389 }
390
391 #[cfg(not(feature = "serialize"))]
392 #[allow(clippy::missing_const_for_fn)]
393 fn build_speed_long_help() -> Option<&'static str> {
394 Some(
395 "Speed level (0 is best quality, 10 is fastest)\n\
396 Speeds 10 and 0 are extremes and are generally not recommended",
397 )
398 }
399
400 #[allow(unused_mut)]
401 /// Only call this once at the start of the app,
402 /// otherwise bad things will happen.
403 pub fn parse_cli() -> Result<ParsedCliOptions, CliError> {
404 let matches = CliOptions::parse();
405
406 #[cfg(feature = "serialize")]
407 let mut save_config_path = None;
408 let mut enc = None;
409
410 if let Some(command) = matches.command.as_ref() {
411 match command {
412 Commands::Advanced { completion, save_config, load_config } => {
413 if let Some(shell) = completion {
414 let mut app = CliOptions::command();
415 let app_name = app.get_name().to_string();
416 generate(*shell, &mut app, app_name, &mut std::io::stdout());
417 std::process::exit(0);
418 }
419
420 #[cfg(feature = "serialize")]
421 {
422 save_config_path = save_config.clone();
423 if let Some(load_config) = load_config {
424 let mut config = String::new();
425 File::open(load_config)
426 .and_then(|mut f| f.read_to_string(&mut config))
427 .map_err(|e| e.context("Cannot open the configuration file"))?;
428
429 enc = Some(toml::from_str(&config).unwrap());
430 }
431 }
432 #[cfg(not(feature = "serialize"))]
433 {
434 if save_config.is_some() || load_config.is_some() {
435 let e: io::Error = io::ErrorKind::InvalidInput.into();
436 return Err(e.context(
437 "The load/save config advanced option requires the
438 `serialize` feature, rebuild adding it.",
439 ));
440 }
441 }
442 }
443 }
444 }
445
446 let rec = match matches.reconstruction.as_ref() {
447 Some(f) => Some(Box::new(
448 File::create(f)
449 .map_err(|e| e.context("Cannot create reconstruction file"))?,
450 ) as Box<dyn Write + Send>),
451 None => None,
452 };
453
454 let os_input = &matches.input;
455 let io = EncoderIO {
456 input: match os_input.to_str() {
457 Some("-") => Box::new(io::stdin()) as Box<dyn Read + Send>,
458 _ => Box::new(
459 File::open(os_input)
460 .map_err(|e| e.context("Cannot open input file"))?,
461 ) as Box<dyn Read + Send>,
462 },
463 output: create_muxer(&matches.output, matches.overwrite)?,
464 rec,
465 };
466
467 let enc = enc.map_or_else(|| parse_config(&matches), Ok)?;
468
469 let verbose = if matches.quiet {
470 Verboseness::Quiet
471 } else if matches.verbose {
472 Verboseness::Verbose
473 } else {
474 Verboseness::Normal
475 };
476
477 let metrics_enabled = if matches.metrics {
478 MetricsEnabled::All
479 } else if matches.psnr {
480 MetricsEnabled::Psnr
481 } else {
482 MetricsEnabled::None
483 };
484
485 let limit = matches.limit;
486 if enc.still_picture && limit > 1 {
487 panic!("A limit cannot be set above 1 in still picture mode");
488 }
489
490 #[cfg(feature = "unstable")]
491 let slots = matches.slots;
492
493 Ok(ParsedCliOptions {
494 io,
495 enc,
496 limit,
497 color_range_specified: matches.range.is_some(),
498 override_time_base: matches.frame_rate.is_some(),
499 metrics_enabled,
500 skip: matches.skip,
501 benchmark: matches.benchmark,
502 verbose,
503 threads: matches.threads,
504 pass1file_name: matches.first_pass.clone(),
505 pass2file_name: matches.second_pass.clone(),
506 #[cfg(feature = "serialize")]
507 save_config: save_config_path,
508 photon_noise: matches.photon_noise,
509 force_highbitdepth: matches.high_bitdepth,
510 #[cfg(feature = "unstable")]
511 slots,
512 })
513 }
514
515 fn parse_config(matches: &CliOptions) -> Result<EncoderConfig, CliError> {
516 let maybe_quantizer = matches.quantizer;
517 let maybe_bitrate = matches.bitrate;
518 let quantizer = maybe_quantizer.unwrap_or_else(|| {
519 if maybe_bitrate.is_some() {
520 // If a bitrate is specified, the quantizer is the maximum allowed (e.g.,
521 // the minimum quality allowed), which by default should be
522 // unconstrained.
523 255
524 } else {
525 100
526 }
527 }) as usize;
528 let bitrate: i32 = maybe_bitrate.unwrap_or(0);
529 if bitrate <= 0
530 && (matches.first_pass.is_some() || matches.second_pass.is_some())
531 {
532 panic!("A target bitrate must be specified when using passes");
533 }
534
535 if quantizer == 0 {
536 unimplemented!("Lossless encoding not yet implemented");
537 } else if quantizer > 255 {
538 panic!("Quantizer must be between 0-255");
539 }
540
541 let speed = matches.speed;
542 let scene_detection_speed = matches.scd_speed;
543 let max_interval = matches.keyint;
544 let min_interval = matches.min_keyint.min(max_interval);
545
546 if speed > 10 {
547 panic!("Speed must be between 0-10");
548 } else if min_interval > max_interval {
549 panic!("Maximum keyframe interval must be greater than or equal to minimum keyframe interval");
550 }
551
552 let color_primaries = matches.primaries.unwrap_or_default();
553 let transfer_characteristics = matches.transfer.unwrap_or_default();
554 let matrix_coefficients = matches.matrix.unwrap_or_default();
555
556 let mut cfg = EncoderConfig::with_speed_preset(speed);
557
558 if let Some(level_str) = &matches.level {
559 cfg.level_idx = match level_str.as_str() {
560 "auto" => None,
561 "unconstrained" => Some(31),
562 _ => {
563 let (major, minor) = scan_fmt!(level_str, "{}.{}", u8, u8)
564 .expect("Could not parse AV1 level");
565 if major > 7 || minor > 3 {
566 panic!("Invalid AV1 level")
567 }
568 Some(((major - 2) << 2) + minor)
569 }
570 };
571 };
572
573 if let Some(scd_speed) = scene_detection_speed {
574 cfg.speed_settings.scene_detection_mode = if scd_speed == 0 {
575 SceneDetectionSpeed::Standard
576 } else {
577 SceneDetectionSpeed::Fast
578 };
579 }
580
581 cfg.set_key_frame_interval(min_interval, max_interval);
582 cfg.switch_frame_interval = matches.switch_frame_interval;
583
584 cfg.pixel_range = matches.range.unwrap_or_default();
585 cfg.color_description = if color_primaries == ColorPrimaries::Unspecified
586 && transfer_characteristics == TransferCharacteristics::Unspecified
587 && matrix_coefficients == MatrixCoefficients::Unspecified
588 {
589 // No need to set a color description with all parameters unspecified.
590 None
591 } else {
592 Some(ColorDescription {
593 color_primaries,
594 transfer_characteristics,
595 matrix_coefficients,
596 })
597 };
598
599 cfg.mastering_display = matches.mastering_display.as_ref().map(|mastering_display| {
600 let (g_x, g_y, b_x, b_y, r_x, r_y, wp_x, wp_y, max_lum, min_lum) =
601 scan_fmt!(
602 mastering_display,
603 "G({},{})B({},{})R({},{})WP({},{})L({},{})",
604 f64,
605 f64,
606 f64,
607 f64,
608 f64,
609 f64,
610 f64,
611 f64,
612 f64,
613 f64
614 )
615 .expect("Cannot parse the mastering display option");
616
617 /* AV1 spec sec. 6.7.4 "Metadata high dynamic range mastering display color volume semantics"
618 * specifies chromaticity coords as 0.16 fixed-point numbers, which have a max float value
619 * of 0.9999847412109375 (rounding to 1).
620 */
621 let chromaticity_range = 0.0..=1.0;
622 if !chromaticity_range.contains(&g_x)
623 || !chromaticity_range.contains(&g_y)
624 || !chromaticity_range.contains(&b_x)
625 || !chromaticity_range.contains(&b_y)
626 || !chromaticity_range.contains(&r_x)
627 || !chromaticity_range.contains(&r_y)
628 || !chromaticity_range.contains(&wp_x)
629 || !chromaticity_range.contains(&wp_y)
630 {
631 warn!(
632 "Chromaticity coordinates will be trimmed to the range 0.0 to 1.0 (see AV1 spec sec. 6.7.4)."
633 );
634 }
635
636 MasteringDisplay {
637 primaries: [
638 ChromaticityPoint {
639 x: (r_x * ((1 << 16) as f64)).round() as u16,
640 y: (r_y * ((1 << 16) as f64)).round() as u16,
641 },
642 ChromaticityPoint {
643 x: (g_x * ((1 << 16) as f64)).round() as u16,
644 y: (g_y * ((1 << 16) as f64)).round() as u16,
645 },
646 ChromaticityPoint {
647 x: (b_x * ((1 << 16) as f64)).round() as u16,
648 y: (b_y * ((1 << 16) as f64)).round() as u16,
649 },
650 ],
651 white_point: ChromaticityPoint {
652 x: (wp_x * ((1 << 16) as f64)).round() as u16,
653 y: (wp_y * ((1 << 16) as f64)).round() as u16,
654 },
655 max_luminance: (max_lum * ((1 << 8) as f64)).round() as u32,
656 min_luminance: (min_lum * ((1 << 14) as f64)).round() as u32,
657 }
658 });
659
660 cfg.content_light =
661 matches.content_light.as_ref().and_then(|content_light| {
662 let (cll, fall) = scan_fmt!(content_light, "{},{}", u16, u16)
663 .expect("Cannot parse the content light option");
664 if cll == 0 && fall == 0 {
665 None
666 } else {
667 Some(ContentLight {
668 max_content_light_level: cll,
669 max_frame_average_light_level: fall,
670 })
671 }
672 });
673
674 cfg.still_picture = matches.still_picture;
675
676 cfg.quantizer = quantizer;
677 cfg.min_quantizer = matches.min_quantizer.unwrap_or(0);
678 cfg.bitrate = bitrate.checked_mul(1000).expect("Bitrate too high");
679 cfg.reservoir_frame_delay = matches.reservoir_frame_delay;
680
681 if let Some(rdo_frames) = matches.rdo_lookahead_frames {
682 cfg.speed_settings.rdo_lookahead_frames = rdo_frames;
683 }
684
685 cfg.tune = matches.tune;
686
687 if cfg.tune == Tune::Psychovisual {
688 cfg.speed_settings.transform.tx_domain_distortion = false;
689 }
690
691 cfg.tile_cols = matches.tile_cols;
692 cfg.tile_rows = matches.tile_rows;
693
694 cfg.tiles = matches.tiles.unwrap_or(0);
695
696 if cfg.tile_cols > 64 || cfg.tile_rows > 64 {
697 panic!("Tile columns and rows may not be greater than 64");
698 }
699
700 if let Some(table_file) = matches.film_grain_table.as_ref() {
701 let contents = std::fs::read_to_string(table_file)
702 .expect("Failed to read film grain table file");
703 let table = av1_grain::parse_grain_table(&contents)
704 .expect("Failed to parse film grain table");
705 if !table.is_empty() {
706 cfg.film_grain_params = Some(table);
707 }
708 }
709
710 if let Some(frame_rate) = matches.frame_rate {
711 cfg.time_base = Rational::new(matches.time_scale, frame_rate);
712 }
713
714 cfg.low_latency = matches.low_latency;
715 // Disables scene_detection
716 if matches.no_scene_detection {
717 cfg.speed_settings.scene_detection_mode = SceneDetectionSpeed::None;
718 }
719
720 Ok(cfg)
721 }