api.rs 27.3 KB
Newer Older
rzumer's avatar
rzumer committed
1 2 3 4 5 6 7 8 9
// Copyright (c) 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.

Raphaël Zumer's avatar
Raphaël Zumer committed
10
use bitstream_io::*;
11 12 13
use crate::encoder::*;
use crate::metrics::calculate_frame_psnr;
use crate::partition::*;
14
use crate::rate::RCState;
15 16 17
use crate::rate::FRAME_NSUBTYPES;
use crate::rate::FRAME_SUBTYPE_I;
use crate::rate::FRAME_SUBTYPE_P;
18
use crate::scenechange::SceneChangeDetector;
19
use crate::util::Pixel;
Raphaël Zumer's avatar
Raphaël Zumer committed
20
use self::EncoderStatus::*;
Luca Barbato's avatar
Luca Barbato committed
21

Raphaël Zumer's avatar
Raphaël Zumer committed
22
use std::{cmp, fmt, io};
fbossen's avatar
fbossen committed
23
use std::collections::BTreeMap;
Luca Barbato's avatar
Luca Barbato committed
24
use std::sync::Arc;
Josh Holmer's avatar
Josh Holmer committed
25
use std::collections::BTreeSet;
26
use std::path::PathBuf;
Josh Holmer's avatar
Josh Holmer committed
27 28

const LOOKAHEAD_FRAMES: u64 = 10;
Luca Barbato's avatar
Luca Barbato committed
29 30 31

// TODO: use the num crate?
#[derive(Clone, Copy, Debug)]
32
#[repr(C)]
Luca Barbato's avatar
Luca Barbato committed
33 34 35
pub struct Rational {
  pub num: u64,
  pub den: u64
Luca Barbato's avatar
Luca Barbato committed
36 37
}

Luca Barbato's avatar
Luca Barbato committed
38 39 40
impl Rational {
  pub fn new(num: u64, den: u64) -> Self {
    Rational { num, den }
Luca Barbato's avatar
Luca Barbato committed
41 42 43
  }
}

44 45 46 47 48 49 50
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct Point {
  pub x: u16,
  pub y: u16
}

51
#[derive(Clone, Debug)]
52
pub struct EncoderConfig {
53
  // output size
54 55
  pub width: usize,
  pub height: usize,
56 57

  // data format and ancillary color information
58 59 60
  pub bit_depth: usize,
  pub chroma_sampling: ChromaSampling,
  pub chroma_sample_position: ChromaSamplePosition,
61 62 63 64 65 66
  pub pixel_range: PixelRange,
  pub color_description: Option<ColorDescription>,
  pub mastering_display: Option<MasteringDisplay>,
  pub content_light: Option<ContentLight>,

  // encoder configuration
67
  pub time_base: Rational,
Josh Holmer's avatar
Josh Holmer committed
68 69 70 71
  /// The *minimum* interval between two keyframes
  pub min_key_frame_interval: u64,
  /// The *maximum* interval between two keyframes
  pub max_key_frame_interval: u64,
72
  pub low_latency: bool,
73
  pub quantizer: usize,
74
  pub bitrate: i32,
75 76
  pub tune: Tune,
  pub speed_settings: SpeedSettings,
77 78
  /// `None` for one-pass encode. `Some(1)` or `Some(2)` for two-pass encoding.
  pub pass: Option<u8>,
79
  pub show_psnr: bool,
80
  pub stats_file: Option<PathBuf>,
81
  pub train_rdo: bool,
82 83 84 85
}

impl Default for EncoderConfig {
  fn default() -> Self {
86
    const DEFAULT_SPEED: usize = 5;
87
    Self::with_speed_preset(DEFAULT_SPEED)
88 89 90
  }
}

91 92 93
impl EncoderConfig {
  pub fn with_speed_preset(speed: usize) -> Self {
    EncoderConfig {
94 95
      width: 640,
      height: 480,
96

97 98 99
      bit_depth: 8,
      chroma_sampling: ChromaSampling::Cs420,
      chroma_sample_position: ChromaSamplePosition::Unknown,
100 101 102 103 104
      pixel_range: PixelRange::Unspecified,
      color_description: None,
      mastering_display: None,
      content_light: None,

105
      time_base: Rational { num: 30, den: 1 },
Josh Holmer's avatar
Josh Holmer committed
106 107
      min_key_frame_interval: 12,
      max_key_frame_interval: 240,
108
      low_latency: false,
109
      quantizer: 100,
110
      bitrate: 0,
111
      tune: Tune::default(),
112
      speed_settings: SpeedSettings::from_preset(speed),
113
      pass: None,
114
      show_psnr: false,
115
      stats_file: None,
116
      train_rdo: false
117 118 119 120 121 122 123 124 125 126 127
    }
  }
}

#[derive(Clone, Copy, Debug)]
pub struct SpeedSettings {
  pub min_block_size: BlockSize,
  pub multiref: bool,
  pub fast_deblock: bool,
  pub reduced_tx_set: bool,
  pub tx_domain_distortion: bool,
128
  pub tx_domain_rate: bool,
129 130 131 132
  pub encode_bottomup: bool,
  pub rdo_tx_decision: bool,
  pub prediction_modes: PredictionModesSetting,
  pub include_near_mvs: bool,
133
  pub no_scene_detection: bool,
134
  pub diamond_me: bool
135 136 137 138 139
}

impl Default for SpeedSettings {
  fn default() -> Self {
    SpeedSettings {
140
      min_block_size: BlockSize::BLOCK_16X16,
141 142 143 144
      multiref: false,
      fast_deblock: false,
      reduced_tx_set: false,
      tx_domain_distortion: false,
145
      tx_domain_rate: false,
146 147 148 149 150
      encode_bottomup: false,
      rdo_tx_decision: false,
      prediction_modes: PredictionModesSetting::Simple,
      include_near_mvs: false,
      no_scene_detection: false,
151
      diamond_me: false,
152 153
    }
  }
154 155 156 157 158 159 160 161 162 163
}

impl SpeedSettings {
  pub fn from_preset(speed: usize) -> Self {
    SpeedSettings {
      min_block_size: Self::min_block_size_preset(speed),
      multiref: Self::multiref_preset(speed),
      fast_deblock: Self::fast_deblock_preset(speed),
      reduced_tx_set: Self::reduced_tx_set_preset(speed),
      tx_domain_distortion: Self::tx_domain_distortion_preset(speed),
164
      tx_domain_rate: Self::tx_domain_rate_preset(speed),
165 166 167 168
      encode_bottomup: Self::encode_bottomup_preset(speed),
      rdo_tx_decision: Self::rdo_tx_decision_preset(speed),
      prediction_modes: Self::prediction_modes_preset(speed),
      include_near_mvs: Self::include_near_mvs_preset(speed),
169
      no_scene_detection: Self::no_scene_detection_preset(speed),
170
      diamond_me: Self::diamond_me_preset(speed),
171 172 173
    }
  }

174 175
  /// This preset is set this way because 8x8 with reduced TX set is faster but with equivalent
  /// or better quality compared to 16x16 or 32x32 (to which reduced TX set does not apply).
176
  fn min_block_size_preset(speed: usize) -> BlockSize {
177
    if speed == 0 {
178
      BlockSize::BLOCK_4X4
179
    } else if speed <= 8 {
180 181 182 183 184 185
      BlockSize::BLOCK_8X8
    } else {
      BlockSize::BLOCK_64X64
    }
  }

186 187 188 189
  /// Multiref is enabled automatically if low_latency is false,
  /// but if someone is setting low_latency to true manually,
  /// multiref has a large speed penalty with low quality gain.
  /// Because low_latency can be set manually, this setting is conservative.
190
  fn multiref_preset(speed: usize) -> bool {
191
    speed <= 1
192 193 194
  }

  fn fast_deblock_preset(speed: usize) -> bool {
195
    speed >= 8
196 197 198
  }

  fn reduced_tx_set_preset(speed: usize) -> bool {
199
    speed >= 5
200 201
  }

202 203 204
  /// TX domain distortion is always faster, with no significant quality change
  fn tx_domain_distortion_preset(_speed: usize) -> bool {
    true
205 206
  }

207 208 209 210
  fn tx_domain_rate_preset(_speed: usize) -> bool {
    false
  }

211 212 213 214 215 216 217 218 219
  fn encode_bottomup_preset(speed: usize) -> bool {
    speed == 0
  }

  fn rdo_tx_decision_preset(speed: usize) -> bool {
    speed <= 3
  }

  fn prediction_modes_preset(speed: usize) -> PredictionModesSetting {
220
    if speed <= 1 {
221
      PredictionModesSetting::ComplexAll
222
    } else if speed <= 5 {
223 224 225 226 227 228 229 230 231
      PredictionModesSetting::ComplexKeyframes
    } else {
      PredictionModesSetting::Simple
    }
  }

  fn include_near_mvs_preset(speed: usize) -> bool {
    speed <= 2
  }
232 233 234 235

  fn no_scene_detection_preset(speed: usize) -> bool {
    speed == 10
  }
236

237 238 239 240 241 242 243
  /// Currently Diamond ME gives better quality than full search on most videos,
  /// in addition to being faster.
  /// There are a few outliers, such as the Wikipedia test clip.
  ///
  /// TODO: Revisit this setting if full search quality improves in the future.
  fn diamond_me_preset(_speed: usize) -> bool {
    true
244
  }
245 246
}

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
#[allow(dead_code, non_camel_case_types)]
#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
#[repr(C)]
pub enum FrameType {
  KEY,
  INTER,
  INTRA_ONLY,
  SWITCH
}

impl fmt::Display for FrameType {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    use self::FrameType::*;
    match self {
      KEY => write!(f, "Key frame"),
      INTER => write!(f, "Inter frame"),
      INTRA_ONLY => write!(f, "Intra only frame"),
      SWITCH => write!(f, "Switching frame"),
    }
  }
}

269 270 271 272 273 274 275
#[derive(Clone, Copy, Debug, PartialOrd, PartialEq)]
pub enum PredictionModesSetting {
  Simple,
  ComplexKeyframes,
  ComplexAll,
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub enum ChromaSampling {
  Cs420,
  Cs422,
  Cs444,
  Cs400,
}

impl Default for ChromaSampling {
  fn default() -> Self {
    ChromaSampling::Cs420
  }
}

impl ChromaSampling {
  // Provides the sampling period in the horizontal and vertical axes.
  pub fn sampling_period(self) -> (usize, usize) {
    use self::ChromaSampling::*;
    match self {
      Cs420 => (2, 2),
      Cs422 => (2, 1),
      Cs444 => (1, 1),
      Cs400 => (2, 2),
    }
  }
}

#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub enum ChromaSamplePosition {
  Unknown,
  Vertical,
  Colocated
}

impl Default for ChromaSamplePosition {
  fn default() -> Self {
    ChromaSamplePosition::Unknown
  }
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
arg_enum!{
  #[derive(Debug, Clone, Copy, PartialEq)]
  #[repr(C)]
  pub enum PixelRange {
      Unspecified = 0,
      Limited,
      Full,
  }
}

impl Default for PixelRange {
    fn default() -> Self {
        PixelRange::Unspecified
    }
}

334 335
arg_enum!{
  #[derive(Debug, Clone, Copy, PartialEq)]
336
  #[repr(C)]
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
  pub enum MatrixCoefficients {
      Identity = 0,
      BT709,
      Unspecified,
      BT470M = 4,
      BT470BG,
      ST170M,
      ST240M,
      YCgCo,
      BT2020NonConstantLuminance,
      BT2020ConstantLuminance,
      ST2085,
      ChromaticityDerivedNonConstantLuminance,
      ChromaticityDerivedConstantLuminance,
      ICtCp,
  }
353 354 355 356 357 358 359 360
}

impl Default for MatrixCoefficients {
    fn default() -> Self {
        MatrixCoefficients::Unspecified
    }
}

361
arg_enum!{
362
  #[derive(Debug, Clone, Copy, PartialEq)]
363
  #[repr(C)]
364 365 366 367 368 369 370 371 372 373 374 375 376 377
  pub enum ColorPrimaries {
      BT709 = 1,
      Unspecified,
      BT470M = 4,
      BT470BG,
      ST170M,
      ST240M,
      Film,
      BT2020,
      ST428,
      P3DCI,
      P3Display,
      Tech3213 = 22,
  }
378 379 380 381 382 383 384 385
}

impl Default for ColorPrimaries {
    fn default() -> Self {
        ColorPrimaries::Unspecified
    }
}

386
arg_enum!{
387
  #[derive(Debug, Clone, Copy, PartialEq)]
388
  #[repr(C)]
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  pub enum TransferCharacteristics {
      BT1886 = 1,
      Unspecified,
      BT470M = 4,
      BT470BG,
      ST170M,
      ST240M,
      Linear,
      Logarithmic100,
      Logarithmic316,
      XVYCC,
      BT1361E,
      SRGB,
      BT2020Ten,
      BT2020Twelve,
      PerceptualQuantizer,
      ST428,
      HybridLogGamma,
  }
408 409 410 411 412 413 414 415
}

impl Default for TransferCharacteristics {
    fn default() -> Self {
        TransferCharacteristics::Unspecified
    }
}

416 417 418 419 420 421 422
#[derive(Copy, Clone, Debug)]
pub struct ColorDescription {
    pub color_primaries: ColorPrimaries,
    pub transfer_characteristics: TransferCharacteristics,
    pub matrix_coefficients: MatrixCoefficients
}

423 424 425 426 427 428 429 430 431 432 433 434 435 436
#[derive(Copy, Clone, Debug)]
pub struct MasteringDisplay {
    pub primaries: [Point; 3],
    pub white_point: Point,
    pub max_luminance: u32,
    pub min_luminance: u32,
}

#[derive(Copy, Clone, Debug)]
pub struct ContentLight {
    pub max_content_light_level: u16,
    pub max_frame_average_light_level: u16,
}

437
/// Contain all the encoder configuration
438
#[derive(Clone, Debug)]
439
pub struct Config {
Luca Barbato's avatar
Luca Barbato committed
440 441 442 443
  pub enc: EncoderConfig
}

impl Config {
Luca Barbato's avatar
Luca Barbato committed
444 445
  pub fn parse(&mut self, key: &str, value: &str) -> Result<(), EncoderStatus> {
    match key {
446
      "low_latency" => self.enc.low_latency = value.parse().map_err(|_e| ParseError)?,
Josh Holmer's avatar
Josh Holmer committed
447 448
      "min_key_frame_interval" => self.enc.min_key_frame_interval = value.parse().map_err(|_e| ParseError)?,
      "key_frame_interval" => self.enc.max_key_frame_interval = value.parse().map_err(|_e| ParseError)?,
449
      "quantizer" => self.enc.quantizer = value.parse().map_err(|_e| ParseError)?,
450
      "speed" => self.enc.speed_settings = SpeedSettings::from_preset(value.parse().map_err(|_e| ParseError)?),
451 452
      "tune" => self.enc.tune = value.parse().map_err(|_e| ParseError)?,
      _ => return Err(InvalidKey)
Luca Barbato's avatar
Luca Barbato committed
453 454 455 456 457
    }

    Ok(())
  }

458
  pub fn new_context<T: Pixel>(&self) -> Context<T> {
459 460 461
    // initialize with temporal delimiter
    let packet_data = TEMPORAL_DELIMITER.to_vec();

462 463 464 465 466 467
    let maybe_ac_qi_max = if self.enc.quantizer < 255 {
      Some(self.enc.quantizer as u8)
    } else {
      None
    };

Josh Holmer's avatar
Josh Holmer committed
468 469
    Context {
      frame_count: 0,
470
      limit: 0,
Josh Holmer's avatar
Josh Holmer committed
471
      idx: 0,
Josh Holmer's avatar
Josh Holmer committed
472
      frames_processed: 0,
Josh Holmer's avatar
Josh Holmer committed
473
      frame_q: BTreeMap::new(),
Josh Holmer's avatar
Josh Holmer committed
474 475
      frame_data: BTreeMap::new(),
      keyframes: BTreeSet::new(),
476
      packet_data,
Josh Holmer's avatar
Josh Holmer committed
477 478
      segment_start_idx: 0,
      segment_start_frame: 0,
479
      keyframe_detector: SceneChangeDetector::new(self.enc.bit_depth),
480
      config: self.clone(),
481 482 483 484 485 486 487 488 489 490
      rc_state: RCState::new(
        self.enc.width as i32,
        self.enc.height as i32,
        self.enc.time_base.num as i64,
        self.enc.time_base.den as i64,
        self.enc.bitrate,
        maybe_ac_qi_max,
        self.enc.max_key_frame_interval as i32
      ),
      maybe_prev_log_base_q: None,
491 492 493
      first_pass_data: FirstPassData {
        frames: Vec::new(),
      },
Josh Holmer's avatar
Josh Holmer committed
494
    }
Luca Barbato's avatar
Luca Barbato committed
495 496 497
  }
}

498
pub struct Context<T: Pixel> {
Luca Barbato's avatar
Luca Barbato committed
499
  //    timebase: Rational,
fbossen's avatar
fbossen committed
500
  frame_count: u64,
501
  limit: u64,
502
  pub(crate) idx: u64,
Josh Holmer's avatar
Josh Holmer committed
503 504
  frames_processed: u64,
  /// Maps frame *number* to frames
505
  frame_q: BTreeMap<u64, Option<Arc<Frame<T>>>>, //    packet_q: VecDeque<Packet>
Josh Holmer's avatar
Josh Holmer committed
506
  /// Maps frame *idx* to frame data
507
  frame_data: BTreeMap<u64, FrameInvariants<T>>,
Josh Holmer's avatar
Josh Holmer committed
508 509 510
  /// A list of keyframe *numbers* in this encode. Needed so that we don't
  /// need to keep all of the frame_data in memory for the whole life of the encode.
  keyframes: BTreeSet<u64>,
511
  /// A storage space for reordered frames.
Josh Holmer's avatar
Josh Holmer committed
512 513 514
  packet_data: Vec<u8>,
  segment_start_idx: u64,
  segment_start_frame: u64,
515
  keyframe_detector: SceneChangeDetector<T>,
516
  pub config: Config,
517
  rc_state: RCState,
518
  maybe_prev_log_base_q: Option<i64>,
519
  pub first_pass_data: FirstPassData,
Luca Barbato's avatar
Luca Barbato committed
520 521 522 523
}

#[derive(Clone, Copy, Debug)]
pub enum EncoderStatus {
524
  /// The encoder needs more data to produce an output Packet--used with frame reordering
Luca Barbato's avatar
Luca Barbato committed
525
  NeedMoreData,
526 527
  /// The encoder needs more Frames to analyze lookahead
  NeedMoreFrames,
Luca Barbato's avatar
Luca Barbato committed
528 529 530
  /// There are enough Frames queue
  EnoughData,
  ///
Luca Barbato's avatar
Luca Barbato committed
531 532 533
  Failure,
  InvalidKey,
  ParseError
Luca Barbato's avatar
Luca Barbato committed
534 535
}

536
pub struct Packet<T: Pixel> {
Luca Barbato's avatar
Luca Barbato committed
537
  pub data: Vec<u8>,
538
  pub rec: Option<Frame<T>>,
fbossen's avatar
fbossen committed
539
  pub number: u64,
540 541 542
  pub frame_type: FrameType,
  /// PSNR for Y, U, and V planes
  pub psnr: Option<(f64, f64, f64)>,
543 544
}

545
impl<T: Pixel> fmt::Display for Packet<T> {
546
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Luca Barbato's avatar
Luca Barbato committed
547 548 549 550 551 552 553
    write!(
      f,
      "Frame {} - {} - {} bytes",
      self.number,
      self.frame_type,
      self.data.len()
    )
554
  }
Luca Barbato's avatar
Luca Barbato committed
555 556
}

557 558
impl<T: Pixel> Context<T> {
  pub fn new_frame(&self) -> Arc<Frame<T>> {
Josh Holmer's avatar
Josh Holmer committed
559
    Arc::new(Frame::new(
560 561
      self.config.enc.width,
      self.config.enc.height,
562
      self.config.enc.chroma_sampling
Josh Holmer's avatar
Josh Holmer committed
563
    ))
Luca Barbato's avatar
Luca Barbato committed
564 565 566 567
  }

  pub fn send_frame<F>(&mut self, frame: F) -> Result<(), EncoderStatus>
  where
568 569
    F: Into<Option<Arc<Frame<T>>>>,
    T: Pixel,
Luca Barbato's avatar
Luca Barbato committed
570
  {
Josh Holmer's avatar
Josh Holmer committed
571 572
    let idx = self.frame_count;
    self.frame_q.insert(idx, frame.into());
573
    self.frame_count += 1;
Luca Barbato's avatar
Luca Barbato committed
574 575 576
    Ok(())
  }

577
  pub fn get_frame(&self, frame_number: u64) -> Arc<Frame<T>> {
578 579 580 581
    // Clones only the arc, so low cost overhead
    self.frame_q.get(&frame_number).as_ref().unwrap().as_ref().unwrap().clone()
  }

582 583 584 585
  pub fn get_frame_count(&self) -> u64 {
    self.frame_count
  }

586 587
  pub fn set_limit(&mut self, limit: u64) {
    self.limit = limit;
588 589
  }

Josh Holmer's avatar
Josh Holmer committed
590 591 592 593
  pub fn needs_more_lookahead(&self) -> bool {
    self.needs_more_frames(self.frame_count) && self.frames_processed + LOOKAHEAD_FRAMES > self.frame_q.keys().last().cloned().unwrap_or(0)
  }

594
  pub fn needs_more_frames(&self, frame_count: u64) -> bool {
595
    self.limit == 0 || frame_count < self.limit
596 597
  }

598 599 600
  pub fn container_sequence_header(&mut self) -> Vec<u8> {
    fn sequence_header_inner(seq: &Sequence) -> io::Result<Vec<u8>> {
      let mut buf = Vec::new();
601

602
      {
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        let mut bw = BitWriter::endian(&mut buf, BigEndian);
        bw.write_bit(true)?; // marker
        bw.write(7, 1)?; // version
        bw.write(3, seq.profile)?;
        bw.write(5, 32)?; // level
        bw.write_bit(false)?; // tier
        bw.write_bit(seq.bit_depth > 8)?; // high_bitdepth
        bw.write_bit(seq.bit_depth == 12)?; // twelve_bit
        bw.write_bit(seq.bit_depth == 1)?; // monochrome
        bw.write_bit(seq.bit_depth == 12)?; // twelve_bit
        bw.write_bit(seq.chroma_sampling != ChromaSampling::Cs444)?; // chroma_subsampling_x
        bw.write_bit(seq.chroma_sampling == ChromaSampling::Cs420)?; // chroma_subsampling_y
        bw.write(2, 0)?; // sample_position
        bw.write(3, 0)?; // reserved
        bw.write_bit(false)?; // initial_presentation_delay_present

        bw.write(4, 0)?; // reserved
620
      }
621

622 623 624
      Ok(buf)
    }

Josh Holmer's avatar
Josh Holmer committed
625
    sequence_header_inner(&self.frame_data[&0].sequence).unwrap()
626 627
  }

Josh Holmer's avatar
Josh Holmer committed
628
  fn next_keyframe(&self) -> u64 {
Josh Holmer's avatar
Josh Holmer committed
629 630 631 632
    let next_detected = self.frame_data.values()
      .find(|fi| fi.frame_type == FrameType::KEY && fi.number > self.segment_start_frame)
      .map(|fi| fi.number);
    let next_limit = self.segment_start_frame + self.config.enc.max_key_frame_interval;
Josh Holmer's avatar
Josh Holmer committed
633 634 635 636 637
    if next_detected.is_none() {
      return next_limit;
    }
    cmp::min(next_detected.unwrap(), next_limit)
  }
fbossen's avatar
fbossen committed
638

639
  fn set_frame_properties(&mut self, idx: u64) -> bool {
640
    let (fi, end_of_subgop) = self.build_frame_properties(idx);
641 642 643
    self.frame_data.insert(idx, fi);

    end_of_subgop
Josh Holmer's avatar
Josh Holmer committed
644 645
  }

646
  fn build_frame_properties(&mut self, idx: u64) -> (FrameInvariants<T>, bool) {
Josh Holmer's avatar
Josh Holmer committed
647
    if idx == 0 {
648
      let seq = Sequence::new(&self.config.enc);
649

Josh Holmer's avatar
Josh Holmer committed
650
      // The first frame will always be a key frame
Josh Holmer's avatar
Josh Holmer committed
651 652
      let fi = FrameInvariants::new_key_frame(
        &FrameInvariants::new(
653
          self.config.enc.clone(),
654
          seq
Josh Holmer's avatar
Josh Holmer committed
655 656 657
        ),
        0
      );
658
      return (fi, true);
Josh Holmer's avatar
Josh Holmer committed
659 660
    }

Josh Holmer's avatar
Josh Holmer committed
661 662
    let mut fi = self.frame_data[&(idx - 1)].clone();

663 664 665 666 667
    // FIXME: inter unsupported with 4:2:2 and 4:4:4 chroma sampling
    let chroma_sampling = self.config.enc.chroma_sampling;
    let keyframe_only = chroma_sampling == ChromaSampling::Cs444 ||
      chroma_sampling == ChromaSampling::Cs422;

Josh Holmer's avatar
Josh Holmer committed
668 669 670 671 672 673
    // Initially set up the frame as an inter frame.
    // We need to determine what the frame number is before we can
    // look up the frame type. If reordering is enabled, the idx
    // may not match the frame number.
    let idx_in_segment = idx - self.segment_start_idx;
    if idx_in_segment > 0 {
674
      let next_keyframe = if keyframe_only { self.segment_start_frame + 1 } else { self.next_keyframe() };
675
      let (fi_temp, end_of_subgop) = FrameInvariants::new_inter_frame(
Josh Holmer's avatar
Josh Holmer committed
676
        &fi,
677 678 679 680
        self.segment_start_frame,
        idx_in_segment,
        next_keyframe
      );
Josh Holmer's avatar
Josh Holmer committed
681
      fi = fi_temp;
682
      if !end_of_subgop {
Josh Holmer's avatar
Josh Holmer committed
683 684 685
        if !fi.inter_cfg.unwrap().reorder
          || ((idx_in_segment - 1) % fi.inter_cfg.unwrap().group_len == 0
          && fi.number == (next_keyframe - 1))
686
        {
Josh Holmer's avatar
Josh Holmer committed
687
          self.segment_start_idx = idx;
Josh Holmer's avatar
Josh Holmer committed
688
          self.segment_start_frame = next_keyframe;
Josh Holmer's avatar
Josh Holmer committed
689
          fi.number = next_keyframe;
Josh Holmer's avatar
Josh Holmer committed
690
        } else {
691
          return (fi, false);
Josh Holmer's avatar
Josh Holmer committed
692 693
        }
      }
fbossen's avatar
fbossen committed
694
    }
Luca Barbato's avatar
Luca Barbato committed
695

696 697
    match self.frame_q.get(&fi.number) {
      Some(Some(_)) => {},
Josh Holmer's avatar
Josh Holmer committed
698
      _ => { return (fi, false); }
699 700
    }

Josh Holmer's avatar
Josh Holmer committed
701
    // Now that we know the frame number, look up the correct frame type
Josh Holmer's avatar
Josh Holmer committed
702 703 704 705 706 707 708
    let frame_type = self.determine_frame_type(fi.number);
    if frame_type == FrameType::KEY {
      self.segment_start_idx = idx;
      self.segment_start_frame = fi.number;
      self.keyframes.insert(fi.number);
    }
    fi.frame_type = frame_type;
Josh Holmer's avatar
Josh Holmer committed
709

Josh Holmer's avatar
Josh Holmer committed
710 711 712 713 714
    let idx_in_segment = idx - self.segment_start_idx;
    if idx_in_segment == 0 {
      fi = FrameInvariants::new_key_frame(&fi, self.segment_start_frame);
    } else {
      let next_keyframe = self.next_keyframe();
715
      let (fi_temp, end_of_subgop) = FrameInvariants::new_inter_frame(
Josh Holmer's avatar
Josh Holmer committed
716 717 718 719 720 721
        &fi,
        self.segment_start_frame,
        idx_in_segment,
        next_keyframe
      );
      fi = fi_temp;
722 723
      if !end_of_subgop {
        return (fi, false);
Josh Holmer's avatar
Josh Holmer committed
724 725
      }
    }
726
    (fi, true)
fbossen's avatar
fbossen committed
727
  }
Luca Barbato's avatar
Luca Barbato committed
728

729
  pub fn receive_packet(&mut self) -> Result<Packet<T>, EncoderStatus> {
730
    if self.needs_more_lookahead() {
731
      return Err(EncoderStatus::NeedMoreFrames);
732 733
    }

734 735 736 737 738 739
    let idx = {
      let mut idx = self.idx;
      while !self.set_frame_properties(idx) {
        self.idx += 1;
        idx = self.idx;
      }
Luca Barbato's avatar
Luca Barbato committed
740

741
      if !self.needs_more_frames(self.frame_data[&idx].number) {
742 743 744 745 746
        self.idx += 1;
        return Err(EncoderStatus::EnoughData);
      }
      idx
    };
747

748
    let ret = {
Luca Barbato's avatar
Luca Barbato committed
749 750 751
      let fi = self.frame_data.get_mut(&idx).unwrap();
      if fi.show_existing_frame {
        self.idx += 1;
Luca Barbato's avatar
Luca Barbato committed
752

Luca Barbato's avatar
Luca Barbato committed
753
        let mut fs = FrameState::new(fi);
fbossen's avatar
fbossen committed
754

755 756
        // TODO: Record the bits spent here against the original frame for rate
        //  control purposes, or add a new frame subtype?
757 758
        let sef_data = encode_frame(fi, &mut fs);
        self.packet_data.extend(sef_data);
Luca Barbato's avatar
Luca Barbato committed
759

Luca Barbato's avatar
Luca Barbato committed
760
        let rec = if fi.show_frame { Some(fs.rec) } else { None };
761
        let fi = fi.clone();
762
        self.finalize_packet(rec, &fi)
Luca Barbato's avatar
Luca Barbato committed
763 764 765
      } else {
        if let Some(f) = self.frame_q.get(&fi.number) {
          self.idx += 1;
fbossen's avatar
fbossen committed
766

767
          if let Some(frame) = f.clone() {
768
            let fti = fi.get_frame_subtype();
769 770 771
            let qps =
              self.rc_state.select_qi(self, fti, self.maybe_prev_log_base_q);
            let fi = self.frame_data.get_mut(&idx).unwrap();
772
            fi.set_quantizers(&qps);
Luca Barbato's avatar
Luca Barbato committed
773
            let mut fs = FrameState::new_with_frame(fi, frame.clone());
fbossen's avatar
fbossen committed
774

775
            // TODO: Trial encoding for first frame of each type.
Luca Barbato's avatar
Luca Barbato committed
776
            let data = encode_frame(fi, &mut fs);
777 778 779 780 781 782 783 784
            self.maybe_prev_log_base_q = Some(qps.log_base_q);
            // TODO: Add support for dropping frames.
            self.rc_state.update_state(
              (data.len() * 8) as i64,
              fti,
              qps.log_target_q,
              false
            );
Luca Barbato's avatar
Luca Barbato committed
785
            self.packet_data.extend(data);
fbossen's avatar
fbossen committed
786

Luca Barbato's avatar
Luca Barbato committed
787
            fs.rec.pad(fi.width, fi.height);
fbossen's avatar
fbossen committed
788

Luca Barbato's avatar
Luca Barbato committed
789 790
            // TODO avoid the clone by having rec Arc.
            let rec = if fi.show_frame { Some(fs.rec.clone()) } else { None };
fbossen's avatar
fbossen committed
791

Luca Barbato's avatar
Luca Barbato committed
792
            update_rec_buffer(fi, fs);
fbossen's avatar
fbossen committed
793

Luca Barbato's avatar
Luca Barbato committed
794
            if fi.show_frame {
795
              let fi = fi.clone();
796
              self.finalize_packet(rec, &fi)
Luca Barbato's avatar
Luca Barbato committed
797 798 799
            } else {
              Err(EncoderStatus::NeedMoreData)
            }
800 801 802
          } else {
            Err(EncoderStatus::NeedMoreData)
          }
fbossen's avatar
fbossen committed
803 804 805 806
        } else {
          Err(EncoderStatus::NeedMoreData)
        }
      }
807 808 809
    };

    if let Ok(ref pkt) = ret {
Luca Barbato's avatar
Luca Barbato committed
810
      self.garbage_collect(pkt.number);
811 812 813
    }

    ret
Luca Barbato's avatar
Luca Barbato committed
814 815
  }

816
  fn finalize_packet(&mut self, rec: Option<Frame<T>>, fi: &FrameInvariants<T>) -> Result<Packet<T>, EncoderStatus> {
817 818 819 820 821 822 823 824 825
    let data = self.packet_data.clone();
    self.packet_data.clear();
    if write_temporal_delimiter(&mut self.packet_data).is_err() {
      return Err(EncoderStatus::Failure);
    }

    let mut psnr = None;
    if self.config.enc.show_psnr {
      if let Some(ref rec) = rec {
826
        let original_frame = self.get_frame(fi.number);
827 828 829 830 831 832 833 834
        psnr = Some(calculate_frame_psnr(
          &*original_frame,
          rec,
          fi.sequence.bit_depth
        ));
      }
    }

835 836 837 838
    if self.config.enc.pass == Some(1) {
      self.first_pass_data.frames.push(FirstPassFrame::from(fi));
    }

839 840 841 842 843 844 845 846 847 848
    self.frames_processed += 1;
    Ok(Packet {
      data,
      rec,
      number: fi.number,
      frame_type: fi.frame_type,
      psnr
    })
  }

849
  fn garbage_collect(&mut self, cur_frame: u64) {
Josh Holmer's avatar
Josh Holmer committed
850 851 852 853 854 855 856 857 858 859 860 861 862 863
    if cur_frame == 0 {
      return;
    }
    for i in 0..cur_frame {
      self.frame_q.remove(&i);
    }
    if self.idx < 2 {
      return;
    }
    for i in 0..(self.idx - 1) {
      self.frame_data.remove(&i);
    }
  }

Luca Barbato's avatar
Luca Barbato committed
864
  pub fn flush(&mut self) {
fbossen's avatar
fbossen committed
865
    self.frame_q.insert(self.frame_count, None);
866
    self.frame_count += 1;
Luca Barbato's avatar
Luca Barbato committed
867
  }
Josh Holmer's avatar
Josh Holmer committed
868

Josh Holmer's avatar
Josh Holmer committed
869 870
  fn determine_frame_type(&mut self, frame_number: u64) -> FrameType {
    if frame_number == 0 {
Josh Holmer's avatar
Josh Holmer committed
871 872
      return FrameType::KEY;
    }
873 874 875 876 877 878 879
    if self.config.enc.speed_settings.no_scene_detection {
      if frame_number % self.config.enc.max_key_frame_interval == 0 {
        return FrameType::KEY;
      } else {
        return FrameType::INTER;
      }
    }
Josh Holmer's avatar
Josh Holmer committed
880

Josh Holmer's avatar
Josh Holmer committed
881 882 883 884 885 886 887 888
    let prev_keyframe = self.keyframes.iter()
      .rfind(|&&keyframe| keyframe < frame_number)
      .cloned()
      .unwrap_or(0);
    let frame = match self.frame_q.get(&frame_number).cloned() {
      Some(frame) => frame,
      None => { return FrameType::KEY; }
    };
Josh Holmer's avatar
Josh Holmer committed
889
    if let Some(frame) = frame {
Josh Holmer's avatar
Josh Holmer committed
890 891 892
      let distance = frame_number - prev_keyframe;
      if distance < self.config.enc.min_key_frame_interval {
        if distance + 1 == self.config.enc.min_key_frame_interval {
Josh Holmer's avatar
Josh Holmer committed
893 894
          // Run the detector for the current frame, so that it will contain this frame's information
          // to compare against the next frame. We can ignore the results for this frame.
Josh Holmer's avatar
Josh Holmer committed
895
          self.keyframe_detector.detect_scene_change(frame, frame_number as usize);
Josh Holmer's avatar
Josh Holmer committed
896 897 898
        }
        return FrameType::INTER;
      }
Josh Holmer's avatar
Josh Holmer committed
899
      if distance >= self.config.enc.max_key_frame_interval {
Josh Holmer's avatar
Josh Holmer committed
900 901
        return FrameType::KEY;
      }
Josh Holmer's avatar
Josh Holmer committed
902
      if self.keyframe_detector.detect_scene_change(frame, frame_number as usize) {
Josh Holmer's avatar
Josh Holmer committed
903 904 905 906 907
        return FrameType::KEY;
      }
    }
    FrameType::INTER
  }
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

  // Count the number of frames of each subtype in the next
  //  reservoir_frame_delay frames.
  // Returns the number of frames until the last keyframe in the next
  //  reservoir_frame_delay frames, or the end of the interval, whichever
  //  comes first.
  pub(crate) fn guess_frame_subtypes(
    &self, nframes: &mut [i32; FRAME_NSUBTYPES], reservoir_frame_delay: i32
  ) -> i32 {
    // TODO: Ideally this logic should be centralized, but the actual code used
    //  to determine a frame's subtype is spread over many places and
    //  intertwined with mutable state changes that occur when the frame is
    //  actually encoded.
    // So for now we just duplicate it here in stateless fashion.
    for fti in 0..FRAME_NSUBTYPES {
      nframes[fti] = 0;
    }
    let mut prev_keyframe = self.segment_start_idx;
    let mut acc: [i32; FRAME_NSUBTYPES] = [0; FRAME_NSUBTYPES];
    // Updates the frame counts with the accumulated values when we hit a
    //  keyframe.
    fn collect_counts(
      nframes: &mut [i32; FRAME_NSUBTYPES], acc: &mut [i32; FRAME_NSUBTYPES]
    ) {
      for fti in 0..FRAME_NSUBTYPES {
        nframes[fti] += acc[fti];
        acc[fti] = 0;
      }
      acc[FRAME_SUBTYPE_I] += 1;
    }
    for idx in self.idx..(self.idx + reservoir_frame_delay as u64) {
      if let Some(fd) = self.frame_data.get(&idx) {
        if fd.frame_type == FrameType::KEY {
          collect_counts(nframes, &mut acc);
          prev_keyframe = idx;
          continue;
        }
      } else if idx == 0
        || idx - prev_keyframe >= self.config.enc.max_key_frame_interval
      {
        collect_counts(nframes, &mut acc);
        prev_keyframe = idx;
        continue;
      }
      // TODO: Implement golden P-frames.
      let mut fti = FRAME_SUBTYPE_P;
      if !self.config.enc.low_latency {
        let pyramid_depth = 2;
        let group_src_len = 1 << pyramid_depth;
        let group_len = group_src_len + pyramid_depth;
        let idx_in_group = (idx - prev_keyframe - 1) % group_len;
        let lvl = if idx_in_group < pyramid_depth {
          idx_in_group
        } else {
          pos_to_lvl(idx_in_group - pyramid_depth + 1, pyramid_depth)
        };
        fti += lvl as usize;
      }
      acc[fti] += 1;
    }
    if prev_keyframe <= self.idx {
      // If there were no keyframes at all, or only the first frame was a
      //  keyframe, the accumulators never flushed and still contain counts for
      //  the entire buffer.
      // In both cases, we return these counts.
      collect_counts(nframes, &mut acc);
      reservoir_frame_delay
    } else {
      // Otherwise, we discard what remains in the accumulators as they contain
      //  the counts from and past the last keyframe.
      (prev_keyframe - self.idx) as i32
    }
  }
Luca Barbato's avatar
Luca Barbato committed
981
}
982 983 984 985 986 987 988 989 990 991 992 993

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FirstPassData {
  frames: Vec<FirstPassFrame>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FirstPassFrame {
  number: u64,
  frame_type: FrameType,
}

994 995
impl<T: Pixel> From<&FrameInvariants<T>> for FirstPassFrame {
  fn from(fi: &FrameInvariants<T>) -> FirstPassFrame {
996 997 998 999 1000
    FirstPassFrame {
      number: fi.number,
      frame_type: fi.frame_type,
    }
  }
1001
}