common.rs 15.1 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 clap::{App, Arg, ArgMatches};
Raphaël Zumer's avatar
Raphaël Zumer committed
11
use crate::{ColorPrimaries, TransferCharacteristics, MatrixCoefficients};
12
use rav1e::FrameType;
13
use rav1e::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
14

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

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

27
28
29
30
31
32
33
34
pub struct CliOptions {
  pub io: EncoderIO,
  pub enc: EncoderConfig,
  pub limit: usize,
  pub verbose: bool,
}

pub fn parse_cli() -> CliOptions {
Luca Barbato's avatar
Luca Barbato committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  let matches = App::new("rav1e")
    .version("0.1.0")
    .about("AV1 video encoder")
    .arg(
      Arg::with_name("INPUT")
        .help("Uncompressed YUV4MPEG2 video input")
        .required(true)
        .index(1)
    ).arg(
      Arg::with_name("OUTPUT")
        .help("Compressed AV1 in IVF video output")
        .short("o")
        .long("output")
        .required(true)
        .takes_value(true)
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    ).arg(
      Arg::with_name("PASS")
        .help("Specify first-pass or second-pass to run as a two-pass encode")
        .short("p")
        .long("pass")
        .takes_value(true)
        .possible_values(&["1", "2"])
    )
    .arg(
      Arg::with_name("STATS_FILE")
        .help("Custom location for first-pass stats file")
        .long("stats")
        .takes_value(true)
        .default_value("rav1e_stats.json")
64
65
66
67
68
    ).arg(
      Arg::with_name("RECONSTRUCTION")
        .short("r")
        .takes_value(true)
    ).arg(
Luca Barbato's avatar
Luca Barbato committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
      Arg::with_name("LIMIT")
        .help("Maximum number of frames to encode")
        .short("l")
        .long("limit")
        .takes_value(true)
        .default_value("0")
    ).arg(
      Arg::with_name("QP")
        .help("Quantizer (0-255)")
        .long("quantizer")
        .takes_value(true)
        .default_value("100")
    ).arg(
      Arg::with_name("SPEED")
        .help("Speed level (0(slow)-10(fast))")
        .short("s")
        .long("speed")
        .takes_value(true)
        .default_value("3")
Josh Holmer's avatar
Josh Holmer committed
88
89
90
91
92
93
94
    ).arg(
      Arg::with_name("MIN_KEYFRAME_INTERVAL")
        .help("Minimum interval between keyframes")
        .short("i")
        .long("min-keyint")
        .takes_value(true)
        .default_value("12")
95
96
    ).arg(
      Arg::with_name("KEYFRAME_INTERVAL")
Josh Holmer's avatar
Josh Holmer committed
97
        .help("Maximum interval between keyframes")
98
99
100
        .short("I")
        .long("keyint")
        .takes_value(true)
101
        .default_value("240")
102
103
    ).arg(
      Arg::with_name("LOW_LATENCY")
104
        .help("low latency mode. true or [false]")
105
106
        .long("low_latency")
        .takes_value(true)
107
        .default_value("false")
Luca Barbato's avatar
Luca Barbato committed
108
109
    ).arg(
      Arg::with_name("TUNE")
110
        .help("Quality tuning")
Luca Barbato's avatar
Luca Barbato committed
111
112
        .long("tune")
        .possible_values(&Tune::variants())
113
        .default_value("Psychovisual")
Luca Barbato's avatar
Luca Barbato committed
114
        .case_insensitive(true)
115
116
117
118
119
120
121
    ).arg(
      Arg::with_name("PIXEL_RANGE")
      .help("Pixel range")
      .long("range")
      .possible_values(&PixelRange::variants())
      .default_value("unspecified")
      .case_insensitive(true)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    ).arg(
      Arg::with_name("COLOR_PRIMARIES")
      .help("Color primaries used to describe color parameters.")
      .long("primaries")
      .possible_values(&ColorPrimaries::variants())
      .default_value("unspecified")
      .case_insensitive(true)
    ).arg(
      Arg::with_name("TRANSFER_CHARACTERISTICS")
      .help("Transfer characteristics used to describe color parameters.")
      .long("transfer")
      .possible_values(&TransferCharacteristics::variants())
      .default_value("unspecified")
      .case_insensitive(true)
    ).arg(
      Arg::with_name("MATRIX_COEFFICIENTS")
138
      .help("Matrix coefficients used to describe color parameters.")
139
140
141
142
      .long("matrix")
      .possible_values(&MatrixCoefficients::variants())
      .default_value("unspecified")
      .case_insensitive(true)
143
144
145
146
147
148
149
150
151
152
153
154
    ).arg(
      Arg::with_name("MASTERING_DISPLAY")
      .help("Mastering display primaries in the form of G(x,y)B(x,y)R(x,y)WP(x,y)L(max,min).")
      .long("mastering_display")
      .default_value("unspecified")
      .case_insensitive(true)
    ).arg(
      Arg::with_name("CONTENT_LIGHT")
      .help("Content light level used to describe content luminosity (cll,fall).")
      .long("content_light")
      .default_value("0,0")
      .case_insensitive(true)
155
156
157
158
159
    ).arg(
      Arg::with_name("VERBOSE")
        .help("verbose logging, output info for every frame")
        .long("verbose")
        .short("v")
160
161
162
163
    ).arg(
      Arg::with_name("PSNR")
        .help("calculate and display PSNR metrics")
        .long("psnr")
Luca Barbato's avatar
Luca Barbato committed
164
    ).get_matches();
165

Luca Barbato's avatar
Luca Barbato committed
166
167
168
169
170
171
172
173
174
175
176
177
178
  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>
    },
    output: match matches.value_of("OUTPUT").unwrap() {
      "-" => Box::new(io::stdout()) as Box<dyn Write>,
      f => Box::new(File::create(&f).unwrap()) as Box<dyn Write>
    },
    rec: matches
      .value_of("RECONSTRUCTION")
      .map(|f| Box::new(File::create(&f).unwrap()) as Box<dyn Write>)
  };
Kyle Siefring's avatar
Kyle Siefring committed
179

180
181
  CliOptions {
    io,
182
    enc: parse_config(&matches),
183
184
185
186
187
    limit: matches.value_of("LIMIT").unwrap().parse().unwrap(),
    verbose: matches.is_present("VERBOSE"),
  }
}

188
fn parse_config(matches: &ArgMatches<'_>) -> EncoderConfig {
189
190
  let speed = matches.value_of("SPEED").unwrap().parse().unwrap();
  let quantizer = matches.value_of("QP").unwrap().parse().unwrap();
191
192
193
194
195
196
  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();

  if matches.occurrences_of("MIN_KEYFRAME_INTERVAL") == 0 {
    min_interval = min_interval.min(max_interval);
  }
197
198
199
200
201
202

  // Validate arguments
  if quantizer == 0 {
    unimplemented!("Lossless encoding not yet implemented");
  } else if quantizer > 255 || speed > 10 {
    panic!("argument out of range");
Josh Holmer's avatar
Josh Holmer committed
203
204
  } else if min_interval > max_interval {
    panic!("Maximum keyframe interval must be greater than or equal to minimum keyframe interval");
205
206
  }

207
208
209
210
211
212
213
214
215
216
217
218
  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();
219

220
  let mut cfg = EncoderConfig::with_speed_preset(speed);
Josh Holmer's avatar
Josh Holmer committed
221
222
  cfg.max_key_frame_interval = min_interval;
  cfg.max_key_frame_interval = max_interval;
223
224
  cfg.low_latency = matches.value_of("LOW_LATENCY").unwrap().parse().unwrap();
  cfg.tune = matches.value_of("TUNE").unwrap().parse().unwrap();
225
226

  cfg.pixel_range = matches.value_of("PIXEL_RANGE").unwrap().parse().unwrap_or_default();
227
228
229
230
231
232
233
234
235
236
237
238
  cfg.color_description = if color_primaries == ColorPrimaries::Unspecified &&
    transfer_characteristics == TransferCharacteristics::Unspecified &&
    matrix_coefficients == MatrixCoefficients::Unspecified {
      // No need to set a color description with all parameters unspecified.
      None
    } else {
      Some(ColorDescription {
        color_primaries,
        transfer_characteristics,
        matrix_coefficients
      })
    };
239
  cfg.quantizer = quantizer;
240
  cfg.show_psnr = matches.is_present("PSNR");
241
242
243
244
245
246
  cfg.pass = matches.value_of("PASS").map(|pass| pass.parse().unwrap());
  cfg.stats_file = if cfg.pass.is_some() {
    Some(PathBuf::from(matches.value_of("STATS_FILE").unwrap()))
  } else {
    None
  };
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  let mastering_display_opt = matches.value_of("MASTERING_DISPLAY").unwrap();
  cfg.mastering_display = if mastering_display_opt == "unspecified" { None } else {
    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);
    Some(MasteringDisplay {
      primaries: [
        Point{
          x: (r_x.unwrap() * ((1 << 16) as f64)).round() as u16,
          y: (r_y.unwrap() * ((1 << 16) as f64)).round() as u16,
        },
        Point{
          x: (g_x.unwrap() * ((1 << 16) as f64)).round() as u16,
          y: (g_y.unwrap() * ((1 << 16) as f64)).round() as u16,
        },
        Point{
          x: (b_x.unwrap() * ((1 << 16) as f64)).round() as u16,
          y: (b_y.unwrap() * ((1 << 16) as f64)).round() as u16,
        }
      ],
      white_point: Point{
        x: (wp_x.unwrap() * ((1 << 16) as f64)).round() as u16,
        y: (wp_y.unwrap() * ((1 << 16) as f64)).round() as u16,
      },
      max_luminance: (max_lum.unwrap() * ((1 << 8) as f64)).round() as u32,
      min_luminance: (min_lum.unwrap() * ((1 << 14) as f64)).round() as u32,
    })
  };

  let content_light_opt = matches.value_of("CONTENT_LIGHT").unwrap();
  let (cll, fall) = scan_fmt!(content_light_opt, "{},{}", u16, u16);
  cfg.content_light = if cll.unwrap() == 0 && fall.unwrap() == 0 { None } else {
    Some(ContentLight {
      max_content_light_level : cll.unwrap(),
      max_frame_average_light_level : fall.unwrap()
    })
  };

284
285
286
  cfg
}

287
288
#[derive(Debug, Clone, Copy)]
pub struct FrameSummary {
289
  // Frame size in bytes
290
291
  pub size: usize,
  pub number: u64,
292
  pub frame_type: FrameType,
293
  // PSNR for Y, U, and V planes
294
  pub psnr: Option<(f64, f64, f64)>,
295
296
297
298
299
300
301
302
}

impl From<Packet> for FrameSummary {
  fn from(packet: Packet) -> Self {
    Self {
      size: packet.data.len(),
      number: packet.number,
      frame_type: packet.frame_type,
303
      psnr: packet.psnr,
304
305
306
307
308
309
310
311
    }
  }
}

impl fmt::Display for FrameSummary {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
312
      "Frame {} - {} - {} bytes{}",
313
314
      self.number,
      self.frame_type,
315
316
317
318
      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() }
319
320
    )
  }
321
}
322

323
324
#[derive(Debug, Clone)]
pub struct ProgressInfo {
325
  // Frame rate of the video
326
  frame_rate: Rational,
327
  // The length of the whole video, in frames, if known
328
  total_frames: Option<usize>,
329
  // The time the encode was started
330
  time_started: Instant,
331
  // List of frames encoded so far
332
  frame_info: Vec<FrameSummary>,
333
334
335
336
  // 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.
337
  encoded_size: usize,
338
  // Whether to display PSNR statistics during and at end of encode
339
  show_psnr: bool,
340
341
342
}

impl ProgressInfo {
343
  pub fn new(frame_rate: Rational, total_frames: Option<usize>, show_psnr: bool) -> Self {
344
345
346
347
348
349
    Self {
      frame_rate,
      total_frames,
      time_started: Instant::now(),
      frame_info: Vec::with_capacity(total_frames.unwrap_or_default()),
      encoded_size: 0,
350
      show_psnr,
351
352
353
354
355
356
357
358
359
360
361
362
363
    }
  }

  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 {
364
365
    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)
366
367
368
369
370
371
  }

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

372
  // Returns the bitrate of the frames so far, in bits/second
373
374
375
376
377
378
  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
  }

379
  // Estimates the final filesize in bytes, if the number of frames is known
380
381
382
383
384
  pub fn estimated_size(&self) -> usize {
    self.total_frames
      .map(|frames| self.encoded_size * frames / self.frames_encoded())
      .unwrap_or_default()
  }
385

386
387
388
389
390
391
  // 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()
  }
392

393
  // Number of frames of given type which appear in the video
394
395
396
397
398
399
  pub fn get_frame_type_count(&self, frame_type: FrameType) -> usize {
    self.frame_info.iter()
      .filter(|frame| frame.frame_type == frame_type)
      .count()
  }

400
  // Size in bytes of all frames of given frame type
401
402
403
404
405
406
407
  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()
  }

408
  pub fn print_summary(&self) -> String {
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    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)
    );
425
426
427
428
    format!("\
    Key Frames: {:>6}    avg size: {:>7} B\n\
    Inter:      {:>6}    avg size: {:>7} B\n\
    Intra Only: {:>6}    avg size: {:>7} B\n\
429
430
    Switch:     {:>6}    avg size: {:>7} B\
    {}",
431
      key, key_size / key,
432
      inter, inter_size.checked_div(inter).unwrap_or(0),
433
      ionly, ionly_size / key,
434
435
      switch, switch_size / key,
      if self.show_psnr {
436
437
438
439
440
441
442
443
444
        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;
445
446
447
448
        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() }
449
450
451
452
453
454
455
456
457
    )
  }
}

impl fmt::Display for ProgressInfo {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if let Some(total_frames) = self.total_frames {
      write!(
        f,
458
        "encoded {}/{} frames, {:.3} fps, {:.2} Kb/s, est. size: {:.2} MB, est. time: {:.0} s",
459
460
461
462
        self.frames_encoded(),
        total_frames,
        self.encoding_fps(),
        self.bitrate() as f64 / 1024f64,
463
464
        self.estimated_size() as f64 / (1024 * 1024) as f64,
        self.estimated_time()
465
466
467
468
      )
    } else {
      write!(
        f,
469
        "encoded {} frames, {:.3} fps, {:.2} Kb/s",
470
471
472
473
        self.frames_encoded(),
        self.encoding_fps(),
        self.bitrate() as f64 / 1024f64
      )
474
    }
Kyle Siefring's avatar
Kyle Siefring committed
475
  }
476
}