common.rs 14.5 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::time::Instant;
18
19

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

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

Luca Barbato's avatar
Luca Barbato committed
150
151
152
153
154
155
156
157
158
159
160
161
162
  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
163

164
165
  CliOptions {
    io,
166
    enc: parse_config(&matches),
167
168
169
170
171
    limit: matches.value_of("LIMIT").unwrap().parse().unwrap(),
    verbose: matches.is_present("VERBOSE"),
  }
}

172
173
174
fn parse_config(matches: &ArgMatches) -> EncoderConfig {
  let speed = matches.value_of("SPEED").unwrap().parse().unwrap();
  let quantizer = matches.value_of("QP").unwrap().parse().unwrap();
175
176
177
178
179
180
  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);
  }
181
182
183
184
185
186

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

191
192
193
194
195
196
197
198
199
200
201
202
  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();
203

204
  let mut cfg = EncoderConfig::with_speed_preset(speed);
Josh Holmer's avatar
Josh Holmer committed
205
206
  cfg.max_key_frame_interval = min_interval;
  cfg.max_key_frame_interval = max_interval;
207
208
  cfg.low_latency = matches.value_of("LOW_LATENCY").unwrap().parse().unwrap();
  cfg.tune = matches.value_of("TUNE").unwrap().parse().unwrap();
209
210

  cfg.pixel_range = matches.value_of("PIXEL_RANGE").unwrap().parse().unwrap_or_default();
211
212
213
214
215
216
217
218
219
220
221
222
  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
      })
    };
223
  cfg.quantizer = quantizer;
224
  cfg.show_psnr = matches.is_present("PSNR");
225

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  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()
    })
  };

262
263
264
  cfg
}

265
266
#[derive(Debug, Clone, Copy)]
pub struct FrameSummary {
267
  // Frame size in bytes
268
269
  pub size: usize,
  pub number: u64,
270
  pub frame_type: FrameType,
271
  // PSNR for Y, U, and V planes
272
  pub psnr: Option<(f64, f64, f64)>,
273
274
275
276
277
278
279
280
}

impl From<Packet> for FrameSummary {
  fn from(packet: Packet) -> Self {
    Self {
      size: packet.data.len(),
      number: packet.number,
      frame_type: packet.frame_type,
281
      psnr: packet.psnr,
282
283
284
285
286
287
288
289
    }
  }
}

impl fmt::Display for FrameSummary {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
290
      "Frame {} - {} - {} bytes{}",
291
292
      self.number,
      self.frame_type,
293
294
295
296
      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() }
297
298
    )
  }
299
}
300

301
302
#[derive(Debug, Clone)]
pub struct ProgressInfo {
303
  // Frame rate of the video
304
  frame_rate: Rational,
305
  // The length of the whole video, in frames, if known
306
  total_frames: Option<usize>,
307
  // The time the encode was started
308
  time_started: Instant,
309
  // List of frames encoded so far
310
  frame_info: Vec<FrameSummary>,
311
312
313
314
  // 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.
315
  encoded_size: usize,
316
  // Whether to display PSNR statistics during and at end of encode
317
  show_psnr: bool,
318
319
320
}

impl ProgressInfo {
321
  pub fn new(frame_rate: Rational, total_frames: Option<usize>, show_psnr: bool) -> Self {
322
323
324
325
326
327
    Self {
      frame_rate,
      total_frames,
      time_started: Instant::now(),
      frame_info: Vec::with_capacity(total_frames.unwrap_or_default()),
      encoded_size: 0,
328
      show_psnr,
329
330
331
332
333
334
335
336
337
338
339
340
341
    }
  }

  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 {
342
343
    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)
344
345
346
347
348
349
  }

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

350
  // Returns the bitrate of the frames so far, in bits/second
351
352
353
354
355
356
  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
  }

357
  // Estimates the final filesize in bytes, if the number of frames is known
358
359
360
361
362
  pub fn estimated_size(&self) -> usize {
    self.total_frames
      .map(|frames| self.encoded_size * frames / self.frames_encoded())
      .unwrap_or_default()
  }
363

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

371
  // Number of frames of given type which appear in the video
372
373
374
375
376
377
  pub fn get_frame_type_count(&self, frame_type: FrameType) -> usize {
    self.frame_info.iter()
      .filter(|frame| frame.frame_type == frame_type)
      .count()
  }

378
  // Size in bytes of all frames of given frame type
379
380
381
382
383
384
385
386
  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()
  }

  pub fn print_stats(&self) -> String {
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    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)
    );
403
404
405
406
    format!("\
    Key Frames: {:>6}    avg size: {:>7} B\n\
    Inter:      {:>6}    avg size: {:>7} B\n\
    Intra Only: {:>6}    avg size: {:>7} B\n\
407
408
    Switch:     {:>6}    avg size: {:>7} B\
    {}",
409
      key, key_size / key,
410
      inter, inter_size.checked_div(inter).unwrap_or(0),
411
      ionly, ionly_size / key,
412
413
      switch, switch_size / key,
      if self.show_psnr {
414
415
416
417
418
419
420
421
422
        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;
423
424
425
426
        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() }
427
428
429
430
431
432
433
434
435
    )
  }
}

impl fmt::Display for ProgressInfo {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if let Some(total_frames) = self.total_frames {
      write!(
        f,
436
        "encoded {}/{} frames, {:.3} fps, {:.2} Kb/s, est. size: {:.2} MB, est. time: {:.0} s",
437
438
439
440
        self.frames_encoded(),
        total_frames,
        self.encoding_fps(),
        self.bitrate() as f64 / 1024f64,
441
442
        self.estimated_size() as f64 / (1024 * 1024) as f64,
        self.estimated_time()
443
444
445
446
      )
    } else {
      write!(
        f,
447
        "encoded {} frames, {:.3} fps, {:.2} Kb/s",
448
449
450
451
        self.frames_encoded(),
        self.encoding_fps(),
        self.bitrate() as f64 / 1024f64
      )
452
    }
Kyle Siefring's avatar
Kyle Siefring committed
453
  }
454
}