api.rs 19.7 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::*;
Luca Barbato's avatar
Luca Barbato committed
11
use encoder::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
12
use metrics::calculate_frame_psnr;
13
use partition::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
14 15
use scenechange::SceneChangeDetector;
use self::EncoderStatus::*;
Luca Barbato's avatar
Luca Barbato committed
16

Raphaël Zumer's avatar
Raphaël Zumer committed
17
use std::{cmp, fmt, io};
fbossen's avatar
fbossen committed
18
use std::collections::BTreeMap;
Luca Barbato's avatar
Luca Barbato committed
19 20 21 22
use std::sync::Arc;

// TODO: use the num crate?
#[derive(Clone, Copy, Debug)]
23
#[repr(C)]
Luca Barbato's avatar
Luca Barbato committed
24 25 26
pub struct Rational {
  pub num: u64,
  pub den: u64
Luca Barbato's avatar
Luca Barbato committed
27 28
}

Luca Barbato's avatar
Luca Barbato committed
29 30 31
impl Rational {
  pub fn new(num: u64, den: u64) -> Self {
    Rational { num, den }
Luca Barbato's avatar
Luca Barbato committed
32 33 34
  }
}

35 36
#[derive(Copy, Clone, Debug)]
pub struct EncoderConfig {
Josh Holmer's avatar
Josh Holmer committed
37 38 39 40
  /// The *minimum* interval between two keyframes
  pub min_key_frame_interval: u64,
  /// The *maximum* interval between two keyframes
  pub max_key_frame_interval: u64,
41
  pub low_latency: bool,
42
  pub quantizer: usize,
43 44
  pub tune: Tune,
  pub speed_settings: SpeedSettings,
45
  pub show_psnr: bool,
46 47 48 49
}

impl Default for EncoderConfig {
  fn default() -> Self {
50 51
    const DEFAULT_SPEED: usize = 3;
    Self::with_speed_preset(DEFAULT_SPEED)
52 53 54
  }
}

55 56 57
impl EncoderConfig {
  pub fn with_speed_preset(speed: usize) -> Self {
    EncoderConfig {
Josh Holmer's avatar
Josh Holmer committed
58 59
      min_key_frame_interval: 12,
      max_key_frame_interval: 240,
60 61 62
      low_latency: true,
      quantizer: 100,
      tune: Tune::Psnr,
63 64
      speed_settings: SpeedSettings::from_preset(speed),
      show_psnr: false,
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    }
  }
}

#[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,
  pub encode_bottomup: bool,
  pub rdo_tx_decision: bool,
  pub prediction_modes: PredictionModesSetting,
  pub include_near_mvs: bool,
}

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),
      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),
    }
  }

  fn min_block_size_preset(speed: usize) -> BlockSize {
    if speed <= 1 {
      BlockSize::BLOCK_4X4
    } else if speed <= 2 {
      BlockSize::BLOCK_8X8
    } else if speed <= 3 {
      BlockSize::BLOCK_16X16
    } else if speed <= 4 {
      BlockSize::BLOCK_32X32
    } else {
      BlockSize::BLOCK_64X64
    }
  }

  fn multiref_preset(speed: usize) -> bool {
    speed <= 2
  }

  fn fast_deblock_preset(speed: usize) -> bool {
    speed >= 4
  }

  fn reduced_tx_set_preset(speed: usize) -> bool {
    speed >= 2
  }

  fn tx_domain_distortion_preset(speed: usize) -> bool {
    speed >= 1
  }

  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 {
    if speed <= 1 {
      PredictionModesSetting::ComplexAll
    } else if speed <= 3 {
      PredictionModesSetting::ComplexKeyframes
    } else {
      PredictionModesSetting::Simple
    }
  }

  fn include_near_mvs_preset(speed: usize) -> bool {
    speed <= 2
  }
}

#[derive(Clone, Copy, Debug, PartialOrd, PartialEq)]
pub enum PredictionModesSetting {
  Simple,
  ComplexKeyframes,
  ComplexAll,
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 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
#[derive(Debug,Clone,Copy,PartialEq)]
pub enum MatrixCoefficients {
    Identity = 0,
    BT709,
    Unspecified,
    Reserved,
    BT470M,
    BT470BG,
    ST170M,
    ST240M,
    YCgCo,
    BT2020NonConstantLuminance,
    BT2020ConstantLuminance,
    ST2085,
    ChromaticityDerivedNonConstantLuminance,
    ChromaticityDerivedConstantLuminance,
    ICtCp,
}

impl fmt::Display for MatrixCoefficients {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            MatrixCoefficients::Identity => write!(f, "Identity"),
            MatrixCoefficients::BT709 => write!(f, "ITU BT.709"),
            MatrixCoefficients::Unspecified => write!(f, "Unspecified"),
            MatrixCoefficients::Reserved => write!(f, "Reserved"),
            MatrixCoefficients::BT470M => write!(f, "ITU BT.470M"),
            MatrixCoefficients::BT470BG => write!(f, "ITU BT.470BG"),
            MatrixCoefficients::ST170M => write!(f, "SMPTE ST-170M"),
            MatrixCoefficients::ST240M => write!(f, "SMPTE ST-240M"),
            MatrixCoefficients::YCgCo => write!(f, "YCgCo"),
            MatrixCoefficients::BT2020NonConstantLuminance => write!(f, "ITU BT.2020 (Non Constant Luminance)"),
            MatrixCoefficients::BT2020ConstantLuminance => write!(f, "ITU BT.2020 (Constant Luminance)"),
            MatrixCoefficients::ST2085 => write!(f, "SMPTE ST-2085"),
            MatrixCoefficients::ChromaticityDerivedNonConstantLuminance => write!(f, "Chromaticity Derived (Non Constant Luminance)"),
            MatrixCoefficients::ChromaticityDerivedConstantLuminance => write!(f, "Chromaticity Derived (Constant Luminance)"),
            MatrixCoefficients::ICtCp => write!(f, "ICtCp"),
        }
    }
}

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

#[derive(Debug,Clone,Copy,PartialEq)]
pub enum ColorPrimaries {
    Reserved0 = 0,
    BT709,
    Unspecified,
    Reserved,
    BT470M,
    BT470BG,
    ST170M,
    ST240M,
    Film,
    BT2020,
    ST428,
    P3DCI,
    P3Display,
    Tech3213 = 22,
}

impl fmt::Display for ColorPrimaries {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            ColorPrimaries::Reserved0 => write!(f, "Identity"),
            ColorPrimaries::BT709 => write!(f, "ITU BT.709"),
            ColorPrimaries::Unspecified => write!(f, "Unspecified"),
            ColorPrimaries::Reserved => write!(f, "Reserved"),
            ColorPrimaries::BT470M => write!(f, "ITU BT.470M"),
            ColorPrimaries::BT470BG => write!(f, "ITU BT.470BG"),
            ColorPrimaries::ST170M => write!(f, "SMPTE ST-170M"),
            ColorPrimaries::ST240M => write!(f, "SMPTE ST-240M"),
            ColorPrimaries::Film => write!(f, "Film"),
            ColorPrimaries::BT2020 => write!(f, "ITU BT.2020"),
            ColorPrimaries::ST428 => write!(f, "SMPTE ST-428"),
            ColorPrimaries::P3DCI => write!(f, "DCI P3"),
            ColorPrimaries::P3Display => write!(f, "Display P3"),
            ColorPrimaries::Tech3213 => write!(f, "EBU Tech3213"),
        }
    }
}

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

#[derive(Debug,Clone,Copy,PartialEq)]
pub enum TransferCharacteristics {
    Reserved0 = 0,
    BT1886,
    Unspecified,
    Reserved,
    BT470M,
    BT470BG,
    ST170M,
    ST240M,
    Linear,
    Logarithmic100,
    Logarithmic316,
    XVYCC,
    BT1361E,
    SRGB,
    BT2020Ten,
    BT2020Twelve,
    PerceptualQuantizer,
    ST428,
    HybridLogGamma,
}

impl fmt::Display for TransferCharacteristics {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            TransferCharacteristics::Reserved0 => write!(f, "Identity"),
            TransferCharacteristics::BT1886 => write!(f, "ITU BT.1886"),
            TransferCharacteristics::Unspecified => write!(f, "Unspecified"),
            TransferCharacteristics::Reserved => write!(f, "Reserved"),
            TransferCharacteristics::BT470M => write!(f, "ITU BT.470M"),
            TransferCharacteristics::BT470BG => write!(f, "ITU BT.470BG"),
            TransferCharacteristics::ST170M => write!(f, "SMPTE ST-170M"),
            TransferCharacteristics::ST240M => write!(f, "SMPTE ST-240M"),
            TransferCharacteristics::Linear => write!(f, "Linear"),
            TransferCharacteristics::Logarithmic100 => write!(f, "Logarithmic 100:1 range"),
            TransferCharacteristics::Logarithmic316 => write!(f, "Logarithmic 316:1 range"),
            TransferCharacteristics::XVYCC => write!(f, "XVYCC"),
            TransferCharacteristics::BT1361E => write!(f, "ITU BT.1361 Extended Color Gamut"),
            TransferCharacteristics::SRGB => write!(f, "sRGB"),
            TransferCharacteristics::BT2020Ten => write!(f, "ITU BT.2020 for 10bit systems"),
            TransferCharacteristics::BT2020Twelve => write!(f, "ITU BT.2020 for 12bit systems"),
            TransferCharacteristics::PerceptualQuantizer => write!(f, "Perceptual Quantizer"),
            TransferCharacteristics::ST428 => write!(f, "SMPTE ST-428"),
            TransferCharacteristics::HybridLogGamma => write!(f, "Hybrid Log-Gamma"),
        }
    }
}

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

304
/// Frame-specific information
305
#[derive(Clone, Copy, Debug, Default)]
306
pub struct FrameInfo {
Luca Barbato's avatar
Luca Barbato committed
307 308 309
  pub width: usize,
  pub height: usize,
  pub bit_depth: usize,
310
  pub chroma_sampling: ChromaSampling,
311 312 313 314
  pub chroma_sample_position: ChromaSamplePosition,
  pub primaries: ColorPrimaries,
  pub transfer: TransferCharacteristics,
  pub matrix: MatrixCoefficients
315 316 317 318 319 320
}

/// Contain all the encoder configuration
#[derive(Clone, Copy, Debug)]
pub struct Config {
  pub frame_info: FrameInfo,
Luca Barbato's avatar
Luca Barbato committed
321
  pub timebase: Rational,
Luca Barbato's avatar
Luca Barbato committed
322 323 324 325
  pub enc: EncoderConfig
}

impl Config {
Luca Barbato's avatar
Luca Barbato committed
326 327
  pub fn parse(&mut self, key: &str, value: &str) -> Result<(), EncoderStatus> {
    match key {
328
      "low_latency" => self.enc.low_latency = value.parse().map_err(|_e| ParseError)?,
Josh Holmer's avatar
Josh Holmer committed
329 330
      "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)?,
331
      "quantizer" => self.enc.quantizer = value.parse().map_err(|_e| ParseError)?,
332
      "speed" => self.enc.speed_settings = SpeedSettings::from_preset(value.parse().map_err(|_e| ParseError)?),
333 334
      "tune" => self.enc.tune = value.parse().map_err(|_e| ParseError)?,
      _ => return Err(InvalidKey)
Luca Barbato's avatar
Luca Barbato committed
335 336 337 338 339
    }

    Ok(())
  }

Luca Barbato's avatar
Luca Barbato committed
340
  pub fn new_context(&self) -> Context {
341 342 343
    let fi = FrameInvariants::new(
      self.frame_info.width,
      self.frame_info.height,
344
      self.enc
Luca Barbato's avatar
Luca Barbato committed
345
    );
346
    let seq = Sequence::new(&self.frame_info);
Luca Barbato's avatar
Luca Barbato committed
347

348
    #[cfg(feature = "aom")]
Luca Barbato's avatar
Luca Barbato committed
349
    unsafe {
Luca Barbato's avatar
Luca Barbato committed
350 351
      av1_rtcd();
      aom_dsp_rtcd();
Luca Barbato's avatar
Luca Barbato committed
352 353
    }

Josh Holmer's avatar
Josh Holmer committed
354 355 356 357 358 359 360 361 362 363 364 365 366
    Context {
      fi,
      seq,
      frame_count: 0,
      frames_to_be_coded: 0,
      idx: 0,
      frame_q: BTreeMap::new(),
      packet_data: Vec::new(),
      segment_start_idx: 0,
      segment_start_frame: 0,
      frame_types: BTreeMap::new(),
      keyframe_detector: SceneChangeDetector::new(&self.frame_info),
    }
Luca Barbato's avatar
Luca Barbato committed
367 368 369 370 371 372
  }
}

pub struct Context {
  fi: FrameInvariants,
  seq: Sequence,
Luca Barbato's avatar
Luca Barbato committed
373
  //    timebase: Rational,
fbossen's avatar
fbossen committed
374
  frame_count: u64,
375
  frames_to_be_coded: u64,
fbossen's avatar
fbossen committed
376
  idx: u64,
377
  frame_q: BTreeMap<u64, Option<Arc<Frame>>>, //    packet_q: VecDeque<Packet>
Josh Holmer's avatar
Josh Holmer committed
378 379 380 381 382
  packet_data: Vec<u8>,
  segment_start_idx: u64,
  segment_start_frame: u64,
  frame_types: BTreeMap<u64, FrameType>,
  keyframe_detector: SceneChangeDetector,
Luca Barbato's avatar
Luca Barbato committed
383 384 385 386 387 388 389 390 391
}

#[derive(Clone, Copy, Debug)]
pub enum EncoderStatus {
  /// The encoder needs more Frames to produce an output Packet
  NeedMoreData,
  /// There are enough Frames queue
  EnoughData,
  ///
Luca Barbato's avatar
Luca Barbato committed
392 393 394
  Failure,
  InvalidKey,
  ParseError
Luca Barbato's avatar
Luca Barbato committed
395 396 397 398
}

pub struct Packet {
  pub data: Vec<u8>,
fbossen's avatar
fbossen committed
399 400
  pub rec: Option<Frame>,
  pub number: u64,
401 402 403
  pub frame_type: FrameType,
  /// PSNR for Y, U, and V planes
  pub psnr: Option<(f64, f64, f64)>,
404 405 406 407
}

impl fmt::Display for Packet {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Luca Barbato's avatar
Luca Barbato committed
408 409 410 411 412 413 414
    write!(
      f,
      "Frame {} - {} - {} bytes",
      self.number,
      self.frame_type,
      self.data.len()
    )
415
  }
Luca Barbato's avatar
Luca Barbato committed
416 417 418 419 420 421 422 423 424 425 426
}

impl Context {
  pub fn new_frame(&self) -> Arc<Frame> {
    Arc::new(Frame::new(self.fi.padded_w, self.fi.padded_h))
  }

  pub fn send_frame<F>(&mut self, frame: F) -> Result<(), EncoderStatus>
  where
    F: Into<Option<Arc<Frame>>>
  {
Josh Holmer's avatar
Josh Holmer committed
427 428 429
    let idx = self.frame_count;
    self.frame_q.insert(idx, frame.into());
    self.save_frame_type(idx);
fbossen's avatar
fbossen committed
430
    self.frame_count = self.frame_count + 1;
Luca Barbato's avatar
Luca Barbato committed
431 432 433
    Ok(())
  }

434 435 436 437 438 439 440 441 442 443 444 445
  pub fn get_frame_count(&self) -> u64 {
    self.frame_count
  }

  pub fn set_frames_to_be_coded(&mut self, frames_to_be_coded: u64) {
    self.frames_to_be_coded = frames_to_be_coded;
  }

  pub fn needs_more_frames(&self, frame_count: u64) -> bool {
    self.frames_to_be_coded == 0 || frame_count < self.frames_to_be_coded
  }

446 447 448
  pub fn container_sequence_header(&mut self) -> Vec<u8> {
    fn sequence_header_inner(seq: &Sequence) -> io::Result<Vec<u8>> {
      let mut buf = Vec::new();
449

450
      {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        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
468
      }
469

470 471 472 473 474 475
      Ok(buf)
    }

    sequence_header_inner(&self.seq).unwrap()
  }

Josh Holmer's avatar
Josh Holmer committed
476 477 478 479 480 481 482 483 484 485
  fn next_keyframe(&self) -> u64 {
    let next_detected = self.frame_types.iter()
      .find(|(&i, &ty)| ty == FrameType::KEY && i > self.segment_start_frame)
      .map(|(&i, _)| i);
    let next_limit = self.segment_start_frame + self.fi.config.max_key_frame_interval;
    if next_detected.is_none() {
      return next_limit;
    }
    cmp::min(next_detected.unwrap(), next_limit)
  }
fbossen's avatar
fbossen committed
486

Josh Holmer's avatar
Josh Holmer committed
487
  fn set_frame_properties(&mut self, idx: u64) -> Result<(), ()> {
Josh Holmer's avatar
Josh Holmer committed
488 489
    if idx == 0 {
      // The first frame will always be a key frame
Josh Holmer's avatar
Josh Holmer committed
490
      self.fi = FrameInvariants::new_key_frame(&self.fi,0);
Josh Holmer's avatar
Josh Holmer committed
491 492 493 494 495 496 497 498 499
      return Ok(());
    }

    // 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 {
Josh Holmer's avatar
Josh Holmer committed
500 501 502 503 504
      let next_keyframe = self.next_keyframe();
      let (fi, success) = FrameInvariants::new_inter_frame(&self.fi, self.segment_start_frame, idx_in_segment, next_keyframe);
      self.fi = fi;
      if !success {
        if !self.fi.inter_cfg.unwrap().reorder || ((idx_in_segment - 1) % self.fi.inter_cfg.unwrap().group_len == 0 && self.fi.number == (next_keyframe - 1)) {
Josh Holmer's avatar
Josh Holmer committed
505
          self.segment_start_idx = idx;
Josh Holmer's avatar
Josh Holmer committed
506 507
          self.segment_start_frame = next_keyframe;
          self.fi.number = next_keyframe;
Josh Holmer's avatar
Josh Holmer committed
508
        } else {
Josh Holmer's avatar
Josh Holmer committed
509
          return Err(());
Josh Holmer's avatar
Josh Holmer committed
510 511
        }
      }
fbossen's avatar
fbossen committed
512
    }
Luca Barbato's avatar
Luca Barbato committed
513

Josh Holmer's avatar
Josh Holmer committed
514 515 516 517 518 519 520 521 522 523 524
    // Now that we know the frame number, look up the correct frame type
    let frame_type = self.frame_types.get(&self.fi.number).cloned();
    if let Some(frame_type) = frame_type {
      if frame_type == FrameType::KEY {
        self.segment_start_idx = idx;
        self.segment_start_frame = self.fi.number;
      }
      self.fi.frame_type = frame_type;

      let idx_in_segment = idx - self.segment_start_idx;
      if idx_in_segment == 0 {
Josh Holmer's avatar
Josh Holmer committed
525
        self.fi = FrameInvariants::new_key_frame(&self.fi, self.segment_start_frame);
Josh Holmer's avatar
Josh Holmer committed
526
      } else {
Josh Holmer's avatar
Josh Holmer committed
527 528 529 530 531 532
        let next_keyframe = self.next_keyframe();
        let (fi, success) = FrameInvariants::new_inter_frame(&self.fi, self.segment_start_frame, idx_in_segment, next_keyframe);
        self.fi = fi;
        if !success {
          return Err(());
        }
Josh Holmer's avatar
Josh Holmer committed
533 534 535
      }
    }
    Ok(())
fbossen's avatar
fbossen committed
536
  }
Luca Barbato's avatar
Luca Barbato committed
537

fbossen's avatar
fbossen committed
538 539
  pub fn receive_packet(&mut self) -> Result<Packet, EncoderStatus> {
    let mut idx = self.idx;
Josh Holmer's avatar
Josh Holmer committed
540
    while self.set_frame_properties(idx).is_err() {
Josh Holmer's avatar
Josh Holmer committed
541
      self.idx += 1;
fbossen's avatar
fbossen committed
542 543
      idx = self.idx;
    }
Luca Barbato's avatar
Luca Barbato committed
544

545
    if !self.needs_more_frames(self.fi.number) {
Josh Holmer's avatar
Josh Holmer committed
546
      self.idx += 1;
547 548 549
      return Err(EncoderStatus::EnoughData)
    }

fbossen's avatar
fbossen committed
550
    if self.fi.show_existing_frame {
Josh Holmer's avatar
Josh Holmer committed
551
      self.idx += 1;
Luca Barbato's avatar
Luca Barbato committed
552

553
      let mut fs = FrameState::new(&self.fi);
fbossen's avatar
fbossen committed
554 555

      let data = encode_frame(&mut self.seq, &mut self.fi, &mut fs);
Luca Barbato's avatar
Luca Barbato committed
556

fbossen's avatar
fbossen committed
557 558
      // TODO avoid the clone by having rec Arc.
      let rec = if self.fi.show_frame { Some(fs.rec.clone()) } else { None };
559 560 561 562 563 564
      let mut psnr = None;
      if self.fi.config.show_psnr {
        if let Some(ref rec) = rec {
          psnr = Some(calculate_frame_psnr(&*fs.input, rec, self.seq.bit_depth));
        }
      }
Luca Barbato's avatar
Luca Barbato committed
565

566
      Ok(Packet { data, rec, number: self.fi.number, frame_type: self.fi.frame_type, psnr })
Luca Barbato's avatar
Luca Barbato committed
567
    } else {
fbossen's avatar
fbossen committed
568
      if let Some(f) = self.frame_q.remove(&self.fi.number) {
Josh Holmer's avatar
Josh Holmer committed
569
        self.idx += 1;
fbossen's avatar
fbossen committed
570 571

        if let Some(frame) = f {
572
          let mut fs = FrameState::new_with_frame(&self.fi, frame.clone());
fbossen's avatar
fbossen committed
573 574

          let data = encode_frame(&mut self.seq, &mut self.fi, &mut fs);
575
          self.packet_data.extend(data);
fbossen's avatar
fbossen committed
576

577
          fs.rec.pad(self.fi.width, self.fi.height);
fbossen's avatar
fbossen committed
578 579 580 581 582 583

          // TODO avoid the clone by having rec Arc.
          let rec = if self.fi.show_frame { Some(fs.rec.clone()) } else { None };

          update_rec_buffer(&mut self.fi, fs);

584 585 586
          if self.fi.show_frame {
            let data = self.packet_data.clone();
            self.packet_data = Vec::new();
587 588 589 590 591 592 593 594 595

            let mut psnr = None;
            if self.fi.config.show_psnr {
              if let Some(ref rec) = rec {
                psnr = Some(calculate_frame_psnr(&*frame, rec, self.seq.bit_depth));
              }
            }

            Ok(Packet { data, rec, number: self.fi.number, frame_type: self.fi.frame_type, psnr })
596 597 598
          } else {
            Err(EncoderStatus::NeedMoreData)
          }
fbossen's avatar
fbossen committed
599 600 601 602 603 604
        } else {
          Err(EncoderStatus::NeedMoreData)
        }
      } else {
        Err(EncoderStatus::NeedMoreData)
      }
Luca Barbato's avatar
Luca Barbato committed
605 606 607 608
    }
  }

  pub fn flush(&mut self) {
fbossen's avatar
fbossen committed
609 610
    self.frame_q.insert(self.frame_count, None);
    self.frame_count = self.frame_count + 1;
Luca Barbato's avatar
Luca Barbato committed
611
  }
Josh Holmer's avatar
Josh Holmer committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

  fn save_frame_type(&mut self, idx: u64) {
    let frame_type = self.determine_frame_type(idx);
    self.frame_types.insert(idx, frame_type);
  }

  fn determine_frame_type(&mut self, idx: u64) -> FrameType {
    if idx == 0 {
      return FrameType::KEY;
    }

    let prev_keyframe = *self.frame_types.iter().rfind(|(_, &ty)| ty == FrameType::KEY).unwrap().0;
    let frame = self.frame_q.get(&idx).cloned().unwrap();
    if let Some(frame) = frame {
      let distance = idx - prev_keyframe;
      if distance < self.fi.config.min_key_frame_interval {
        if distance + 1 == self.fi.config.min_key_frame_interval {
          // 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.
          self.keyframe_detector.detect_scene_change(frame, idx as usize);
        }
        return FrameType::INTER;
      }
      if distance >= self.fi.config.max_key_frame_interval {
        return FrameType::KEY;
      }
      if self.keyframe_detector.detect_scene_change(frame, idx as usize) {
        return FrameType::KEY;
      }
    }
    FrameType::INTER
  }
Luca Barbato's avatar
Luca Barbato committed
644
}
Luca Barbato's avatar
Luca Barbato committed
645 646 647 648 649 650

impl fmt::Display for Context {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "Frame {} - {}", self.fi.number, self.fi.frame_type)
  }
}