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::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
13

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

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

26
27
28
29
30
31
32
33
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  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)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    ).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")
63
64
65
66
67
    ).arg(
      Arg::with_name("RECONSTRUCTION")
        .short("r")
        .takes_value(true)
    ).arg(
Luca Barbato's avatar
Luca Barbato committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
      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
87
88
89
90
91
92
93
    ).arg(
      Arg::with_name("MIN_KEYFRAME_INTERVAL")
        .help("Minimum interval between keyframes")
        .short("i")
        .long("min-keyint")
        .takes_value(true)
        .default_value("12")
94
95
    ).arg(
      Arg::with_name("KEYFRAME_INTERVAL")
Josh Holmer's avatar
Josh Holmer committed
96
        .help("Maximum interval between keyframes")
97
98
99
        .short("I")
        .long("keyint")
        .takes_value(true)
100
        .default_value("240")
101
102
    ).arg(
      Arg::with_name("LOW_LATENCY")
103
        .help("low latency mode. true or [false]")
104
105
        .long("low_latency")
        .takes_value(true)
106
        .default_value("false")
Luca Barbato's avatar
Luca Barbato committed
107
108
    ).arg(
      Arg::with_name("TUNE")
109
        .help("Quality tuning")
Luca Barbato's avatar
Luca Barbato committed
110
111
        .long("tune")
        .possible_values(&Tune::variants())
112
        .default_value("Psychovisual")
Luca Barbato's avatar
Luca Barbato committed
113
        .case_insensitive(true)
114
115
116
117
118
119
120
    ).arg(
      Arg::with_name("PIXEL_RANGE")
      .help("Pixel range")
      .long("range")
      .possible_values(&PixelRange::variants())
      .default_value("unspecified")
      .case_insensitive(true)
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    ).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")
137
      .help("Matrix coefficients used to describe color parameters.")
138
139
140
141
      .long("matrix")
      .possible_values(&MatrixCoefficients::variants())
      .default_value("unspecified")
      .case_insensitive(true)
142
143
144
145
146
147
148
149
150
151
152
153
    ).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)
154
155
156
157
158
    ).arg(
      Arg::with_name("VERBOSE")
        .help("verbose logging, output info for every frame")
        .long("verbose")
        .short("v")
159
160
161
162
    ).arg(
      Arg::with_name("PSNR")
        .help("calculate and display PSNR metrics")
        .long("psnr")
Luca Barbato's avatar
Luca Barbato committed
163
    ).get_matches();
164

Luca Barbato's avatar
Luca Barbato committed
165
166
167
168
169
170
171
172
173
174
175
176
177
  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
178

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

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

  // 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
202
203
  } else if min_interval > max_interval {
    panic!("Maximum keyframe interval must be greater than or equal to minimum keyframe interval");
204
205
  }

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

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

  cfg.pixel_range = matches.value_of("PIXEL_RANGE").unwrap().parse().unwrap_or_default();
226
227
228
229
230
231
232
233
234
235
236
237
  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
      })
    };
238
  cfg.quantizer = quantizer;
239
  cfg.show_psnr = matches.is_present("PSNR");
240
241
242
243
244
245
  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
  };
246

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
  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()
    })
  };

283
284
285
  cfg
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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