common.rs 24.6 KB
Newer Older
Raphaël Zumer's avatar
Raphaël Zumer committed
1
2
3
4
5
6
7
8
9
// Copyright (c) 2017-2018, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

10
use crate::muxer::{create_muxer, Muxer};
11
use crate::{ColorPrimaries, MatrixCoefficients, TransferCharacteristics};
12
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand, Shell};
Luca Barbato's avatar
Luca Barbato committed
13
14
use rav1e::prelude::*;
use rav1e::version;
Luca Barbato's avatar
Luca Barbato committed
15
use scan_fmt::scan_fmt;
Raphaël Zumer's avatar
Raphaël Zumer committed
16

17
use std::fs::File;
18
use std::io::prelude::*;
19
use std::path::PathBuf;
20
use std::time::Instant;
21
use std::{fmt, io};
22
23

pub struct EncoderIO {
Kyle Siefring's avatar
Kyle Siefring committed
24
  pub input: Box<dyn Read>,
25
  pub output: Box<dyn Muxer>,
Kyle Siefring's avatar
Kyle Siefring committed
26
  pub rec: Option<Box<dyn Write>>
27
28
}

29
30
31
32
pub struct CliOptions {
  pub io: EncoderIO,
  pub enc: EncoderConfig,
  pub limit: usize,
33
  pub color_range_specified: bool,
Vibhoothi's avatar
Vibhoothi committed
34
  pub skip: usize,
35
  pub verbose: bool,
Luca Barbato's avatar
Luca Barbato committed
36
  pub threads: usize,
37
38
  pub pass1file_name: Option<String>,
  pub pass2file_name: Option<String>
39
40
41
}

pub fn parse_cli() -> CliOptions {
42
43
44
  let ver_short = version::short();
  let ver_long = version::full();
  let ver = version::full();
45
  let mut app = App::new("rav1e")
46
47
48
    .version(ver.as_str())
    .long_version(ver_long.as_str())
    .version_short(ver_short.as_str())
Luca Barbato's avatar
Luca Barbato committed
49
    .about("AV1 video encoder")
50
    .setting(AppSettings::DeriveDisplayOrder)
51
    .setting(AppSettings::SubcommandsNegateReqs)
52
53
54
    .arg(Arg::with_name("FULLHELP")
      .help("Prints more detailed help information")
      .long("fullhelp"))
Luca Barbato's avatar
Luca Barbato committed
55
56
57
58
59
60
61
62
    // THREADS
    .arg(
      Arg::with_name("THREADS")
        .help("Set the threadpool size")
        .long("threads")
        .takes_value(true)
        .default_value("0")
    )
63
    // INPUT/OUTPUT
Luca Barbato's avatar
Luca Barbato committed
64
65
66
    .arg(
      Arg::with_name("INPUT")
        .help("Uncompressed YUV4MPEG2 video input")
67
        .required_unless("FULLHELP")
Luca Barbato's avatar
Luca Barbato committed
68
        .index(1)
69
70
    )
    .arg(
Luca Barbato's avatar
Luca Barbato committed
71
72
73
74
      Arg::with_name("OUTPUT")
        .help("Compressed AV1 in IVF video output")
        .short("o")
        .long("output")
75
        .required_unless("FULLHELP")
Luca Barbato's avatar
Luca Barbato committed
76
        .takes_value(true)
77
78
79
80
81
82
83
    )
    .arg(
      Arg::with_name("STATS_FILE")
        .help("Custom location for first-pass stats file")
        .long("stats")
        .takes_value(true)
        .default_value("rav1e_stats.json")
84
85
86
    )
    // ENCODING SETTINGS
    .arg(
87
88
89
90
91
92
93
94
95
      Arg::with_name("FIRST_PASS")
        .help("Perform the first pass of a two-pass encode, saving the pass data to the specified file for future passes")
        .long("first-pass")
        .takes_value(true)
    )
    .arg(
      Arg::with_name("SECOND_PASS")
        .help("Perform the second pass of a two-pass encode, reading the pass data saved from a previous pass from the specified file")
        .long("second-pass")
96
        .takes_value(true)
97
98
    )
    .arg(
Luca Barbato's avatar
Luca Barbato committed
99
100
101
102
103
104
      Arg::with_name("LIMIT")
        .help("Maximum number of frames to encode")
        .short("l")
        .long("limit")
        .takes_value(true)
        .default_value("0")
105
    )
Vibhoothi's avatar
Vibhoothi committed
106
107
108
109
110
111
112
    .arg(
      Arg::with_name("SKIP")
        .help("Skip n number of frames and encode")
        .long("skip")
        .takes_value(true)
        .default_value("0")
    )
113
    .arg(
Luca Barbato's avatar
Luca Barbato committed
114
      Arg::with_name("QP")
115
        .help("Quantizer (0-255), smaller values are higher quality [default: 100]")
Luca Barbato's avatar
Luca Barbato committed
116
117
        .long("quantizer")
        .takes_value(true)
118
    )
119
120
121
    .arg(
      Arg::with_name("MINQP")
        .help("Minimum quantizer (0-255) to use in bitrate mode [default: 0]")
122
123
        .long("min-quantizer")
        .alias("min_quantizer")
124
125
        .takes_value(true)
    )
126
127
128
129
130
131
    .arg(
      Arg::with_name("BITRATE")
        .help("Bitrate (kbps)")
        .short("b")
        .long("bitrate")
        .takes_value(true)
132
133
    )
    .arg(
Luca Barbato's avatar
Luca Barbato committed
134
      Arg::with_name("SPEED")
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        .help("Speed level (0 is best quality, 10 is fastest)\n\
        Speeds 10 and 0 are extremes and are generally not recommended")
        .long_help("Speed level (0 is best quality, 10 is fastest)\n\
        Speeds 10 and 0 are extremes and are generally not recommended\n\
        - 10 (fastest):\n\
        Min block size 64x64, TX domain distortion, fast deblock, no scenechange detection\n\
        - 9:\n\
        Min block size 64x64, TX domain distortion, fast deblock\n\
        - 8:\n\
        Min block size 8x8, reduced TX set, TX domain distortion, fast deblock\n\
        - 7:\n\
        Min block size 8x8, reduced TX set, TX domain distortion\n\
        - 6:\n\
        Min block size 8x8, reduced TX set, TX domain distortion\n\
        - 5 (default):\n\
        Min block size 8x8, reduced TX set, TX domain distortion, complex pred modes for keyframes\n\
        - 4:\n\
        Min block size 8x8, TX domain distortion, complex pred modes for keyframes\n\
        - 3:\n\
        Min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision\n\
        - 2:\n\
        Min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision, include near MVs\n\
        - 1:\n\
        Min block size 8x8, TX domain distortion, complex pred modes, RDO TX decision, include near MVs\n\
        - 0 (slowest):\n\
        Min block size 4x4, TX domain distortion, complex pred modes, RDO TX decision, include near MVs, bottom-up encoding\n")
Luca Barbato's avatar
Luca Barbato committed
161
162
163
        .short("s")
        .long("speed")
        .takes_value(true)
164
        .default_value("5")
165
166
    )
    .arg(
Josh Holmer's avatar
Josh Holmer committed
167
168
169
170
171
172
      Arg::with_name("MIN_KEYFRAME_INTERVAL")
        .help("Minimum interval between keyframes")
        .short("i")
        .long("min-keyint")
        .takes_value(true)
        .default_value("12")
173
174
    )
    .arg(
175
      Arg::with_name("KEYFRAME_INTERVAL")
Josh Holmer's avatar
Josh Holmer committed
176
        .help("Maximum interval between keyframes")
177
178
179
        .short("I")
        .long("keyint")
        .takes_value(true)
180
        .default_value("240")
181
    )
182
183
184
185
    .arg(
      Arg::with_name("RESERVOIR_FRAME_DELAY")
        .help("Number of frames over which rate control should distribute the reservoir [default: max(240, 1.5x keyint)]\n\
         A minimum value of 12 is enforced.")
186
187
        .long("reservoir-frame-delay")
        .alias("reservoir_frame_delay")
188
189
        .takes_value(true)
    )
190
    .arg(
191
      Arg::with_name("LOW_LATENCY")
192
193
        .help("Low latency mode; disables frame reordering\n\
            Has a significant speed-to-quality trade-off")
194
195
        .long("low-latency")
        .alias("low_latency")
196
197
    )
    .arg(
Luca Barbato's avatar
Luca Barbato committed
198
      Arg::with_name("TUNE")
199
        .help("Quality tuning")
Luca Barbato's avatar
Luca Barbato committed
200
201
        .long("tune")
        .possible_values(&Tune::variants())
202
        .default_value("Psychovisual")
Luca Barbato's avatar
Luca Barbato committed
203
        .case_insensitive(true)
204
    )
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    .arg(
      Arg::with_name("TILE_ROWS_LOG2")
        .help("Log2 of number of tile rows")
        .long("tile-rows-log2")
        .takes_value(true)
        .default_value("0")
    )
    .arg(
      Arg::with_name("TILE_COLS_LOG2")
        .help("Log2 of number of tile columns")
        .long("tile-cols-log2")
        .takes_value(true)
        .default_value("0")
    )
219
220
221
222
223
224
225
226
    .arg(
      Arg::with_name("TILES")
        .help("Number of tiles. Tile-cols and tile-rows are overridden\n\
               so that the video has at least this many tiles.")
        .long("tiles")
        .takes_value(true)
        .default_value("0")
    )
227
228
    // MASTERING
    .arg(
229
      Arg::with_name("PIXEL_RANGE")
230
231
232
233
234
235
236
        .help("Pixel range")
        .long("range")
        .possible_values(&PixelRange::variants())
        .default_value("unspecified")
        .case_insensitive(true)
    )
    .arg(
237
      Arg::with_name("COLOR_PRIMARIES")
238
239
240
241
242
243
244
        .help("Color primaries used to describe color parameters")
        .long("primaries")
        .possible_values(&ColorPrimaries::variants())
        .default_value("unspecified")
        .case_insensitive(true)
    )
    .arg(
245
      Arg::with_name("TRANSFER_CHARACTERISTICS")
246
247
248
249
250
251
252
        .help("Transfer characteristics used to describe color parameters")
        .long("transfer")
        .possible_values(&TransferCharacteristics::variants())
        .default_value("unspecified")
        .case_insensitive(true)
    )
    .arg(
253
      Arg::with_name("MATRIX_COEFFICIENTS")
254
255
256
257
258
259
260
        .help("Matrix coefficients used to describe color parameters")
        .long("matrix")
        .possible_values(&MatrixCoefficients::variants())
        .default_value("unspecified")
        .case_insensitive(true)
    )
    .arg(
261
      Arg::with_name("MASTERING_DISPLAY")
262
        .help("Mastering display primaries in the form of G(x,y)B(x,y)R(x,y)WP(x,y)L(max,min)")
263
264
        .long("mastering-display")
        .alias("mastering_display")
265
266
267
268
        .default_value("unspecified")
        .case_insensitive(true)
    )
    .arg(
269
      Arg::with_name("CONTENT_LIGHT")
270
        .help("Content light level used to describe content luminosity (cll,fall)")
271
272
        .long("content-light")
        .alias("content_light")
273
274
275
276
277
        .default_value("0,0")
        .case_insensitive(true)
    )
    // DEBUGGING
    .arg(
278
      Arg::with_name("VERBOSE")
279
        .help("Verbose logging; outputs info for every frame")
280
281
        .long("verbose")
        .short("v")
282
283
    )
    .arg(
284
      Arg::with_name("PSNR")
285
        .help("Calculate and display PSNR metrics")
286
        .long("psnr")
287
288
289
290
    )
    .arg(
      Arg::with_name("RECONSTRUCTION")
        .help("Outputs a Y4M file containing the output from the decoder")
291
        .long("reconstruction")
292
293
294
        .short("r")
        .takes_value(true)
    )
295
296
    .arg(
      Arg::with_name("SPEED_TEST")
297
        .help("Run an encode using default encoding settings, manually adjusting only the settings specified; allows benchmarking settings in isolation")
298
299
300
301
        .hidden(true)
        .long("speed-test")
        .takes_value(true)
    )
302
303
304
305
    .arg(
      Arg::with_name("train-rdo")
        .long("train-rdo")
    )
306
    .subcommand(SubCommand::with_name("advanced")
307
                .setting(AppSettings::Hidden)
308
309
310
311
312
313
314
315
316
317
318
                .about("Advanced features")
                .arg(Arg::with_name("SHELL")
                     .help("Output to stdout the completion definition for the shell")
                     .short("c")
                     .long("completion")
                     .takes_value(true)
                     .possible_values(&Shell::variants())
                )
    );

  let matches = app.clone().get_matches();
319

320
321
322
323
324
  if matches.is_present("FULLHELP") {
    app.print_long_help().unwrap();
    std::process::exit(0);
  }

Luca Barbato's avatar
Luca Barbato committed
325
  let threads = matches.value_of("THREADS").map(|v| v.parse().expect("Threads must be an integer")).unwrap();
Luca Barbato's avatar
Luca Barbato committed
326

327
328
329
330
331
332
333
  if let Some(matches) = matches.subcommand_matches("advanced") {
    if let Some(shell) = matches.value_of("SHELL").map(|v| v.parse().unwrap()) {
      app.gen_completions_to("rav1e", shell, &mut std::io::stdout());
      std::process::exit(0);
    }
  }

Luca Barbato's avatar
Luca Barbato committed
334
335
336
337
338
  let io = EncoderIO {
    input: match matches.value_of("INPUT").unwrap() {
      "-" => Box::new(io::stdin()) as Box<dyn Read>,
      f => Box::new(File::open(&f).unwrap()) as Box<dyn Read>
    },
339
    output: create_muxer(matches.value_of("OUTPUT").unwrap()),
Luca Barbato's avatar
Luca Barbato committed
340
341
342
343
    rec: matches
      .value_of("RECONSTRUCTION")
      .map(|f| Box::new(File::create(&f).unwrap()) as Box<dyn Write>)
  };
Kyle Siefring's avatar
Kyle Siefring committed
344

345
346
  CliOptions {
    io,
347
    enc: parse_config(&matches),
348
    limit: matches.value_of("LIMIT").unwrap().parse().unwrap(),
349
350
351
    // Use `occurrences_of()` because `is_present()` is always true
    // if a parameter has a default value.
    color_range_specified: matches.occurrences_of("PIXEL_RANGE") > 0,
Vibhoothi's avatar
Vibhoothi committed
352
    skip: matches.value_of("SKIP").unwrap().parse().unwrap(),
353
    verbose: matches.is_present("VERBOSE"),
Luca Barbato's avatar
Luca Barbato committed
354
    threads,
355
356
    pass1file_name: matches.value_of("FIRST_PASS").map(|s| s.to_owned()),
    pass2file_name: matches.value_of("SECOND_PASS").map(|s| s.to_owned())
357
358
359
  }
}

360
fn parse_config(matches: &ArgMatches<'_>) -> EncoderConfig {
361
362
363
364
365
366
367
368
369
370
371
372
373
  let maybe_quantizer = matches.value_of("QP").map(|qp| qp.parse().unwrap());
  let maybe_bitrate =
    matches.value_of("BITRATE").map(|bitrate| bitrate.parse().unwrap());
  let quantizer = maybe_quantizer.unwrap_or_else(|| {
    if maybe_bitrate.is_some() {
      // If a bitrate is specified, the quantizer is the maximum allowed (e.g.,
      //  the minimum quality allowed), which by default should be
      //  unconstrained.
      255
    } else {
      100
    }
  });
374
  let bitrate: i32 = maybe_bitrate.unwrap_or(0);
375
  let train_rdo = matches.is_present("train-rdo");
376
377
  if quantizer == 0 {
    unimplemented!("Lossless encoding not yet implemented");
378
379
  } else if quantizer > 255 {
    panic!("Quantizer must be between 0-255");
380
381
  }

382
  let mut cfg = if let Some(settings) = matches.value_of("SPEED_TEST") {
383
    eprintln!("Running in speed test mode--ignoring other settings");
384
385
386
387
388
    let mut cfg = EncoderConfig::default();
    settings
      .split_whitespace()
      .for_each(|setting| apply_speed_test_cfg(&mut cfg, setting));
    cfg
389
390
391
392
  } else {
    let speed = matches.value_of("SPEED").unwrap().parse().unwrap();
    let max_interval: u64 = matches.value_of("KEYFRAME_INTERVAL").unwrap().parse().unwrap();
    let mut min_interval: u64 = matches.value_of("MIN_KEYFRAME_INTERVAL").unwrap().parse().unwrap();
393

394
395
396
397
398
    if matches.occurrences_of("MIN_KEYFRAME_INTERVAL") == 0 {
      min_interval = min_interval.min(max_interval);
    }

    // Validate arguments
399
400
401
402
    if max_interval < 1 {
      panic!("Keyframe interval must be greater than 0");
    }

403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    if speed > 10 {
      panic!("Speed must be between 0-10");
    } else if min_interval > max_interval {
      panic!("Maximum keyframe interval must be greater than or equal to minimum keyframe interval");
    }

    let color_primaries =
      matches.value_of("COLOR_PRIMARIES").unwrap().parse().unwrap_or_default();
    let transfer_characteristics = matches
      .value_of("TRANSFER_CHARACTERISTICS")
      .unwrap()
      .parse()
      .unwrap_or_default();
    let matrix_coefficients = matches
      .value_of("MATRIX_COEFFICIENTS")
      .unwrap()
      .parse()
      .unwrap_or_default();
421

422
423
424
425
426
427
428
429
    let mut cfg = EncoderConfig::with_speed_preset(speed);
    cfg.max_key_frame_interval = min_interval;
    cfg.max_key_frame_interval = max_interval;

    cfg.pixel_range = matches.value_of("PIXEL_RANGE").unwrap().parse().unwrap_or_default();
    cfg.color_description = if color_primaries == ColorPrimaries::Unspecified &&
      transfer_characteristics == TransferCharacteristics::Unspecified &&
      matrix_coefficients == MatrixCoefficients::Unspecified {
430
431
432
433
434
435
436
437
438
      // No need to set a color description with all parameters unspecified.
      None
    } else {
      Some(ColorDescription {
        color_primaries,
        transfer_characteristics,
        matrix_coefficients
      })
    };
439
440
441

    let mastering_display_opt = matches.value_of("MASTERING_DISPLAY").unwrap();
    cfg.mastering_display = if mastering_display_opt == "unspecified" { None } else {
442
      let (g_x, g_y, b_x, b_y, r_x, r_y, wp_x, wp_y, max_lum, min_lum) = scan_fmt!(mastering_display_opt, "G({},{})B({},{})R({},{})WP({},{})L({},{})", f64, f64, f64, f64, f64, f64, f64, f64, f64, f64).expect("Cannot parse the mastering display option");
443
444
445
      Some(MasteringDisplay {
        primaries: [
          Point {
446
447
            x: (r_x * ((1 << 16) as f64)).round() as u16,
            y: (r_y * ((1 << 16) as f64)).round() as u16,
448
449
          },
          Point {
450
451
            x: (g_x * ((1 << 16) as f64)).round() as u16,
            y: (g_y * ((1 << 16) as f64)).round() as u16,
452
453
          },
          Point {
454
455
            x: (b_x * ((1 << 16) as f64)).round() as u16,
            y: (b_y * ((1 << 16) as f64)).round() as u16,
456
457
458
          }
        ],
        white_point: Point {
459
460
          x: (wp_x * ((1 << 16) as f64)).round() as u16,
          y: (wp_y * ((1 << 16) as f64)).round() as u16,
461
        },
462
463
        max_luminance: (max_lum * ((1 << 8) as f64)).round() as u32,
        min_luminance: (min_lum * ((1 << 14) as f64)).round() as u32,
464
465
466
467
      })
    };

    let content_light_opt = matches.value_of("CONTENT_LIGHT").unwrap();
468
469
    let (cll, fall) = scan_fmt!(content_light_opt, "{},{}", u16, u16).expect("Cannot parse the content light option");
    cfg.content_light = if cll == 0 && fall == 0 { None } else {
470
      Some(ContentLight {
471
472
        max_content_light_level: cll,
        max_frame_average_light_level: fall
473
474
475
476
477
      })
    };
    cfg
  };

478
  cfg.quantizer = quantizer;
Luca Barbato's avatar
Luca Barbato committed
479
  cfg.min_quantizer = matches.value_of("MINQP").unwrap_or("0").parse().unwrap();
480
  cfg.bitrate = bitrate.checked_mul(1000).expect("Bitrate too high");
481
  cfg.reservoir_frame_delay = matches.value_of("RESERVOIR_FRAME_DELAY").map(|reservior_frame_delay| reservior_frame_delay.parse().unwrap());
482
  cfg.show_psnr = matches.is_present("PSNR");
483
  cfg.pass = None;
484
485
486
487
488
  cfg.stats_file = if cfg.pass.is_some() {
    Some(PathBuf::from(matches.value_of("STATS_FILE").unwrap()))
  } else {
    None
  };
489
  cfg.tune = matches.value_of("TUNE").unwrap().parse().unwrap();
490
491
492
493

  cfg.tile_cols_log2 = matches.value_of("TILE_COLS_LOG2").unwrap().parse().unwrap();
  cfg.tile_rows_log2 = matches.value_of("TILE_ROWS_LOG2").unwrap().parse().unwrap();

494
495
  cfg.tiles = matches.value_of("TILES").unwrap().parse().unwrap();

496
497
498
499
  if cfg.tile_cols_log2 > 6 || cfg.tile_rows_log2 > 6 {
    panic!("Log2 of tile columns and rows may not be greater than 6");
  }

500
  cfg.low_latency = matches.is_present("LOW_LATENCY");
501
  cfg.train_rdo = train_rdo;
502
503
  cfg
}
504

505
fn apply_speed_test_cfg(cfg: &mut EncoderConfig, setting: &str) {
506
507
  match setting {
    "baseline" => {
508
      cfg.speed_settings = SpeedSettings::default();
509
510
511
512
513
514
515
516
517
518
    },
    "min_block_size_4x4" => {
      cfg.speed_settings.min_block_size = BlockSize::BLOCK_4X4;
    },
    "min_block_size_8x8" => {
      cfg.speed_settings.min_block_size = BlockSize::BLOCK_8X8;
    },
    "min_block_size_32x32" => {
      cfg.speed_settings.min_block_size = BlockSize::BLOCK_32X32;
    },
519
520
521
    "min_block_size_64x64" => {
      cfg.speed_settings.min_block_size = BlockSize::BLOCK_64X64;
    },
522
523
524
525
526
527
528
529
530
531
532
533
    "multiref" => {
      cfg.speed_settings.multiref = true;
    },
    "fast_deblock" => {
      cfg.speed_settings.fast_deblock = true;
    },
    "reduced_tx_set" => {
      cfg.speed_settings.reduced_tx_set = true;
    },
    "tx_domain_distortion" => {
      cfg.speed_settings.tx_domain_distortion = true;
    },
534
535
536
    "tx_domain_rate" => {
      cfg.speed_settings.tx_domain_rate = true;
    },
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    "encode_bottomup" => {
      cfg.speed_settings.encode_bottomup = true;
    },
    "rdo_tx_decision" => {
      cfg.speed_settings.rdo_tx_decision = true;
    },
    "prediction_modes_keyframes" => {
      cfg.speed_settings.prediction_modes = PredictionModesSetting::ComplexKeyframes;
    },
    "prediction_modes_all" => {
      cfg.speed_settings.prediction_modes = PredictionModesSetting::ComplexAll;
    },
    "include_near_mvs" => {
      cfg.speed_settings.include_near_mvs = true;
    },
    "no_scene_detection" => {
      cfg.speed_settings.no_scene_detection = true;
    },
555
556
557
    "diamond_me" => {
      cfg.speed_settings.diamond_me = true;
    }
558
559
560
    "cdef" => {
      cfg.speed_settings.cdef = true;
    }
561
562
    setting => {
      panic!("Unrecognized speed test setting {}", setting);
563
    }
564
  };
565
566
}

567
568
#[derive(Debug, Clone, Copy)]
pub struct FrameSummary {
569
  // Frame size in bytes
570
  pub size: usize,
571
  pub input_frameno: u64,
572
  pub frame_type: FrameType,
573
  // PSNR for Y, U, and V planes
574
  pub psnr: Option<(f64, f64, f64)>,
575
576
}

577
578
impl<T: Pixel> From<Packet<T>> for FrameSummary {
  fn from(packet: Packet<T>) -> Self {
579
580
    Self {
      size: packet.data.len(),
581
      input_frameno: packet.input_frameno,
582
      frame_type: packet.frame_type,
583
      psnr: packet.psnr,
584
585
586
587
588
589
590
591
    }
  }
}

impl fmt::Display for FrameSummary {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
592
593
      "Input Frame {} - {} - {} bytes{}",
      self.input_frameno,
594
      self.frame_type,
595
596
597
598
      self.size,
      if let Some(psnr) = self.psnr {
        format!(" - PSNR: Y: {:.4}  Cb: {:.4}  Cr: {:.4}", psnr.0, psnr.1, psnr.2)
      } else { String::new() }
599
600
    )
  }
601
}
602

603
604
#[derive(Debug, Clone)]
pub struct ProgressInfo {
605
  // Frame rate of the video
606
  frame_rate: Rational,
607
  // The length of the whole video, in frames, if known
608
  total_frames: Option<usize>,
609
  // The time the encode was started
610
  time_started: Instant,
611
  // List of frames encoded so far
612
  frame_info: Vec<FrameSummary>,
613
614
615
616
  // Video size so far in bytes.
  //
  // This value will be updated in the CLI very frequently, so we cache the previous value
  // to reduce the overall complexity.
617
  encoded_size: usize,
618
  // Whether to display PSNR statistics during and at end of encode
619
  show_psnr: bool,
620
621
622
}

impl ProgressInfo {
623
  pub fn new(frame_rate: Rational, total_frames: Option<usize>, show_psnr: bool) -> Self {
624
625
626
627
628
629
    Self {
      frame_rate,
      total_frames,
      time_started: Instant::now(),
      frame_info: Vec::with_capacity(total_frames.unwrap_or_default()),
      encoded_size: 0,
630
      show_psnr,
631
632
633
634
635
636
637
638
639
640
641
642
643
    }
  }

  pub fn add_frame(&mut self, frame: FrameSummary) {
    self.encoded_size += frame.size;
    self.frame_info.push(frame);
  }

  pub fn frames_encoded(&self) -> usize {
    self.frame_info.len()
  }

  pub fn encoding_fps(&self) -> f64 {
644
645
    let duration = Instant::now().duration_since(self.time_started);
    self.frame_info.len() as f64 / (duration.as_secs() as f64 + duration.subsec_millis() as f64 / 1000f64)
646
647
648
649
650
651
  }

  pub fn video_fps(&self) -> f64 {
    self.frame_rate.num as f64 / self.frame_rate.den as f64
  }

652
  // Returns the bitrate of the frames so far, in bits/second
653
654
655
656
657
658
  pub fn bitrate(&self) -> usize {
    let bits = self.encoded_size * 8;
    let seconds = self.frame_info.len() as f64 / self.video_fps();
    (bits as f64 / seconds) as usize
  }

659
  // Estimates the final filesize in bytes, if the number of frames is known
660
661
662
663
664
  pub fn estimated_size(&self) -> usize {
    self.total_frames
      .map(|frames| self.encoded_size * frames / self.frames_encoded())
      .unwrap_or_default()
  }
665

666
667
668
669
670
671
  // Estimates the remaining encoding time in seconds, if the number of frames is known
  pub fn estimated_time(&self) -> f64 {
    self.total_frames
      .map(|frames| (frames - self.frames_encoded()) as f64 / self.encoding_fps())
      .unwrap_or_default()
  }
672

673
  // Number of frames of given type which appear in the video
674
675
676
677
678
679
  pub fn get_frame_type_count(&self, frame_type: FrameType) -> usize {
    self.frame_info.iter()
      .filter(|frame| frame.frame_type == frame_type)
      .count()
  }

680
  // Size in bytes of all frames of given frame type
681
682
683
684
685
686
687
  pub fn get_frame_type_size(&self, frame_type: FrameType) -> usize {
    self.frame_info.iter()
      .filter(|frame| frame.frame_type == frame_type)
      .map(|frame| frame.size)
      .sum()
  }

688
  pub fn print_summary(&self) -> String {
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
    let (key, key_size) = (
      self.get_frame_type_count(FrameType::KEY),
      self.get_frame_type_size(FrameType::KEY)
    );
    let (inter, inter_size) = (
      self.get_frame_type_count(FrameType::INTER),
      self.get_frame_type_size(FrameType::INTER)
    );
    let (ionly, ionly_size) = (
      self.get_frame_type_count(FrameType::INTRA_ONLY),
      self.get_frame_type_size(FrameType::INTRA_ONLY)
    );
    let (switch, switch_size) = (
      self.get_frame_type_count(FrameType::SWITCH),
      self.get_frame_type_size(FrameType::SWITCH)
    );
705
706
707
708
    format!("\
    Key Frames: {:>6}    avg size: {:>7} B\n\
    Inter:      {:>6}    avg size: {:>7} B\n\
    Intra Only: {:>6}    avg size: {:>7} B\n\
709
710
    Switch:     {:>6}    avg size: {:>7} B\
    {}",
711
      key, key_size / key,
712
      inter, inter_size.checked_div(inter).unwrap_or(0),
713
      ionly, ionly_size / key,
714
715
      switch, switch_size / key,
      if self.show_psnr {
716
717
718
719
720
721
722
723
724
        let psnr_y =
          self.frame_info.iter().map(|fi| fi.psnr.unwrap().0).sum::<f64>()
            / self.frame_info.len() as f64;
        let psnr_u =
          self.frame_info.iter().map(|fi| fi.psnr.unwrap().1).sum::<f64>()
            / self.frame_info.len() as f64;
        let psnr_v =
          self.frame_info.iter().map(|fi| fi.psnr.unwrap().2).sum::<f64>()
            / self.frame_info.len() as f64;
725
726
727
728
        format!("\nMean PSNR: Y: {:.4}  Cb: {:.4}  Cr: {:.4}  Avg: {:.4}",
                psnr_y, psnr_u, psnr_v,
                (psnr_y + psnr_u + psnr_v) / 3.0)
      } else { String::new() }
729
730
731
732
733
734
735
736
737
    )
  }
}

impl fmt::Display for ProgressInfo {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if let Some(total_frames) = self.total_frames {
      write!(
        f,
738
        "encoded {}/{} frames, {:.3} fps, {:.2} Kb/s, est. size: {:.2} MB, est. time: {:.0} s",
739
740
741
        self.frames_encoded(),
        total_frames,
        self.encoding_fps(),
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
742
        self.bitrate() as f64 / 1000f64,
743
744
        self.estimated_size() as f64 / (1024 * 1024) as f64,
        self.estimated_time()
745
746
747
748
      )
    } else {
      write!(
        f,
749
        "encoded {} frames, {:.3} fps, {:.2} Kb/s",
750
751
        self.frames_encoded(),
        self.encoding_fps(),
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
752
        self.bitrate() as f64 / 1000f64
753
      )
754
    }
Kyle Siefring's avatar
Kyle Siefring committed
755
  }
756
}