api.rs 33 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.

10
use arg_enum_proc_macro::ArgEnum;
Raphaël Zumer's avatar
Raphaël Zumer committed
11
use bitstream_io::*;
12 13 14
use crate::encoder::*;
use crate::metrics::calculate_frame_psnr;
use crate::partition::*;
15
use crate::rate::RCState;
16 17 18
use crate::rate::FRAME_NSUBTYPES;
use crate::rate::FRAME_SUBTYPE_I;
use crate::rate::FRAME_SUBTYPE_P;
19
use crate::scenechange::SceneChangeDetector;
20
use crate::util::Pixel;
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 52

/// Encoder Settings impacting the bitstream produced
53
#[derive(Clone, Debug)]
54
pub struct EncoderConfig {
55
  // output size
56 57
  pub width: usize,
  pub height: usize,
58 59

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

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

impl Default for EncoderConfig {
  fn default() -> Self {
90
    const DEFAULT_SPEED: usize = 5;
91
    Self::with_speed_preset(DEFAULT_SPEED)
92 93 94
  }
}

95 96 97
impl EncoderConfig {
  pub fn with_speed_preset(speed: usize) -> Self {
    EncoderConfig {
98 99
      width: 640,
      height: 480,
100

101 102 103
      bit_depth: 8,
      chroma_sampling: ChromaSampling::Cs420,
      chroma_sample_position: ChromaSamplePosition::Unknown,
104 105 106 107 108
      pixel_range: PixelRange::Unspecified,
      color_description: None,
      mastering_display: None,
      content_light: None,

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

Vibhoothi's avatar
Vibhoothi committed
127
/// Contains all the speed settings
128 129 130 131 132 133 134
#[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,
135
  pub tx_domain_rate: bool,
136 137 138 139
  pub encode_bottomup: bool,
  pub rdo_tx_decision: bool,
  pub prediction_modes: PredictionModesSetting,
  pub include_near_mvs: bool,
140
  pub no_scene_detection: bool,
141 142
  pub diamond_me: bool,
  pub cdef: bool
143 144
}

Vibhoothi's avatar
Vibhoothi committed
145
/// Default values for the speed settings.
146 147 148
impl Default for SpeedSettings {
  fn default() -> Self {
    SpeedSettings {
149
      min_block_size: BlockSize::BLOCK_16X16,
150 151 152 153
      multiref: false,
      fast_deblock: false,
      reduced_tx_set: false,
      tx_domain_distortion: false,
154
      tx_domain_rate: false,
155 156 157 158 159
      encode_bottomup: false,
      rdo_tx_decision: false,
      prediction_modes: PredictionModesSetting::Simple,
      include_near_mvs: false,
      no_scene_detection: false,
160
      diamond_me: false,
161
      cdef: false,
162 163
    }
  }
164 165 166
}

impl SpeedSettings {
Vibhoothi's avatar
Vibhoothi committed
167 168 169 170 171 172 173 174 175 176 177 178 179
  /// Set the speed setting according to a numeric speed preset.
  /// The speed settings vary depending on speed value from 0 to 10:
  ///  - speed - 10, fastest, Min block size 64x64, TX domain distortion, fast deblock, no scenechange detection,
  ///  - speed - 9, Min block size 64x64, TX domain distortion, fast deblock,
  ///  - speed - 8, Min block size 8x8, reduced TX set, TX domain distortion, fast deblock,
  ///  - speed - 7, Min block size 8x8, reduced TX set, TX domain distortion,
  ///  - speed - 6, Min block size 8x8, reduced TX set, TX domain distortion,
  ///  - speed - 5, default, Min block size 8x8, reduced TX set, TX domain distortion, complex pred modes for keyframes,
  ///  - speed - 4, Min block size 8x8, TX domain distortion, complex pred modes for keyframes,
  ///  - speed - 3, Min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision,
  ///  - speed - 2, Min block size 8x8, TX domain distortion, complex pred modes for keyframes, RDO TX decision, include near MVs,
  ///  - speed - 1, Min block size 8x8, TX domain distortion, complex pred modes, RDO TX decision, include near MVs,
  ///  - speed - 0, slowest,  Min block size 4x4, TX domain distortion, complex pred modes, RDO TX decision, include near MVs, bottom-up encoding.
180 181 182 183 184 185 186
  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),
187
      tx_domain_rate: Self::tx_domain_rate_preset(speed),
188 189 190 191
      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),
192
      no_scene_detection: Self::no_scene_detection_preset(speed),
193
      diamond_me: Self::diamond_me_preset(speed),
194
      cdef: Self::cdef_preset(speed),
195 196 197
    }
  }

198 199
  /// 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).
200
  fn min_block_size_preset(speed: usize) -> BlockSize {
201
    if speed == 0 {
202
      BlockSize::BLOCK_4X4
203
    } else if speed <= 8 {
204 205 206 207 208 209
      BlockSize::BLOCK_8X8
    } else {
      BlockSize::BLOCK_64X64
    }
  }

210 211 212 213
  /// 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.
214
  fn multiref_preset(speed: usize) -> bool {
215
    speed <= 1
216 217 218
  }

  fn fast_deblock_preset(speed: usize) -> bool {
219
    speed >= 8
220 221 222
  }

  fn reduced_tx_set_preset(speed: usize) -> bool {
223
    speed >= 5
224 225
  }

226 227 228
  /// TX domain distortion is always faster, with no significant quality change
  fn tx_domain_distortion_preset(_speed: usize) -> bool {
    true
229 230
  }

231 232 233 234
  fn tx_domain_rate_preset(_speed: usize) -> bool {
    false
  }

235 236 237 238 239 240 241 242 243
  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 {
244
    if speed <= 1 {
245
      PredictionModesSetting::ComplexAll
246
    } else if speed <= 5 {
247 248 249 250 251 252 253 254 255
      PredictionModesSetting::ComplexKeyframes
    } else {
      PredictionModesSetting::Simple
    }
  }

  fn include_near_mvs_preset(speed: usize) -> bool {
    speed <= 2
  }
256 257 258 259

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

261 262 263 264 265 266 267
  /// 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
268
  }
269 270 271 272

  fn cdef_preset(_speed: usize) -> bool {
    true
  }
273 274
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
#[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"),
    }
  }
}

297 298 299 300 301 302 303
#[derive(Clone, Copy, Debug, PartialOrd, PartialEq)]
pub enum PredictionModesSetting {
  Simple,
  ComplexKeyframes,
  ComplexAll,
}

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
#[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
  }
}

346 347 348 349 350 351
#[derive(ArgEnum, Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub enum PixelRange {
    Unspecified = 0,
    Limited,
    Full,
352 353 354 355 356 357 358 359
}

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

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
#[derive(ArgEnum, Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub enum MatrixCoefficients {
    Identity = 0,
    BT709,
    Unspecified,
    BT470M = 4,
    BT470BG,
    ST170M,
    ST240M,
    YCgCo,
    BT2020NonConstantLuminance,
    BT2020ConstantLuminance,
    ST2085,
    ChromaticityDerivedNonConstantLuminance,
    ChromaticityDerivedConstantLuminance,
    ICtCp,
377 378 379 380 381 382 383 384
}

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

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
#[derive(ArgEnum, Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub enum ColorPrimaries {
    BT709 = 1,
    Unspecified,
    BT470M = 4,
    BT470BG,
    ST170M,
    ST240M,
    Film,
    BT2020,
    ST428,
    P3DCI,
    P3Display,
    Tech3213 = 22,
400 401 402 403 404 405 406 407
}

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

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
#[derive(ArgEnum, Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub enum TransferCharacteristics {
    BT1886 = 1,
    Unspecified,
    BT470M = 4,
    BT470BG,
    ST170M,
    ST240M,
    Linear,
    Logarithmic100,
    Logarithmic316,
    XVYCC,
    BT1361E,
    SRGB,
    BT2020Ten,
    BT2020Twelve,
    PerceptualQuantizer,
    ST428,
    HybridLogGamma,
428 429 430 431 432 433 434 435
}

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

436 437 438 439 440 441 442
#[derive(Copy, Clone, Debug)]
pub struct ColorDescription {
    pub color_primaries: ColorPrimaries,
    pub transfer_characteristics: TransferCharacteristics,
    pub matrix_coefficients: MatrixCoefficients
}

443 444 445 446 447 448 449 450 451 452 453 454 455 456
#[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,
}

457
/// Contains all the encoder configuration
458
#[derive(Clone, Debug)]
459
pub struct Config {
Luca Barbato's avatar
Luca Barbato committed
460 461 462
  pub enc: EncoderConfig,
  /// The number of threads in the threadpool.
  pub threads: usize
Luca Barbato's avatar
Luca Barbato committed
463 464 465
}

impl Config {
466
  pub fn new_context<T: Pixel>(&self) -> Context<T> {
467 468
    assert!(8 * std::mem::size_of::<T>() >= self.enc.bit_depth, "The Pixel u{} does not match the Config bit_depth {}",
            8 * std::mem::size_of::<T>(), self.enc.bit_depth);
469 470 471
    // initialize with temporal delimiter
    let packet_data = TEMPORAL_DELIMITER.to_vec();

472 473 474 475 476 477
    let maybe_ac_qi_max = if self.enc.quantizer < 255 {
      Some(self.enc.quantizer as u8)
    } else {
      None
    };

Romain Vimont's avatar
Romain Vimont committed
478
    let pool = rayon::ThreadPoolBuilder::new().num_threads(self.threads).build().unwrap();
Luca Barbato's avatar
Luca Barbato committed
479

Josh Holmer's avatar
Josh Holmer committed
480
    Context {
Luca Barbato's avatar
Luca Barbato committed
481
      inner: ContextInner {
Luca Barbato's avatar
Luca Barbato committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        frame_count: 0,
        limit: 0,
        idx: 0,
        frames_processed: 0,
        frame_q: BTreeMap::new(),
        frame_invariants: BTreeMap::new(),
        keyframes: BTreeSet::new(),
        packet_data,
        segment_start_idx: 0,
        segment_start_frame: 0,
        keyframe_detector: SceneChangeDetector::new(self.enc.bit_depth),
        config: self.enc.clone(),
        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,
        first_pass_data: FirstPassData { frames: Vec::new() },
        pool
506
      },
Luca Barbato's avatar
Luca Barbato committed
507
      config: self.enc.clone()
Josh Holmer's avatar
Josh Holmer committed
508
    }
Luca Barbato's avatar
Luca Barbato committed
509 510 511
  }
}

Luca Barbato's avatar
Luca Barbato committed
512
pub struct ContextInner<T: Pixel> {
fbossen's avatar
fbossen committed
513
  frame_count: u64,
514
  limit: u64,
515
  pub(crate) idx: u64,
Josh Holmer's avatar
Josh Holmer committed
516 517
  frames_processed: u64,
  /// Maps frame *number* to frames
518
  frame_q: BTreeMap<u64, Option<Arc<Frame<T>>>>, //    packet_q: VecDeque<Packet>
Josh Holmer's avatar
Josh Holmer committed
519
  /// Maps frame *idx* to frame data
Luca Barbato's avatar
Luca Barbato committed
520
  frame_invariants: BTreeMap<u64, FrameInvariants<T>>,
Josh Holmer's avatar
Josh Holmer committed
521
  /// A list of keyframe *numbers* in this encode. Needed so that we don't
Luca Barbato's avatar
Luca Barbato committed
522
  /// need to keep all of the frame_invariants in memory for the whole life of the encode.
Josh Holmer's avatar
Josh Holmer committed
523
  keyframes: BTreeSet<u64>,
524
  /// A storage space for reordered frames.
Josh Holmer's avatar
Josh Holmer committed
525 526 527
  packet_data: Vec<u8>,
  segment_start_idx: u64,
  segment_start_frame: u64,
528
  keyframe_detector: SceneChangeDetector<T>,
529
  pub(crate) config: EncoderConfig,
530
  rc_state: RCState,
531
  maybe_prev_log_base_q: Option<i64>,
532
  pub first_pass_data: FirstPassData,
Luca Barbato's avatar
Luca Barbato committed
533
  pool: rayon::ThreadPool,
Luca Barbato's avatar
Luca Barbato committed
534 535
}

Luca Barbato's avatar
Luca Barbato committed
536 537 538 539 540
pub struct Context<T: Pixel> {
  inner: ContextInner<T>,
  config: EncoderConfig,
}

Luca Barbato's avatar
Luca Barbato committed
541 542
#[derive(Clone, Copy, Debug)]
pub enum EncoderStatus {
Luca Barbato's avatar
Luca Barbato committed
543 544
  /// The encoder needs more data to produce an output Packet
  /// May be emitted by `Context::receive_packet`  when frame reordering is enabled.
Luca Barbato's avatar
Luca Barbato committed
545 546
  NeedMoreData,
  /// There are enough Frames queue
Luca Barbato's avatar
Luca Barbato committed
547
  /// May be emitted by `Context::send_frame` when the input queue is constrained
Luca Barbato's avatar
Luca Barbato committed
548
  EnoughData,
Luca Barbato's avatar
Luca Barbato committed
549 550 551 552 553
  /// The encoder already produced the number of frames requested
  /// May be emitted by `Context::receive_packet` after a flush request had been processed
  /// or the frame limit had been reached.
  LimitReached,
  /// Generic fatal error
Luca Barbato's avatar
Luca Barbato committed
554
  Failure,
Luca Barbato's avatar
Luca Barbato committed
555 556
}

557
pub struct Packet<T: Pixel> {
Luca Barbato's avatar
Luca Barbato committed
558
  pub data: Vec<u8>,
559
  pub rec: Option<Frame<T>>,
fbossen's avatar
fbossen committed
560
  pub number: u64,
561 562 563
  pub frame_type: FrameType,
  /// PSNR for Y, U, and V planes
  pub psnr: Option<(f64, f64, f64)>,
564 565
}

566
impl<T: Pixel> fmt::Display for Packet<T> {
567
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Luca Barbato's avatar
Luca Barbato committed
568 569 570 571 572 573 574
    write!(
      f,
      "Frame {} - {} - {} bytes",
      self.number,
      self.frame_type,
      self.data.len()
    )
575
  }
Luca Barbato's avatar
Luca Barbato committed
576 577
}

578 579
impl<T: Pixel> Context<T> {
  pub fn new_frame(&self) -> Arc<Frame<T>> {
Josh Holmer's avatar
Josh Holmer committed
580
    Arc::new(Frame::new(
581 582 583
      self.config.width,
      self.config.height,
      self.config.chroma_sampling
Josh Holmer's avatar
Josh Holmer committed
584
    ))
Luca Barbato's avatar
Luca Barbato committed
585 586 587 588
  }

  pub fn send_frame<F>(&mut self, frame: F) -> Result<(), EncoderStatus>
  where
589 590
    F: Into<Option<Arc<Frame<T>>>>,
    T: Pixel,
Luca Barbato's avatar
Luca Barbato committed
591
  {
592 593 594 595 596 597
    let frame = frame.into();

    if frame.is_none() {
        self.inner.limit = self.inner.frame_count;
    }

Luca Barbato's avatar
Luca Barbato committed
598
    self.inner.send_frame(frame)
Luca Barbato's avatar
Luca Barbato committed
599 600
  }

Luca Barbato's avatar
Luca Barbato committed
601 602
  pub fn receive_packet(&mut self) -> Result<Packet<T>, EncoderStatus> {
    self.inner.receive_packet()
603 604
  }

Luca Barbato's avatar
Luca Barbato committed
605 606
  pub fn flush(&mut self) {
    self.send_frame(None).unwrap();
607 608
  }

609 610 611
  pub fn container_sequence_header(&mut self) -> Vec<u8> {
    fn sequence_header_inner(seq: &Sequence) -> io::Result<Vec<u8>> {
      let mut buf = Vec::new();
612

613
      {
614 615 616 617
        let mut bw = BitWriter::endian(&mut buf, BigEndian);
        bw.write_bit(true)?; // marker
        bw.write(7, 1)?; // version
        bw.write(3, seq.profile)?;
618
        bw.write(5, 31)?; // level
619 620 621 622 623 624 625 626 627 628 629 630
        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
631
      }
632

633 634 635
      Ok(buf)
    }

636
    let seq = Sequence::new(&self.config);
637 638

    sequence_header_inner(&seq).unwrap()
639 640
  }

Luca Barbato's avatar
Luca Barbato committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  pub fn get_first_pass_data(&self) -> &FirstPassData {
    &self.inner.first_pass_data
  }

  pub fn set_limit(&mut self, limit: u64) {
    self.inner.set_limit(limit);
  }
}


impl<T: Pixel> ContextInner<T> {
  pub fn send_frame<F>(&mut self, frame: F) -> Result<(), EncoderStatus>
  where
    F: Into<Option<Arc<Frame<T>>>>,
    T: Pixel,
  {
    let idx = self.frame_count;
658 659 660 661 662
    let frame = frame.into();
    if frame.is_some() {
      self.frame_count += 1;
    }
    self.frame_q.insert(idx, frame);
Luca Barbato's avatar
Luca Barbato committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    Ok(())
  }

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

  pub fn get_frame_count(&self) -> u64 {
    self.frame_count
  }

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

  pub(crate) 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)
  }

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

Josh Holmer's avatar
Josh Holmer committed
687
  fn next_keyframe(&self) -> u64 {
Luca Barbato's avatar
Luca Barbato committed
688
    let next_detected = self.frame_invariants.values()
Josh Holmer's avatar
Josh Holmer committed
689 690
      .find(|fi| fi.frame_type == FrameType::KEY && fi.number > self.segment_start_frame)
      .map(|fi| fi.number);
691
    let next_limit = self.segment_start_frame + self.config.max_key_frame_interval;
692
    let next_limit = if self.limit != 0 { next_limit.min(self.limit) } else { next_limit };
Josh Holmer's avatar
Josh Holmer committed
693 694 695 696 697
    if next_detected.is_none() {
      return next_limit;
    }
    cmp::min(next_detected.unwrap(), next_limit)
  }
fbossen's avatar
fbossen committed
698

699 700
  fn set_frame_properties(&mut self, idx: u64) -> Result<bool, EncoderStatus> {
    let (fi, end_of_subgop) = self.build_frame_properties(idx)?;
Luca Barbato's avatar
Luca Barbato committed
701
    self.frame_invariants.insert(idx, fi);
702

703
    Ok(end_of_subgop)
Josh Holmer's avatar
Josh Holmer committed
704 705
  }

706
  fn build_frame_properties(&mut self, idx: u64) -> Result<(FrameInvariants<T>, bool), EncoderStatus> {
Josh Holmer's avatar
Josh Holmer committed
707
    if idx == 0 {
708
      let seq = Sequence::new(&self.config);
709

Josh Holmer's avatar
Josh Holmer committed
710
      // The first frame will always be a key frame
Josh Holmer's avatar
Josh Holmer committed
711 712
      let fi = FrameInvariants::new_key_frame(
        &FrameInvariants::new(
713
          self.config.clone(),
714
          seq
Josh Holmer's avatar
Josh Holmer committed
715 716 717
        ),
        0
      );
718
      return Ok((fi, true));
Josh Holmer's avatar
Josh Holmer committed
719 720
    }

Luca Barbato's avatar
Luca Barbato committed
721
    let mut fi = self.frame_invariants[&(idx - 1)].clone();
Josh Holmer's avatar
Josh Holmer committed
722

723
    // FIXME: inter unsupported with 4:2:2 and 4:4:4 chroma sampling
724
    let chroma_sampling = self.config.chroma_sampling;
725 726 727
    let keyframe_only = chroma_sampling == ChromaSampling::Cs444 ||
      chroma_sampling == ChromaSampling::Cs422;

Josh Holmer's avatar
Josh Holmer committed
728 729 730 731 732 733
    // 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 {
734
      let next_keyframe = if keyframe_only { self.segment_start_frame + 1 } else { self.next_keyframe() };
735
      let (fi_temp, end_of_subgop) = FrameInvariants::new_inter_frame(
Josh Holmer's avatar
Josh Holmer committed
736
        &fi,
737 738 739 740
        self.segment_start_frame,
        idx_in_segment,
        next_keyframe
      );
Josh Holmer's avatar
Josh Holmer committed
741
      fi = fi_temp;
742
      if !end_of_subgop {
Josh Holmer's avatar
Josh Holmer committed
743 744 745
        if !fi.inter_cfg.unwrap().reorder
          || ((idx_in_segment - 1) % fi.inter_cfg.unwrap().group_len == 0
          && fi.number == (next_keyframe - 1))
746
        {
Josh Holmer's avatar
Josh Holmer committed
747
          self.segment_start_idx = idx;
Josh Holmer's avatar
Josh Holmer committed
748
          self.segment_start_frame = next_keyframe;
Josh Holmer's avatar
Josh Holmer committed
749
          fi.number = next_keyframe;
Josh Holmer's avatar
Josh Holmer committed
750
        } else {
751
          return Ok((fi, false));
Josh Holmer's avatar
Josh Holmer committed
752 753
        }
      }
fbossen's avatar
fbossen committed
754
    }
Luca Barbato's avatar
Luca Barbato committed
755

756 757
    match self.frame_q.get(&fi.number) {
      Some(Some(_)) => {},
758
      _ => { return Err(EncoderStatus::NeedMoreData); }
759 760
    }

Josh Holmer's avatar
Josh Holmer committed
761
    // Now that we know the frame number, look up the correct frame type
Josh Holmer's avatar
Josh Holmer committed
762 763 764 765 766 767 768
    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
769

Josh Holmer's avatar
Josh Holmer committed
770 771 772 773 774
    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();
775
      let (fi_temp, end_of_subgop) = FrameInvariants::new_inter_frame(
Josh Holmer's avatar
Josh Holmer committed
776 777 778 779 780 781
        &fi,
        self.segment_start_frame,
        idx_in_segment,
        next_keyframe
      );
      fi = fi_temp;
782
      if !end_of_subgop {
783
        return Ok((fi, false));
Josh Holmer's avatar
Josh Holmer committed
784 785
      }
    }
786
    Ok((fi, true))
fbossen's avatar
fbossen committed
787
  }
Luca Barbato's avatar
Luca Barbato committed
788

789
  pub fn receive_packet(&mut self) -> Result<Packet<T>, EncoderStatus> {
790
    if self.limit != 0 && self.frames_processed == self.limit {
Luca Barbato's avatar
Luca Barbato committed
791
      return Err(EncoderStatus::LimitReached);
792 793
    }

794
    if self.needs_more_lookahead() {
Luca Barbato's avatar
Luca Barbato committed
795
      return Err(EncoderStatus::NeedMoreData);
796 797
    }

798 799
    let idx = {
      let mut idx = self.idx;
800
      while !self.set_frame_properties(idx)? {
801 802 803
        self.idx += 1;
        idx = self.idx;
      }
Luca Barbato's avatar
Luca Barbato committed
804

Luca Barbato's avatar
Luca Barbato committed
805
      if !self.needs_more_frames(self.frame_invariants[&idx].number) {
806
        self.idx += 1;
Luca Barbato's avatar
Luca Barbato committed
807
        return Err(EncoderStatus::LimitReached);
808 809 810
      }
      idx
    };
811

812
    let ret = {
Luca Barbato's avatar
Luca Barbato committed
813
      let fi = self.frame_invariants.get_mut(&idx).unwrap();
Luca Barbato's avatar
Luca Barbato committed
814 815
      if fi.show_existing_frame {
        self.idx += 1;
Luca Barbato's avatar
Luca Barbato committed
816

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

819 820
        // TODO: Record the bits spent here against the original frame for rate
        //  control purposes, or add a new frame subtype?
821
        let sef_data = encode_show_existing_frame(fi, &mut fs);
822
        self.packet_data.extend(sef_data);
Luca Barbato's avatar
Luca Barbato committed
823

Luca Barbato's avatar
Luca Barbato committed
824
        let rec = if fi.show_frame { Some(fs.rec) } else { None };
825
        let fi = fi.clone();
826
        self.finalize_packet(rec, &fi)
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
      } else if let Some(f) = self.frame_q.get(&fi.number) {
        self.idx += 1;

        if let Some(frame) = f.clone() {
          let fti = fi.get_frame_subtype();
          let qps =
            self.rc_state.select_qi(self, fti, self.maybe_prev_log_base_q);
          let fi = self.frame_invariants.get_mut(&idx).unwrap();
          fi.set_quantizers(&qps);
          let mut fs = FrameState::new_with_frame(fi, frame.clone());

          // TODO: Trial encoding for first frame of each type.
          let data = self.pool.install(||encode_frame(fi, &mut fs));
          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
          );
          self.packet_data.extend(data);

          fs.rec.pad(fi.width, fi.height);

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

          update_rec_buffer(fi, fs);

          if fi.show_frame {
            let fi = fi.clone();
            self.finalize_packet(rec, &fi)
860 861 862
          } else {
            Err(EncoderStatus::NeedMoreData)
          }
fbossen's avatar
fbossen committed
863 864 865
        } else {
          Err(EncoderStatus::NeedMoreData)
        }
866 867
      } else {
        Err(EncoderStatus::NeedMoreData)
fbossen's avatar
fbossen committed
868
      }
869 870 871
    };

    if let Ok(ref pkt) = ret {
Luca Barbato's avatar
Luca Barbato committed
872
      self.garbage_collect(pkt.number);
873 874 875
    }

    ret
Luca Barbato's avatar
Luca Barbato committed
876 877
  }

878
  fn finalize_packet(&mut self, rec: Option<Frame<T>>, fi: &FrameInvariants<T>) -> Result<Packet<T>, EncoderStatus> {
879 880 881 882 883 884 885
    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;
886
    if self.config.show_psnr {
887
      if let Some(ref rec) = rec {
888
        let original_frame = self.get_frame(fi.number);
889 890 891 892 893 894 895 896
        psnr = Some(calculate_frame_psnr(
          &*original_frame,
          rec,
          fi.sequence.bit_depth
        ));
      }
    }

897
    if self.config.pass == Some(1) {
898 899 900
      self.first_pass_data.frames.push(FirstPassFrame::from(fi));
    }

901 902 903 904 905 906 907 908 909 910
    self.frames_processed += 1;
    Ok(Packet {
      data,
      rec,
      number: fi.number,
      frame_type: fi.frame_type,
      psnr
    })
  }

911
  fn garbage_collect(&mut self, cur_frame: u64) {
Josh Holmer's avatar
Josh Holmer committed
912 913 914 915 916 917 918 919 920 921
    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) {
Luca Barbato's avatar
Luca Barbato committed
922
      self.frame_invariants.remove(&i);
Josh Holmer's avatar
Josh Holmer committed
923 924 925 926 927
    }
  }

  fn determine_frame_type(&mut self, frame_number: u64) -> FrameType {
    if frame_number == 0 {
Josh Holmer's avatar
Josh Holmer committed
928 929
      return FrameType::KEY;
    }
930 931
    if self.config.speed_settings.no_scene_detection {
      if frame_number % self.config.max_key_frame_interval == 0 {
932 933 934 935 936
        return FrameType::KEY;
      } else {
        return FrameType::INTER;
      }
    }
Josh Holmer's avatar
Josh Holmer committed
937

Josh Holmer's avatar
Josh Holmer committed
938 939 940 941 942 943 944 945
    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
946
    if let Some(frame) = frame {
Josh Holmer's avatar
Josh Holmer committed
947
      let distance = frame_number - prev_keyframe;
948 949
      if distance < self.config.min_key_frame_interval {
        if distance + 1 == self.config.min_key_frame_interval {
950
          self.keyframe_detector.set_last_frame(frame, frame_number as usize);
Josh Holmer's avatar
Josh Holmer committed
951 952 953
        }
        return FrameType::INTER;
      }
954
      if distance >= self.config.max_key_frame_interval {
Josh Holmer's avatar
Josh Holmer committed
955 956
        return FrameType::KEY;
      }
Josh Holmer's avatar
Josh Holmer committed
957
      if self.keyframe_detector.detect_scene_change(frame, frame_number as usize) {
Josh Holmer's avatar
Josh Holmer committed
958 959 960 961 962
        return FrameType::KEY;
      }
    }
    FrameType::INTER
  }
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993

  // 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) {
Luca Barbato's avatar
Luca Barbato committed
994
      if let Some(fd) = self.frame_invariants.get(&idx) {
995 996 997 998 999 1000
        if fd.frame_type == FrameType::KEY {
          collect_counts(nframes, &mut acc);
          prev_keyframe = idx;
          continue;
        }
      } else if idx == 0
1001
        || idx - prev_keyframe >= self.config.max_key_frame_interval
1002 1003 1004 1005 1006 1007 1008
      {
        collect_counts(nframes, &mut acc);
        prev_keyframe = idx;
        continue;
      }
      // TODO: Implement golden P-frames.
      let mut fti = FRAME_SUBTYPE_P;
1009
      if !self.config.low_latency {
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        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
1036
}
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

#[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,
}

1049 1050
impl<T: Pixel> From<&FrameInvariants<T>> for FirstPassFrame {
  fn from(fi: &FrameInvariants<T>) -> FirstPassFrame {
1051 1052 1053 1054 1055
    FirstPassFrame {
      number: fi.number,
      frame_type: fi.frame_type,
    }
  }
1056
}
1057 1058 1059 1060 1061

#[cfg(test)]
mod test {
  use super::*;

1062 1063
  use interpolate_name::interpolate_test;

1064 1065 1066
  fn setup_encoder<T: Pixel>(
    w: usize, h: usize, speed: usize, quantizer: usize, bit_depth: usize,
    chroma_sampling: ChromaSampling, min_keyint: u64, max_keyint: u64,
1067 1068 1069
    bitrate: i32,
    low_latency: bool,
    no_scene_detection: bool,
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
  ) -> Context<T> {
    assert!(bit_depth == 8 || std::mem::size_of::<T>() > 1);
    let mut enc = EncoderConfig::with_speed_preset(speed);
    enc.quantizer = quantizer;
    enc.min_key_frame_interval = min_keyint;
    enc.max_key_frame_interval = max_keyint;
    enc.low_latency = low_latency;
    enc.width = w;
    enc.height = h;
    enc.bit_depth = bit_depth;
    enc.chroma_sampling = chroma_sampling;
    enc.bitrate = bitrate;
1082
    enc.speed_settings.no_scene_detection = no_scene_detection;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

    let cfg = Config { enc, threads: 0 };

    cfg.new_context()
  }

  /*
  fn fill_frame<T: Pixel>(ra: &mut ChaChaRng, frame: &mut Frame<T>) {
    for plane in frame.planes.iter_mut() {
      let stride = plane.cfg.stride;
      for row in plane.data.chunks_mut(stride) {
        for pixel in row {
          let v: u8 = ra.gen();
          *pixel = T::cast_from(v);
        }
      }
    }
  }
  */

1103 1104 1105 1106 1107 1108

  #[interpolate_test(low_latency_no_scene_change, true, true)]
  #[interpolate_test(reorder_no_scene_change, false, true)]
  #[interpolate_test(low_latency_scene_change_detection, true, false)]
  #[interpolate_test(reorder_scene_change_detection, false, false)]
  fn flush(low_lantency: bool, no_scene_detection: bool) {
1109 1110
    let mut ctx = setup_encoder::<u8>(64, 80, 10, 100, 8, ChromaSampling::Cs420, 150, 200, 0, low_lantency, no_scene_detection);
    let limit = 41;
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

    ctx.set_limit(limit);

    for _ in  0..limit {
      let input = ctx.new_frame();
      let _ = ctx.send_frame(input);
    }

    ctx.flush();

    let mut count = 0;

    'out: for _ in 0..limit {
      loop {
        match ctx.receive_packet() {
          Ok(_) => {
            eprintln!("Packet Received {}/{}", count, limit);
            count += 1;
          },
          Err(EncoderStatus::EnoughData) => {
            eprintln!("{:?}", EncoderStatus::EnoughData);

            break 'out;
          }
          Err(e) => {
            eprintln!("{:?}", e);
            break;
          }
        }
      }
    }

    assert_eq!(limit, count);
  }
1145 1146 1147 1148 1149 1150 1151


  #[interpolate_test(low_latency_no_scene_change, true, true)]
  #[interpolate_test(reorder_no_scene_change, false, true)]
  #[interpolate_test(low_latency_scene_change_detection, true, false)]
  #[interpolate_test(reorder_scene_change_detection, false, false)]
  fn flush_unlimited(low_lantency: bool, no_scene_detection: bool) {
1152 1153
    let mut ctx = setup_encoder::<u8>(64, 80, 10, 100, 8, ChromaSampling::Cs420, 150, 200, 0, low_lantency, no_scene_detection);
    let limit = 41;
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185

    for _ in  0..limit {
      let input = ctx.new_frame();
      let _ = ctx.send_frame(input);
    }

    ctx.flush();

    let mut count = 0;

    'out: for _ in 0..limit {
      loop {
        match ctx.receive_packet() {
          Ok(_) => {
            eprintln!("Packet Received {}/{}", count, limit);
            count += 1;
          },
          Err(EncoderStatus::EnoughData) => {
            eprintln!("{:?}", EncoderStatus::EnoughData);

            break 'out;
          }
          Err(e) => {
            eprintln!("{:?}", e);
            break;
          }
        }
      }
    }

    assert_eq!(limit, count);
  }
1186
}