encoder.rs 105 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 api::*;
11
use cdef::*;
12
use context::*;
13 14
use deblock::*;
use ec::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
15
use lrf::*;
16
use mc::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
17
use me::*;
18 19
use partition::*;
use plane::*;
20
use quantize::*;
21
use rdo::*;
Raphaël Zumer's avatar
Raphaël Zumer committed
22
use segmentation::*;
23
use transform::*;
24
use util::*;
25
use partition::PartitionType::*;
26

27
use bitstream_io::{BitWriter, BigEndian, LittleEndian};
28
use std;
Raphaël Zumer's avatar
Raphaël Zumer committed
29
use std::{fmt, io};
Josh Holmer's avatar
Josh Holmer committed
30
use std::io::Write;
31
use std::rc::Rc;
Raphaël Zumer's avatar
Raphaël Zumer committed
32
use std::sync::Arc;
33 34 35 36 37 38 39 40 41 42 43

extern {
    pub fn av1_rtcd();
    pub fn aom_dsp_rtcd();
}

#[derive(Debug, Clone)]
pub struct Frame {
    pub planes: [Plane; 3]
}

44 45
const FRAME_MARGIN: usize = 16 + SUBPEL_FILTER_SIZE;

46
impl Frame {
47
    pub fn new(width: usize, height: usize, chroma_sampling: ChromaSampling) -> Frame {
48
        let chroma_sampling_period = chroma_sampling.sampling_period();
49
        let (chroma_width, chroma_height, chroma_padding, chroma_xdec, chroma_ydec) = (
50
            width / chroma_sampling_period.0,
51 52 53 54
            height / chroma_sampling_period.1,
            MAX_SB_SIZE / chroma_sampling_period.0 + FRAME_MARGIN,
            chroma_sampling_period.0 - 1,
            chroma_sampling_period.1 - 1
55
        );
56

57 58
        Frame {
            planes: [
59 60 61 62 63 64
                Plane::new(
                    width, height,
                    0, 0,
                    MAX_SB_SIZE + FRAME_MARGIN, MAX_SB_SIZE + FRAME_MARGIN
                ),
                Plane::new(
65
                    chroma_width, chroma_height,
66 67
                    chroma_xdec, chroma_ydec,
                    chroma_padding, chroma_padding
68 69
                ),
                Plane::new(
70
                    chroma_width, chroma_height,
71 72
                    chroma_xdec, chroma_ydec,
                    chroma_padding, chroma_padding
73
                )
74 75 76
            ]
        }
    }
fbossen's avatar
fbossen committed
77

Frank Bossen's avatar
Frank Bossen committed
78
    pub fn pad(&mut self, w: usize, h: usize) {
fbossen's avatar
fbossen committed
79
        for p in self.planes.iter_mut() {
Frank Bossen's avatar
Frank Bossen committed
80
            p.pad(w, h);
fbossen's avatar
fbossen committed
81 82
        }
    }
83

Josh Holmer's avatar
Josh Holmer committed
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
    /// Returns a `PixelIter` containing the data of this frame's planes in YUV format.
    /// Each point in the `PixelIter` is a triple consisting of a Y, U, and V component.
    /// The `PixelIter` is laid out as contiguous rows, e.g. to get a given 0-indexed row
    /// you could use `data.skip(width * row_idx).take(width)`.
    ///
    /// This data retains any padding, e.g. it uses the width and height specifed in
    /// the Y-plane's `cfg` struct, and not the display width and height specied in
    /// `FrameInvariants`.
    pub fn iter(&self) -> PixelIter {
      PixelIter::new(&self.planes)
    }
}

#[derive(Debug)]
pub struct PixelIter<'a> {
  planes: &'a [Plane; 3],
  y: usize,
  x: usize,
}

impl<'a> PixelIter<'a> {
  pub fn new(planes: &'a [Plane; 3]) -> Self {
    PixelIter {
      planes,
      y: 0,
      x: 0,
    }
  }

  fn width(&self) -> usize {
    self.planes[0].cfg.width
  }

  fn height(&self) -> usize {
    self.planes[0].cfg.height
  }
}

impl<'a> Iterator for PixelIter<'a> {
  type Item = (u16, u16, u16);

  fn next(&mut self) -> Option<<Self as Iterator>::Item> {
    if self.y == self.height() - 1 && self.x == self.width() - 1 {
      return None;
    }
    let pixel = (
      self.planes[0].p(self.x, self.y),
      self.planes[1].p(self.x / 2, self.y / 2),
      self.planes[2].p(self.x / 2, self.y / 2),
    );
    if self.x == self.width() - 1 {
      self.x = 0;
      self.y += 1;
    } else {
      self.x += 1;
    }
    Some(pixel)
  }
142 143
}

144 145
#[derive(Debug, Clone)]
pub struct ReferenceFrame {
fbossen's avatar
fbossen committed
146
  pub order_hint: u32,
147
  pub frame: Frame,
148 149
  pub input_hres: Plane,
  pub input_qres: Plane,
150
  pub cdfs: CDFContext
151 152
}

Josh Holmer's avatar
Josh Holmer committed
153
#[derive(Debug, Clone)]
154
pub struct ReferenceFramesSet {
155
    pub frames: [Option<Rc<ReferenceFrame>>; (REF_FRAMES as usize)],
156
    pub deblock: [DeblockState; (REF_FRAMES as usize)]
157 158 159 160 161
}

impl ReferenceFramesSet {
    pub fn new() -> ReferenceFramesSet {
        ReferenceFramesSet {
162
            frames: Default::default(),
163
            deblock: Default::default()
164 165 166 167 168 169 170 171
        }
    }
}

const MAX_NUM_TEMPORAL_LAYERS: usize = 8;
const MAX_NUM_SPATIAL_LAYERS: usize = 4;
const MAX_NUM_OPERATING_POINTS: usize = MAX_NUM_TEMPORAL_LAYERS * MAX_NUM_SPATIAL_LAYERS;

172
pub const PRIMARY_REF_NONE: u32 = 7;
173 174 175 176
const PRIMARY_REF_BITS: u32 = 3;

arg_enum!{
    #[derive(Copy, Clone, Debug, PartialEq)]
177
    #[repr(C)]
178 179 180 181 182 183 184 185 186 187 188 189 190
    pub enum Tune {
        Psnr,
        Psychovisual
    }
}

impl Default for Tune {
    fn default() -> Self {
        Tune::Psnr
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
191
#[repr(C)]
192 193 194 195 196 197 198 199 200 201 202 203
pub enum ChromaSampling {
    Cs420,
    Cs422,
    Cs444
}

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

204 205 206 207 208 209 210 211 212 213 214
impl ChromaSampling {
    // Provides the sampling period in the horizontal and vertical axes.
    pub fn sampling_period(self) -> (usize, usize) {
        match self {
            ChromaSampling::Cs420 => (2, 2),
            ChromaSampling::Cs422 => (2, 1),
            ChromaSampling::Cs444 => (1, 1)
        }
    }
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C)]
pub enum ChromaSamplePosition {
    Unknown,
    Vertical,
    Colocated
}

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

229
#[derive(Copy, Clone, Debug)]
230
pub struct Sequence {
231
    // OBU Sequence header of AV1
232 233 234 235 236
    pub profile: u8,
    pub num_bits_width: u32,
    pub num_bits_height: u32,
    pub bit_depth: usize,
    pub chroma_sampling: ChromaSampling,
237
    pub chroma_sample_position: ChromaSamplePosition,
238
    pub color_description: Option<ColorDescription>,
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
    pub max_frame_width: u32,
    pub max_frame_height: u32,
    pub frame_id_numbers_present_flag: bool,
    pub frame_id_length: u32,
    pub delta_frame_id_length: u32,
    pub use_128x128_superblock: bool,
    pub order_hint_bits_minus_1: u32,
    pub force_screen_content_tools: u32,  // 0 - force off
                                           // 1 - force on
                                           // 2 - adaptive
    pub force_integer_mv: u32,      // 0 - Not to force. MV can be in 1/4 or 1/8
                                     // 1 - force to integer
                                     // 2 - adaptive
    pub still_picture: bool,               // Video is a single frame still picture
    pub reduced_still_picture_hdr: bool,   // Use reduced header for still picture
    pub monochrome: bool,                  // Monochrome video
    pub enable_intra_edge_filter: bool,    // enables/disables corner/edge/upsampling
    pub enable_interintra_compound: bool,  // enables/disables interintra_compound
    pub enable_masked_compound: bool,      // enables/disables masked compound
    pub enable_dual_filter: bool,         // 0 - disable dual interpolation filter
                                          // 1 - enable vert/horiz filter selection
    pub enable_order_hint: bool,     // 0 - disable order hint, and related tools
                                     // jnt_comp, ref_frame_mvs, frame_sign_bias
                                     // if 0, enable_jnt_comp and
                                     // enable_ref_frame_mvs must be set zs 0.
    pub enable_jnt_comp: bool,        // 0 - disable joint compound modes
                                     // 1 - enable it
    pub enable_ref_frame_mvs: bool,  // 0 - disable ref frame mvs
                                     // 1 - enable it
    pub enable_warped_motion: bool,   // 0 - disable warped motion for sequence
                                     // 1 - enable it for the sequence
    pub enable_superres: bool,// 0 - Disable superres for the sequence, and disable
                              //     transmitting per-frame superres enabled flag.
                              // 1 - Enable superres for the sequence, and also
                              //     enable per-frame flag to denote if superres is
                              //     enabled for that frame.
    pub enable_cdef: bool,         // To turn on/off CDEF
    pub enable_restoration: bool,  // To turn on/off loop restoration
    pub operating_points_cnt_minus_1: usize,
    pub operating_point_idc: [u16; MAX_NUM_OPERATING_POINTS],
    pub display_model_info_present_flag: bool,
    pub decoder_model_info_present_flag: bool,
    pub level: [[usize; 2]; MAX_NUM_OPERATING_POINTS],	// minor, major
    pub tier: [usize; MAX_NUM_OPERATING_POINTS],  // seq_tier in the spec. One bit: 0
                                                  // or 1.
    pub film_grain_params_present: bool,
    pub separate_uv_delta_q: bool,
}

impl Sequence {
289 290 291
    pub fn new(info: &FrameInfo) -> Sequence {
        let width_bits = 32 - (info.width as u32).leading_zeros();
        let height_bits = 32 - (info.height as u32).leading_zeros();
292 293 294
        assert!(width_bits <= 16);
        assert!(height_bits <= 16);

295
        let profile = if info.bit_depth == 12 {
296
            2
297
        } else if info.chroma_sampling == ChromaSampling::Cs444 {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            1
        } else {
            0
        };

        let mut operating_point_idc = [0 as u16; MAX_NUM_OPERATING_POINTS];
        let mut level = [[1, 2 as usize]; MAX_NUM_OPERATING_POINTS];
        let mut tier = [0 as usize; MAX_NUM_OPERATING_POINTS];

        for i in 0..MAX_NUM_OPERATING_POINTS {
            operating_point_idc[i] = 0;
            level[i][0] = 1;	// minor
            level[i][1] = 2;	// major
            tier[i] = 0;
        }

        Sequence {
            profile: profile,
            num_bits_width: width_bits,
            num_bits_height: height_bits,
318 319
            bit_depth: info.bit_depth,
            chroma_sampling: info.chroma_sampling,
320
            chroma_sample_position: info.chroma_sample_position,
321
            color_description: None,
322 323
            max_frame_width: info.width as u32,
            max_frame_height: info.height as u32,
324 325 326 327
            frame_id_numbers_present_flag: false,
            frame_id_length: 0,
            delta_frame_id_length: 0,
            use_128x128_superblock: false,
328
            order_hint_bits_minus_1: 5,
329 330 331 332 333
            force_screen_content_tools: 0,
            force_integer_mv: 2,
            still_picture: false,
            reduced_still_picture_hdr: false,
            monochrome: false,
Frank Bossen's avatar
Frank Bossen committed
334
            enable_intra_edge_filter: false,
335 336 337
            enable_interintra_compound: false,
            enable_masked_compound: false,
            enable_dual_filter: false,
fbossen's avatar
fbossen committed
338
            enable_order_hint: true,
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
            enable_jnt_comp: false,
            enable_ref_frame_mvs: false,
            enable_warped_motion: false,
            enable_superres: false,
            enable_cdef: true,
            enable_restoration: true,
            operating_points_cnt_minus_1: 0,
            operating_point_idc: operating_point_idc,
            display_model_info_present_flag: false,
            decoder_model_info_present_flag: false,
            level: level,
            tier: tier,
            film_grain_params_present: false,
            separate_uv_delta_q: false,
        }
    }
fbossen's avatar
fbossen committed
355 356 357 358 359 360

    pub fn get_relative_dist(&self, a: u32, b: u32) -> i32 {
        let diff = a as i32 - b as i32;
        let m = 1 << self.order_hint_bits_minus_1;
        (diff & (m - 1)) - (diff & m)
    }
fbossen's avatar
fbossen committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

    pub fn get_skip_mode_allowed(&self, fi: &FrameInvariants, reference_select: bool) -> bool {
      if fi.intra_only || !reference_select || !self.enable_order_hint {
        false
      } else {
        let mut forward_idx: isize = -1;
        let mut backward_idx: isize = -1;
        let mut forward_hint = 0;
        let mut backward_hint = 0;
        for i in 0..INTER_REFS_PER_FRAME {
          if let Some(ref rec) = fi.rec_buffer.frames[fi.ref_frames[i] as usize] {
            let ref_hint = rec.order_hint;
            if self.get_relative_dist(ref_hint, fi.order_hint) < 0 {
              if forward_idx < 0 || self.get_relative_dist(ref_hint, forward_hint) > 0 {
                forward_idx = i as isize;
                forward_hint = ref_hint;
              }
            } else if self.get_relative_dist(ref_hint, fi.order_hint) > 0 {
              if backward_idx < 0 || self.get_relative_dist(ref_hint, backward_hint) > 0 {
                backward_idx = i as isize;
                backward_hint = ref_hint;
              }
            }
          }
        }
        if forward_idx < 0 {
          false
        } else if backward_idx >= 0 {
          // set skip_mode_frame
          true
        } else {
          let mut second_forward_idx: isize = -1;
          let mut second_forward_hint = 0;
          for i in 0..INTER_REFS_PER_FRAME {
            if let Some(ref rec) = fi.rec_buffer.frames[fi.ref_frames[i] as usize] {
              let ref_hint = rec.order_hint;
              if self.get_relative_dist(ref_hint, forward_hint) < 0 {
                if second_forward_idx < 0 || self.get_relative_dist(ref_hint, second_forward_hint) > 0 {
                  second_forward_idx = i as isize;
                  second_forward_hint = ref_hint;
                }
              }
            }
          }
          if second_forward_idx < 0 {
            false
          } else {
            // set skip_mode_frame
            true
          }
        }
      }
    }
414 415 416 417
}

#[derive(Debug)]
pub struct FrameState {
Luca Barbato's avatar
Luca Barbato committed
418
    pub input: Arc<Frame>,
419 420
    pub input_hres: Plane, // half-resolution version of input luma
    pub input_qres: Plane, // quarter-resolution version of input luma
421 422
    pub rec: Frame,
    pub qc: QuantizationContext,
423
    pub cdfs: CDFContext,
424
    pub deblock: DeblockState,
425
    pub segmentation: SegmentationState,
426
    pub restoration: RestorationState,
427 428 429
}

impl FrameState {
430
    pub fn new(fi: &FrameInvariants) -> FrameState {
431
        FrameState::new_with_frame(fi, Arc::new(Frame::new(
432
            fi.padded_w, fi.padded_h, fi.sequence.chroma_sampling)))
433 434
    }

435
    pub fn new_with_frame(fi: &FrameInvariants, frame: Arc<Frame>) -> FrameState {
436
        let rs = RestorationState::new(fi, &frame);
437
        FrameState {
438 439 440 441 442 443 444 445 446 447 448
            input: frame,
            input_hres: Plane::new(
                fi.padded_w/2, fi.padded_h/2,
                1, 1,
                (MAX_SB_SIZE + FRAME_MARGIN) / 2, (MAX_SB_SIZE + FRAME_MARGIN) / 2
            ),
            input_qres: Plane::new(
                fi.padded_w/4, fi.padded_h/4,
                2, 2,
                (MAX_SB_SIZE + FRAME_MARGIN) / 4, (MAX_SB_SIZE + FRAME_MARGIN) / 4
            ),
449
            rec: Frame::new(fi.padded_w, fi.padded_h, fi.sequence.chroma_sampling),
450
            qc: Default::default(),
451
            cdfs: CDFContext::new(0),
452
            deblock: Default::default(),
453
            segmentation: Default::default(),
454
            restoration: rs,
455 456 457 458
        }
    }
}

459 460
#[derive(Copy, Clone, Debug)]
pub struct DeblockState {
461
    pub levels: [u8; PLANES+1],  // Y vertical edges, Y horizontal, U, V
462 463 464 465 466
    pub sharpness: u8,
    pub deltas_enabled: bool,
    pub delta_updates_enabled: bool,
    pub ref_deltas: [i8; REF_FRAMES],
    pub mode_deltas: [i8; 2],
467 468 469
    pub block_deltas_enabled: bool,
    pub block_delta_shift: u8,
    pub block_delta_multi: bool,
470 471 472 473 474
}

impl Default for DeblockState {
    fn default() -> Self {
        DeblockState {
475
            levels: [8,8,4,4],
476
            sharpness: 0,
477
            deltas_enabled: false, // requires delta_q_enabled
478 479
            delta_updates_enabled: false,
            ref_deltas: [1, 0, 0, 0, 0, -1, -1, -1],
480 481 482 483
            mode_deltas: [0, 0],
            block_deltas_enabled: false,
            block_delta_shift: 0,
            block_delta_multi: false
484 485 486 487
        }
    }
}

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
#[derive(Copy, Clone, Debug)]
pub struct SegmentationState {
    pub enabled: bool,
    pub update_data: bool,
    pub update_map: bool,
    pub preskip: bool,
    pub last_active_segid: u8,
    pub features: [[bool; SegLvl::SEG_LVL_MAX as usize]; 8],
    pub data: [[i16; SegLvl::SEG_LVL_MAX as usize]; 8],
}

impl Default for SegmentationState {
    fn default() -> Self {
        SegmentationState {
            enabled: false,
            update_data: false,
            update_map: false,
            preskip: true,
            last_active_segid: 0,
            features: [[false; SegLvl::SEG_LVL_MAX as usize]; 8],
            data: [[0; SegLvl::SEG_LVL_MAX as usize]; 8],
        }
    }
}

513 514
// Frame Invariants are invariant inside a frame
#[allow(dead_code)]
Josh Holmer's avatar
Josh Holmer committed
515
#[derive(Debug, Clone)]
516
pub struct FrameInvariants {
517
    pub sequence: Sequence,
518 519 520 521 522 523 524 525 526
    pub width: usize,
    pub height: usize,
    pub padded_w: usize,
    pub padded_h: usize,
    pub sb_width: usize,
    pub sb_height: usize,
    pub w_in_b: usize,
    pub h_in_b: usize,
    pub number: u64,
fbossen's avatar
fbossen committed
527
    pub order_hint: u32,
528 529 530 531 532 533 534
    pub show_frame: bool,
    pub showable_frame: bool,
    pub error_resilient: bool,
    pub intra_only: bool,
    pub allow_high_precision_mv: bool,
    pub frame_type: FrameType,
    pub show_existing_frame: bool,
fbossen's avatar
fbossen committed
535
    pub frame_to_show_map_idx: u32,
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    pub use_reduced_tx_set: bool,
    pub reference_mode: ReferenceMode,
    pub use_prev_frame_mvs: bool,
    pub min_partition_size: BlockSize,
    pub globalmv_transformation_type: [GlobalMVMode; ALTREF_FRAME + 1],
    pub num_tg: usize,
    pub large_scale_tile: bool,
    pub disable_cdf_update: bool,
    pub allow_screen_content_tools: u32,
    pub force_integer_mv: u32,
    pub primary_ref_frame: u32,
    pub refresh_frame_flags: u32,  // a bitmask that specifies which
    // reference frame slots will be updated with the current frame
    // after it is decoded.
    pub allow_intrabc: bool,
    pub use_ref_frame_mvs: bool,
    pub is_filter_switchable: bool,
    pub is_motion_mode_switchable: bool,
    pub disable_frame_end_update_cdf: bool,
    pub allow_warped_motion: bool,
    pub cdef_damping: u8,
    pub cdef_bits: u8,
    pub cdef_y_strengths: [u8; 8],
    pub cdef_uv_strengths: [u8; 8],
560
    pub delta_q_present: bool,
561
    pub config: EncoderConfig,
562
    pub ref_frames: [u8; INTER_REFS_PER_FRAME],
fbossen's avatar
fbossen committed
563
    pub ref_frame_sign_bias: [bool; INTER_REFS_PER_FRAME],
564
    pub rec_buffer: ReferenceFramesSet,
Frank Bossen's avatar
Frank Bossen committed
565
    pub base_q_idx: u8,
566 567
    pub dc_delta_q: [i8; 3],
    pub ac_delta_q: [i8; 3],
fbossen's avatar
fbossen committed
568
    pub me_range_scale: u8,
569
    pub use_tx_domain_distortion: bool,
Josh Holmer's avatar
Josh Holmer committed
570
    pub inter_cfg: Option<InterPropsConfig>,
571 572 573
}

impl FrameInvariants {
574 575
    pub fn new(width: usize, height: usize,
        config: EncoderConfig, sequence: Sequence) -> FrameInvariants {
576 577 578
        // Speed level decides the minimum partition size, i.e. higher speed --> larger min partition size,
        // with exception that SBs on right or bottom frame borders split down to BLOCK_4X4.
        // At speed = 0, RDO search is exhaustive.
579
        let mut min_partition_size = config.speed_settings.min_block_size;
580 581 582 583 584 585 586 587

        if config.tune == Tune::Psychovisual {
            if min_partition_size < BlockSize::BLOCK_8X8 {
                // TODO: Display message that min partition size is enforced to 8x8
                min_partition_size = BlockSize::BLOCK_8X8;
                println!("If tune=Psychovisual is used, min partition size is enforced to 8x8");
            }
        }
588 589
        let use_reduced_tx_set = config.speed_settings.reduced_tx_set;
        let use_tx_domain_distortion = config.tune == Tune::Psnr && config.speed_settings.tx_domain_distortion;
590 591

        FrameInvariants {
592
            sequence,
593 594 595 596 597 598 599 600 601
            width,
            height,
            padded_w: width.align_power_of_two(3),
            padded_h: height.align_power_of_two(3),
            sb_width: width.align_power_of_two_and_shift(6),
            sb_height: height.align_power_of_two_and_shift(6),
            w_in_b: 2 * width.align_power_of_two_and_shift(3), // MiCols, ((width+7)/8)<<3 >> MI_SIZE_LOG2
            h_in_b: 2 * height.align_power_of_two_and_shift(3), // MiRows, ((height+7)/8)<<3 >> MI_SIZE_LOG2
            number: 0,
fbossen's avatar
fbossen committed
602
            order_hint: 0,
603 604
            show_frame: true,
            showable_frame: true,
605
            error_resilient: false,
606
            intra_only: false,
607
            allow_high_precision_mv: false,
608 609
            frame_type: FrameType::KEY,
            show_existing_frame: false,
fbossen's avatar
fbossen committed
610
            frame_to_show_map_idx: 0,
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
            use_reduced_tx_set,
            reference_mode: ReferenceMode::SINGLE,
            use_prev_frame_mvs: false,
            min_partition_size,
            globalmv_transformation_type: [GlobalMVMode::IDENTITY; ALTREF_FRAME + 1],
            num_tg: 1,
            large_scale_tile: false,
            disable_cdf_update: false,
            allow_screen_content_tools: 0,
            force_integer_mv: 0,
            primary_ref_frame: PRIMARY_REF_NONE,
            refresh_frame_flags: 0,
            allow_intrabc: false,
            use_ref_frame_mvs: false,
            is_filter_switchable: false,
            is_motion_mode_switchable: false, // 0: only the SIMPLE motion mode will be used.
            disable_frame_end_update_cdf: false,
            allow_warped_motion: false,
            cdef_damping: 3,
            cdef_bits: 3,
            cdef_y_strengths: [0*4+0, 1*4+0, 2*4+1, 3*4+1, 5*4+2, 7*4+3, 10*4+3, 13*4+3],
            cdef_uv_strengths: [0*4+0, 1*4+0, 2*4+1, 3*4+1, 5*4+2, 7*4+3, 10*4+3, 13*4+3],
633
            delta_q_present: false,
634 635
            config,
            ref_frames: [0; INTER_REFS_PER_FRAME],
fbossen's avatar
fbossen committed
636
            ref_frame_sign_bias: [false; INTER_REFS_PER_FRAME],
637
            rec_buffer: ReferenceFramesSet::new(),
Frank Bossen's avatar
Frank Bossen committed
638
            base_q_idx: config.quantizer as u8,
639 640
            dc_delta_q: [0; 3],
            ac_delta_q: [0; 3],
fbossen's avatar
fbossen committed
641
            me_range_scale: 1,
642
            use_tx_domain_distortion: use_tx_domain_distortion,
Josh Holmer's avatar
Josh Holmer committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            inter_cfg: None,
        }
    }

  pub fn new_key_frame(previous_fi: &Self, segment_start_frame: u64) -> Self {
    let mut fi = previous_fi.clone();
    fi.frame_type = FrameType::KEY;
    fi.intra_only = true;
    fi.inter_cfg = None;
    fi.order_hint = 0;
    fi.refresh_frame_flags = ALL_REF_FRAMES_MASK;
    fi.show_frame = true;
    fi.show_existing_frame = false;
    fi.frame_to_show_map_idx = 0;
    let q_boost = 15;
    fi.base_q_idx = (fi.config.quantizer.max(1 + q_boost).min(255 + q_boost) - q_boost) as u8;
659
    fi.cdef_bits = 3;
Josh Holmer's avatar
Josh Holmer committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    fi.primary_ref_frame = PRIMARY_REF_NONE;
    fi.number = segment_start_frame;
    for i in 0..INTER_REFS_PER_FRAME {
      fi.ref_frames[i] = 0;
    }
    fi
  }

  fn apply_inter_props_cfg(&mut self, idx_in_segment: u64) {
    let reorder = !self.config.low_latency;
    let multiref = reorder || self.config.speed_settings.multiref;

    let pyramid_depth = if reorder { 2 } else { 0 };
    let group_src_len = 1 << pyramid_depth;
    let group_len = group_src_len + if reorder { pyramid_depth } else { 0 };

    let idx_in_group = (idx_in_segment - 1) % group_len;
    let group_idx = (idx_in_segment - 1) / group_len;

    self.inter_cfg = Some(InterPropsConfig {
      reorder,
      multiref,
      pyramid_depth,
      group_src_len,
      group_len,
      idx_in_group,
      group_idx,
    })
  }

  /// Returns the created FrameInvariants along with a bool indicating success.
  /// This interface provides simpler usage, because we always need the produced
  /// FrameInvariants regardless of success or failure.
693 694 695 696
  pub fn new_inter_frame(
    previous_fi: &Self, segment_start_frame: u64, idx_in_segment: u64,
    next_keyframe: u64
  ) -> (Self, bool) {
Josh Holmer's avatar
Josh Holmer committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    let mut fi = previous_fi.clone();
    fi.frame_type = FrameType::INTER;
    fi.intra_only = false;
    fi.apply_inter_props_cfg(idx_in_segment);
    let inter_cfg = fi.inter_cfg.unwrap();

    fi.order_hint = (inter_cfg.group_src_len * inter_cfg.group_idx +
      if inter_cfg.reorder && inter_cfg.idx_in_group < inter_cfg.pyramid_depth {
        inter_cfg.group_src_len >> inter_cfg.idx_in_group
      } else {
        inter_cfg.idx_in_group - inter_cfg.pyramid_depth + 1
      }) as u32;
    let number = segment_start_frame + fi.order_hint as u64;
    if number >= next_keyframe {
      fi.show_existing_frame = false;
      fi.show_frame = false;
      return (fi, false);
    }

    fn pos_to_lvl(pos: u64, pyramid_depth: u64) -> u64 {
      // Derive level within pyramid for a frame with a given coding order position
      // For example, with a pyramid of depth 2, the 2 least significant bits of the
      // position determine the level:
      // 00 -> 0
      // 01 -> 2
      // 10 -> 1
      // 11 -> 2
      pyramid_depth - (pos | (1 << pyramid_depth)).trailing_zeros() as u64
    }

    let lvl = if !inter_cfg.reorder {
      0
    } else if inter_cfg.idx_in_group < inter_cfg.pyramid_depth {
      inter_cfg.idx_in_group
    } else {
      pos_to_lvl(inter_cfg.idx_in_group - inter_cfg.pyramid_depth + 1, inter_cfg.pyramid_depth)
    };

    // Frames with lvl == 0 are stored in slots 0..4 and frames with higher values
    // of lvl in slots 4..8
    let slot_idx = if lvl == 0 {
      (fi.order_hint >> inter_cfg.pyramid_depth) % 4 as u32
    } else {
      3 + lvl as u32
    };
    fi.show_frame = !inter_cfg.reorder || inter_cfg.idx_in_group >= inter_cfg.pyramid_depth;
    fi.show_existing_frame = fi.show_frame && inter_cfg.reorder &&
      (inter_cfg.idx_in_group - inter_cfg.pyramid_depth + 1).count_ones() == 1 &&
      inter_cfg.idx_in_group != inter_cfg.pyramid_depth;
    fi.frame_to_show_map_idx = slot_idx;
    fi.refresh_frame_flags = if fi.show_existing_frame {
      0
    } else {
      1 << slot_idx
    };

    let q_drop = 15 * lvl as usize;
    fi.base_q_idx = (fi.config.quantizer.min(255 - q_drop) + q_drop) as u8;
755
    fi.cdef_bits = 3 - ((fi.base_q_idx.max(128) - 128) >> 5);
Josh Holmer's avatar
Josh Holmer committed
756 757 758 759 760 761 762 763 764 765
    let second_ref_frame = if !inter_cfg.multiref {
      NONE_FRAME
    } else if !inter_cfg.reorder || inter_cfg.idx_in_group == 0 {
      LAST2_FRAME
    } else {
      ALTREF_FRAME
    };
    let ref_in_previous_group = LAST3_FRAME;

    // reuse probability estimates from previous frames only in top level frames
766 767 768 769 770
    fi.primary_ref_frame = if lvl > 0 {
      PRIMARY_REF_NONE
    } else {
      (ref_in_previous_group - LAST_FRAME) as u32
    };
Josh Holmer's avatar
Josh Holmer committed
771 772 773 774 775 776 777

    for i in 0..INTER_REFS_PER_FRAME {
      fi.ref_frames[i] = if lvl == 0 {
        if i == second_ref_frame - LAST_FRAME {
          (slot_idx + 4 - 2) as u8 % 4
        } else {
          (slot_idx + 4 - 1) as u8 % 4
778
        }
Josh Holmer's avatar
Josh Holmer committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
      } else {
        if i == second_ref_frame - LAST_FRAME {
          let oh = fi.order_hint + (inter_cfg.group_src_len as u32 >> lvl);
          let lvl2 = pos_to_lvl(oh as u64, inter_cfg.pyramid_depth);
          if lvl2 == 0 {
            ((oh >> inter_cfg.pyramid_depth) % 4) as u8
          } else {
            3 + lvl2 as u8
          }
        } else if i == ref_in_previous_group - LAST_FRAME {
          if lvl == 0 {
            (slot_idx + 4 - 1) as u8 % 4
          } else {
            slot_idx as u8
          }
        } else {
          let oh = fi.order_hint - (inter_cfg.group_src_len as u32 >> lvl);
          let lvl1 = pos_to_lvl(oh as u64, inter_cfg.pyramid_depth);
          if lvl1 == 0 {
            ((oh >> inter_cfg.pyramid_depth) % 4) as u8
          } else {
            3 + lvl1 as u8
          }
        }
      }
804
    }
Josh Holmer's avatar
Josh Holmer committed
805 806 807 808 809 810 811 812 813 814

    fi.reference_mode = if inter_cfg.multiref && inter_cfg.reorder && inter_cfg.idx_in_group != 0 {
      ReferenceMode::SELECT
    } else {
      ReferenceMode::SINGLE
    };
    fi.number = number;
    fi.me_range_scale = (inter_cfg.group_src_len >> lvl) as u8;
    (fi, true)
  }
815 816
}

817
impl fmt::Display for FrameInvariants {
818 819 820 821 822
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Frame {} - {}", self.number, self.frame_type)
    }
}

Josh Holmer's avatar
Josh Holmer committed
823 824 825 826 827 828 829 830 831 832 833
#[derive(Debug, Clone, Copy)]
pub struct InterPropsConfig {
  pub reorder: bool,
  pub multiref: bool,
  pub pyramid_depth: u64,
  pub group_src_len: u64,
  pub group_len: u64,
  pub idx_in_group: u64,
  pub group_idx: u64,
}

834 835
#[allow(dead_code,non_camel_case_types)]
#[derive(Debug,PartialEq,Clone,Copy)]
836
#[repr(C)]
837 838 839 840 841 842 843 844 845 846
pub enum FrameType {
    KEY,
    INTER,
    INTRA_ONLY,
    SWITCH,
}

//const REFERENCE_MODES: usize = 3;

#[allow(dead_code,non_camel_case_types)]
Josh Holmer's avatar
Josh Holmer committed
847
#[derive(Debug, Clone, Copy, PartialEq)]
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
pub enum ReferenceMode {
  SINGLE = 0,
  COMPOUND = 1,
  SELECT = 2,
}

pub const ALL_REF_FRAMES_MASK: u32 = (1 << REF_FRAMES) - 1;

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

867 868 869 870
pub fn write_ivf_header(
  output_file: &mut dyn io::Write, width: usize, height: usize, num: usize,
  den: usize
) {
871
    let mut bw = BitWriter::endian(output_file, LittleEndian);
872 873 874 875 876 877 878 879 880 881 882 883 884
    bw.write_bytes(b"DKIF").unwrap();
    bw.write(16, 0).unwrap(); // version
    bw.write(16, 32).unwrap(); // version
    bw.write_bytes(b"AV01").unwrap();
    bw.write(16, width as u16).unwrap();
    bw.write(16, height as u16).unwrap();
    bw.write(32, num as u32).unwrap();
    bw.write(32, den as u32).unwrap();
    bw.write(32, 0).unwrap();
    bw.write(32, 0).unwrap();
}

pub fn write_ivf_frame(output_file: &mut dyn io::Write, pts: u64, data: &[u8]) {
885
    let mut bw = BitWriter::endian(output_file, LittleEndian);
886 887 888 889 890 891 892 893 894
    bw.write(32, data.len() as u32).unwrap();
    bw.write(64, pts).unwrap();
    bw.write_bytes(data).unwrap();
}

trait UncompressedHeader {
    // Start of OBU Headers
    fn write_obu_header(&mut self, obu_type: OBU_Type, obu_extension: u32)
            -> io::Result<()>;
895
    fn write_sequence_header_obu(&mut self, fi: &mut FrameInvariants)
896
            -> io::Result<()>;
897 898
    fn write_frame_header_obu(&mut self, fi: &FrameInvariants, fs: &FrameState)
          -> io::Result<()>;
899
    fn write_sequence_header(&mut self, fi: &mut FrameInvariants)
900 901 902 903 904
                                    -> io::Result<()>;
    fn write_color_config(&mut self, seq: &mut Sequence) -> io::Result<()>;
    // End of OBU Headers

    fn write_frame_size(&mut self, fi: &FrameInvariants) -> io::Result<()>;
905 906
    fn write_deblock_filter_a(&mut self, fi: &FrameInvariants, deblock: &DeblockState) -> io::Result<()>;
    fn write_deblock_filter_b(&mut self, fi: &FrameInvariants, deblock: &DeblockState) -> io::Result<()>;
907 908
    fn write_frame_cdef(&mut self, fi: &FrameInvariants) -> io::Result<()>;
    fn write_frame_lrf(&mut self, fi: &FrameInvariants, rs: &RestorationState) -> io::Result<()>;
909
    fn write_segment_data(&mut self, fi: &FrameInvariants, segmentation: &SegmentationState) -> io::Result<()>;
910
    fn write_delta_q(&mut self, delta_q: i8) -> io::Result<()>;
911 912 913 914 915 916 917 918 919 920 921 922 923 924
}
#[allow(unused)]
const OP_POINTS_IDC_BITS:usize = 12;
#[allow(unused)]
const LEVEL_MAJOR_MIN:usize = 2;
#[allow(unused)]
const LEVEL_MAJOR_BITS:usize = 3;
#[allow(unused)]
const LEVEL_MINOR_BITS:usize = 2;
#[allow(unused)]
const LEVEL_BITS:usize = LEVEL_MAJOR_BITS + LEVEL_MINOR_BITS;
const FRAME_ID_LENGTH: usize = 15;
const DELTA_FRAME_ID_LENGTH: usize = 14;

925
impl<W: io::Write> UncompressedHeader for BitWriter<W, BigEndian> {
926 927 928 929 930 931 932 933 934 935 936
    // Start of OBU Headers
    // Write OBU Header syntax
    fn write_obu_header(&mut self, obu_type: OBU_Type, obu_extension: u32)
            -> io::Result<()>{
        self.write_bit(false)?; // forbidden bit.
        self.write(4, obu_type as u32)?;
        self.write_bit(obu_extension != 0)?;
        self.write_bit(true)?; // obu_has_payload_length_field
        self.write_bit(false)?; // reserved

        if obu_extension != 0 {
Raphaël Zumer's avatar
Raphaël Zumer committed
937
            unimplemented!();
938 939 940 941 942 943
            //self.write(8, obu_extension & 0xFF)?; size += 8;
        }

        Ok(())
    }

944
    fn write_sequence_header_obu(&mut self, fi: &mut FrameInvariants)
945
        -> io::Result<()> {
946
        self.write(3, fi.sequence.profile)?; // profile, 3 bits
947 948 949 950 951 952 953 954
        self.write(1, 0)?; // still_picture
        self.write(1, 0)?; // reduced_still_picture
        self.write_bit(false)?; // display model present
        self.write_bit(false)?; // no timing info present
        self.write(5, 0)?; // one operating point
        self.write(12,0)?; // idc
        self.write(5, 31)?; // level
        self.write(1, 0)?; // tier
955
        if fi.sequence.reduced_still_picture_hdr {
Raphaël Zumer's avatar
Raphaël Zumer committed
956
            unimplemented!();
957 958
        }

959
        self.write_sequence_header(fi)?;
960

961
        self.write_color_config(&mut fi.sequence)?;
962

963
        self.write_bit(fi.sequence.film_grain_params_present)?;
964

965
        self.write_bit(true)?; // trailing bit
966 967 968 969

        Ok(())
    }

970
    fn write_sequence_header(&mut self, fi: &mut FrameInvariants)
971 972 973
        -> io::Result<()> {
        self.write_frame_size(fi)?;

974 975
        let seq = &mut fi.sequence;

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        if !seq.reduced_still_picture_hdr {
            seq.frame_id_numbers_present_flag = false;
            seq.frame_id_length = FRAME_ID_LENGTH as u32;
            seq.delta_frame_id_length = DELTA_FRAME_ID_LENGTH as u32;

            self.write_bit(seq.frame_id_numbers_present_flag)?;

            if seq.frame_id_numbers_present_flag {
              // We must always have delta_frame_id_length < frame_id_length,
              // in order for a frame to be referenced with a unique delta.
              // Avoid wasting bits by using a coding that enforces this restriction.
              self.write(4, seq.delta_frame_id_length - 2)?;
              self.write(3, seq.frame_id_length - seq.delta_frame_id_length - 1)?;
            }
        }

        self.write_bit(seq.use_128x128_superblock)?;
993
        self.write_bit(true)?; // enable filter intra
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 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 1036 1037
        self.write_bit(seq.enable_intra_edge_filter)?;

        if !seq.reduced_still_picture_hdr {
            self.write_bit(seq.enable_interintra_compound)?;
            self.write_bit(seq.enable_masked_compound)?;
            self.write_bit(seq.enable_warped_motion)?;
            self.write_bit(seq.enable_dual_filter)?;
            self.write_bit(seq.enable_order_hint)?;

            if seq.enable_order_hint {
              self.write_bit(seq.enable_jnt_comp)?;
              self.write_bit(seq.enable_ref_frame_mvs)?;
            }
            if seq.force_screen_content_tools == 2 {
              self.write_bit(true)?;
            } else {
              self.write_bit(false)?;
              self.write_bit(seq.force_screen_content_tools != 0)?;
            }
            if seq.force_screen_content_tools > 0 {
              if seq.force_integer_mv == 2 {
                self.write_bit(true)?;
              } else {
                self.write_bit(false)?;
                self.write_bit(seq.force_integer_mv != 0)?;
              }
            } else {
              assert!(seq.force_integer_mv == 2);
            }
            if seq.enable_order_hint {
              self.write(3, seq.order_hint_bits_minus_1)?;
            }
        }

        self.write_bit(seq.enable_superres)?;
        self.write_bit(seq.enable_cdef)?;
        self.write_bit(seq.enable_restoration)?;

        Ok(())
    }

    fn write_color_config(&mut self, seq: &mut Sequence) -> io::Result<()> {
        let high_bd = seq.bit_depth > 8;

Raphaël Zumer's avatar
Raphaël Zumer committed
1038
        self.write_bit(high_bd)?;
1039 1040

        if seq.bit_depth == 12 {
Raphaël Zumer's avatar
Raphaël Zumer committed
1041
            self.write_bit(true)?;
1042 1043 1044
        }

        if seq.profile != 1 {
Raphaël Zumer's avatar
Raphaël Zumer committed
1045
            self.write_bit(seq.monochrome)?;
1046 1047 1048
        }

        if seq.monochrome {
Raphaël Zumer's avatar
Raphaël Zumer committed
1049
            unimplemented!();
1050 1051
        }

1052 1053 1054 1055 1056 1057 1058 1059 1060
        if let Some(color_description) = seq.color_description {
            self.write_bit(true)?; // color description present
            self.write(8, color_description.color_primaries as u8)?;
            self.write(8, color_description.transfer_characteristics as u8)?;
            self.write(8, color_description.matrix_coefficients as u8)?;
        } else {
            self.write_bit(false)?; // no color description present
        }

Raphaël Zumer's avatar
Raphaël Zumer committed
1061
        self.write_bit(false)?; // full color range
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

        let subsampling_x = seq.chroma_sampling != ChromaSampling::Cs444;
        let subsampling_y = seq.chroma_sampling == ChromaSampling::Cs420;

        if seq.bit_depth == 12 {
            self.write_bit(subsampling_x)?;

            if subsampling_x {
                self.write_bit(subsampling_y)?;
            }
        }

        if !subsampling_y {
            unimplemented!(); // 4:2:2 or 4:4:4 sampling
        }

1078
        self.write(2, seq.chroma_sample_position as u32)?;
1079

1080
        self.write_bit(seq.separate_uv_delta_q)?;
1081 1082 1083 1084 1085

        Ok(())
    }

#[allow(unused)]
1086
    fn write_frame_header_obu(&mut self, fi: &FrameInvariants, fs: &FrameState)
1087
        -> io::Result<()> {
1088
      if fi.sequence.reduced_still_picture_hdr {
1089 1090 1091 1092
        assert!(fi.show_existing_frame);
        assert!(fi.frame_type == FrameType::KEY);
        assert!(fi.show_frame);
      } else {
Raphaël Zumer's avatar
Raphaël Zumer committed
1093 1094
        self.write_bit(fi.show_existing_frame)?;

1095
        if fi.show_existing_frame {
fbossen's avatar
fbossen committed
1096
          self.write(3, fi.frame_to_show_map_idx)?;
1097 1098 1099

          //TODO:
          /* temporal_point_info();
1100
            if fi.sequence.decoder_model_info_present_flag &&
1101 1102 1103
              timing_info.equal_picture_interval == 0 {
            // write frame_presentation_delay;
          }
1104
          if fi.sequence.frame_id_numbers_present_flag {
1105 1106 1107
            // write display_frame_id;
          }*/

fbossen's avatar
fbossen committed
1108
          self.write_bit(true)?; // trailing bit
1109
          self.byte_align()?;
1110
          return Ok(());
1111
        }
Raphaël Zumer's avatar
Raphaël Zumer committed
1112

1113 1114 1115 1116 1117 1118
        self.write(2, fi.frame_type as u32)?;
        self.write_bit(fi.show_frame)?; // show frame

        if fi.show_frame {
          //TODO:
          /* temporal_point_info();
1119
              if fi.sequence.decoder_model_info_present_flag &&
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
              timing_info.equal_picture_interval == 0 {
            // write frame_presentation_delay;*/
        } else {
          self.write_bit(fi.showable_frame)?;
        }

        if fi.frame_type == FrameType::SWITCH {
          assert!(fi.error_resilient);
        } else {
          if !(fi.frame_type == FrameType::KEY && fi.show_frame) {
            self.write_bit(fi.error_resilient)?; // error resilient
          }
        }
      }

      self.write_bit(fi.disable_cdf_update)?;

1137
      if fi.sequence.force_screen_content_tools == 2 {
1138 1139 1140
        self.write_bit(fi.allow_screen_content_tools != 0)?;
      } else {
        assert!(fi.allow_screen_content_tools ==
1141
                fi.sequence.force_screen_content_tools);
1142 1143 1144
      }

      if fi.allow_screen_content_tools == 2 {
1145
        if fi.sequence.force_integer_mv == 2 {
1146 1147
          self.write_bit(fi.force_integer_mv != 0)?;
        } else {
1148
          assert!(fi.force_integer_mv == fi.sequence.force_integer_mv);
1149 1150 1151
        }
      } else {
        assert!(fi.allow_screen_content_tools ==
1152
                fi.sequence.force_screen_content_tools);
1153 1154
      }

1155
      if fi.sequence.frame_id_numbers_present_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1156 1157
        unimplemented!();

1158
        //TODO:
1159
        //let frame_id_len = fi.sequence.frame_id_length;
1160 1161 1162 1163 1164 1165
        //self.write(frame_id_len, fi.current_frame_id);
      }

      let mut frame_size_override_flag = false;
      if fi.frame_type == FrameType::SWITCH {
        frame_size_override_flag = true;
1166
      } else if fi.sequence.reduced_still_picture_hdr {
1167 1168 1169 1170 1171
        frame_size_override_flag = false;
      } else {
        self.write_bit(frame_size_override_flag)?; // frame size overhead flag
      }

1172 1173
      if fi.sequence.enable_order_hint {
        let n = fi.sequence.order_hint_bits_minus_1 + 1;
fbossen's avatar
fbossen committed
1174 1175
        let mask = (1 << n) - 1;
        self.write(n, fi.order_hint & mask)?;
1176
      }
fbossen's avatar
fbossen committed
1177

1178 1179 1180 1181 1182
      if fi.error_resilient || fi.intra_only {
      } else {
        self.write(PRIMARY_REF_BITS, fi.primary_ref_frame)?;
      }

1183
      if fi.sequence.decoder_model_info_present_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1184
        unimplemented!();
1185 1186 1187 1188
      }

      if fi.frame_type == FrameType::KEY {
        if !fi.show_frame {  // unshown keyframe (forward keyframe)
Raphaël Zumer's avatar
Raphaël Zumer committed
1189
          unimplemented!();
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
          self.write(REF_FRAMES as u32, fi.refresh_frame_flags)?;
        } else {
          assert!(fi.refresh_frame_flags == ALL_REF_FRAMES_MASK);
        }
      } else { // Inter frame info goes here
        if fi.intra_only {
          assert!(fi.refresh_frame_flags != ALL_REF_FRAMES_MASK);
          self.write(REF_FRAMES as u32, fi.refresh_frame_flags)?;
        } else {
          // TODO: This should be set once inter mode is used
          self.write(REF_FRAMES as u32, fi.refresh_frame_flags)?;
        }

      };

      if (!fi.intra_only || fi.refresh_frame_flags != ALL_REF_FRAMES_MASK) {
        // Write all ref frame order hints if error_resilient_mode == 1
1207
        if (fi.error_resilient && fi.sequence.enable_order_hint) {
Raphaël Zumer's avatar
Raphaël Zumer committed
1208
          unimplemented!();
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
          //for _ in 0..REF_FRAMES {
          //  self.write(order_hint_bits_minus_1,ref_order_hint[i])?; // order_hint
          //}
        }
      }

      // if KEY or INTRA_ONLY frame
      // FIXME: Not sure whether putting frame/render size here is good idea
      if fi.intra_only {
        if frame_size_override_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1219
          unimplemented!();
1220
        }
1221
        if fi.sequence.enable_superres {
Raphaël Zumer's avatar
Raphaël Zumer committed
1222
          unimplemented!();
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
        }
        self.write_bit(false)?; // render_and_frame_size_different
        //if render_and_frame_size_different { }
        if fi.allow_screen_content_tools != 0 && true /* UpscaledWidth == FrameWidth */ {
          self.write_bit(fi.allow_intrabc)?;
        }
      }

      let frame_refs_short_signaling = false;
      if fi.frame_type == FrameType::KEY {
        // Done by above
      } else {
        if fi.intra_only {
          // Done by above
        } else {
1238
          if fi.sequence.enable_order_hint {
1239 1240
            self.write_bit(frame_refs_short_signaling)?;
            if frame_refs_short_signaling {
Raphaël Zumer's avatar
Raphaël Zumer committed
1241
              unimplemented!();
1242 1243 1244
            }
          }

1245
          for i in 0..INTER_REFS_PER_FRAME {
1246 1247 1248
            if !frame_refs_short_signaling {
              self.write(REF_FRAMES_LOG2 as u32, fi.ref_frames[i] as u8)?;
            }
1249
            if fi.sequence.frame_id_numbers_present_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1250
              unimplemented!();
1251 1252 1253
            }
          }
          if fi.error_resilient && frame_size_override_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1254
            unimplemented!();
1255 1256
          } else {
            if frame_size_override_flag {
Raphaël Zumer's avatar
Raphaël Zumer committed
1257
               unimplemented!();
1258
            }
1259
            if fi.sequence.enable_superres {
Raphaël Zumer's avatar
Raphaël Zumer committed
1260
              unimplemented!();
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
            }
            self.write_bit(false)?; // render_and_frame_size_different
          }
          if fi.force_integer_mv != 0 {
          } else {
            self.write_bit(fi.allow_high_precision_mv);
          }
          self.write_bit(fi.is_filter_switchable)?;
          self.write_bit(fi.is_motion_mode_switchable)?;
          self.write(2,0)?; // EIGHTTAP_REGULAR
1271
          if fi.error_resilient || !fi.sequence.enable_ref_frame_mvs {
1272 1273 1274 1275 1276 1277
          } else {
            self.write_bit(fi.use_ref_frame_mvs)?;
          }
        }
      }

1278
      if !fi.sequence.reduced_still_picture_hdr && !fi.disable_cdf_update {
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
        self.write_bit(fi.disable_frame_end_update_cdf)?;
      }

      // tile
      self.write_bit(true)?; // uniform_tile_spacing_flag
      if fi.width > 64 {
        // TODO: if tile_cols > 1, write more increment_tile_cols_log2 bits
        self.write_bit(false)?; // tile cols
      }
      if fi.height > 64 {
        // TODO: if tile_rows > 1, write increment_tile_rows_log2 bits
        self.write_bit(false)?; // tile rows
      }
      // TODO: if tile_cols * tile_rows > 1 {
      // write context_update_tile_id and tile_size_bytes_minus_1 }

      // quantization
Frank Bossen's avatar
Frank Bossen committed
1296 1297
      assert!(fi.base_q_idx > 0);
      self.write(8, fi.base_q_idx)?; // base_q_idx
1298 1299
      self.write_delta_q(fi.dc_delta_q[0])?;
      assert!(fi.ac_delta_q[0] == 0);
1300
      let diff_uv_delta = fi.sequence.separate_uv_delta_q
1301 1302
        && (fi.dc_delta_q[1] != fi.dc_delta_q[2]
          || fi.ac_delta_q[1] != fi.ac_delta_q[2]);
1303
      if fi.sequence.separate_uv_delta_q {
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
        self.write_bit(diff_uv_delta)?;
      } else {
        assert!(fi.dc_delta_q[1] == fi.dc_delta_q[2]);
        assert!(fi.ac_delta_q[1] == fi.ac_delta_q[2]);
      }
      self.write_delta_q(fi.dc_delta_q[1])?;
      self.write_delta_q(fi.ac_delta_q[1])?;
      if diff_uv_delta {
        self.write_delta_q(fi.dc_delta_q[2])?;
        self.write_delta_q(fi.ac_delta_q[2])?;
      }
1315 1316 1317
      self.write_bit(false)?; // no qm

      // segmentation
1318
      self.write_segment_data(fi, &fs.segmentation)?;
1319 1320 1321 1322

      // delta_q
      self.write_bit(false)?; // delta_q_present_flag: no delta q

1323
      // delta_lf_params in the spec
1324
      self.write_deblock_filter_a(fi, &fs.deblock)?;
1325 1326 1327 1328

      // code for features not yet implemented....

      // loop_filter_params in the spec
1329
      self.write_deblock_filter_b(fi, &fs.deblock)?;
1330

1331
      // cdef
1332
      self.write_frame_cdef(fi)?;
1333

1334
      // loop restoration
1335
      self.write_frame_lrf(fi, &fs.restoration)?;
1336

1337 1338 1339 1340 1341 1342 1343 1344
      self.write_bit(false)?; // tx mode == TX_MODE_SELECT ?

      let mut reference_select = false;
      if !fi.intra_only {
        reference_select = fi.reference_mode != ReferenceMode::SINGLE;
        self.write_bit(reference_select)?;
      }

1345
      let skip_mode_allowed = fi.sequence.get_skip_mode_allowed(fi, reference_select);
1346 1347 1348 1349
      if skip_mode_allowed {
        self.write_bit(false)?; // skip_mode_present
      }

1350
      if fi.intra_only || fi.error_resilient || !fi.sequence.enable_warped_motion {
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
      } else {
        self.write_bit(fi.allow_warped_motion)?; // allow_warped_motion
      }

      self.write_bit(fi.use_reduced_tx_set)?; // reduced tx

      // global motion
      if !fi.intra_only {
          for i in LAST_FRAME..ALTREF_FRAME+1 {
              let mode = fi.globalmv_transformation_type[i];
              self.write_bit(mode != GlobalMVMode::IDENTITY)?;
              if mode != GlobalMVMode::IDENTITY {
                  self.write_bit(mode == GlobalMVMode::ROTZOOM)?;
                  if mode != GlobalMVMode::ROTZOOM {
                      self.write_bit(mode == GlobalMVMode::TRANSLATION)?;
                  }
              }
              match mode {
                  GlobalMVMode::IDENTITY => { /* Nothing to do */ }
                  GlobalMVMode::TRANSLATION => {
                      let mv_x = 0;
                      let mv_x_ref = 0;
                      let mv_y = 0;
                      let mv_y_ref = 0;
                      let bits = 12 - 6 + 3 - !fi.allow_high_precision_mv as u8;
                      let bits_diff = 12 - 3 + fi.allow_high_precision_mv as u8;
                      BCodeWriter::write_s_refsubexpfin(self, (1 << bits) + 1,
                                                        3, mv_x_ref >> bits_diff,
                                                        mv_x >> bits_diff)?;
                      BCodeWriter::write_s_refsubexpfin(self, (1 << bits) + 1,
                                                        3, mv_y_ref >> bits_diff,
                                                        mv_y >> bits_diff)?;
                  }
                  GlobalMVMode::ROTZOOM => unimplemented!(),
                  GlobalMVMode::AFFINE => unimplemented!(),
              };
          }
      }

1390
      if fi.sequence.film_grain_params_present && fi.show_frame {
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
          unimplemented!();
      }

      if fi.large_scale_tile {
          unimplemented!();
      }
      self.write_bit(true)?; // trailing bit
      self.byte_align()?;

      Ok(())
    }
    // End of OBU Headers

    fn write_frame_size(&mut self, fi: &FrameInvariants) -> io::Result<()> {
        // width_bits and height_bits will have to be moved to the sequence header OBU
        // when we add support for it.
        let width_bits = 32 - (fi.width as u32).leading_zeros();
        let height_bits = 32 - (fi.height as u32).leading_zeros();
        assert!(width_bits <= 16);
        assert!(height_bits <= 16);
        self.write(4, width_bits - 1)?;
        self.write(4, height_bits - 1)?;
        self.write(width_bits, (fi.width - 1) as u16)?;
        self.write(height_bits, (fi.height - 1) as u16)?;
        Ok(())
    }

1418
    fn write_deblock_filter_a(&mut self, fi: &FrameInvariants, deblock: &DeblockState) -> io::Result<()> {
1419 1420
        if fi.delta_q_present {
            if !fi.allow_intrabc {
1421
                self.write_bit(deblock.block_deltas_enabled)?;
1422
            }
1423 1424 1425
            if deblock.block_deltas_enabled {
                self.write(2, deblock.block_delta_shift)?;
                self.write_bit(deblock.block_delta_multi)?;