diff --git a/Cargo.lock b/Cargo.lock index 7759b5d2..6eaee184 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -494,6 +494,14 @@ dependencies = [ "ec-core", ] +[[package]] +name = "ec-vp9" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-vp9-syntax", +] + [[package]] name = "ec-vp9-syntax" version = "0.1.0" diff --git a/crates/ec-vp9/Cargo.toml b/crates/ec-vp9/Cargo.toml new file mode 100644 index 00000000..7f433962 --- /dev/null +++ b/crates/ec-vp9/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "ec-vp9" +description = "Native VP9 decoder — key-frame decoding of the full format, byte-exact against libvpx/ffmpeg." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true +ec-vp9-syntax.workspace = true diff --git a/crates/ec-vp9/src/bool.rs b/crates/ec-vp9/src/bool.rs new file mode 100644 index 00000000..ff14629d --- /dev/null +++ b/crates/ec-vp9/src/bool.rs @@ -0,0 +1,395 @@ +//! The bool decoder (spec 8.3.2), VP9's arithmetic range coder over one +//! data partition (the compressed header, and each tile of tile data). +//! +//! Every syntax element below the uncompressed header is coded as a +//! sequence of bools, each written at an 8-bit zero-probability `p` +//! (meaning `p/256`). The decoder mirrors the encoder's interval state +//! with two numbers — `range` (128..=255) and `value` (the encoded +//! number minus the interval's left endpoint) — and renormalises one +//! bit at a time, shifting a fresh input byte into `value` for every 8 +//! bits consumed (spec 8.3.2, `read_bool` / libvpx `vpx_reader`). +//! +//! The tests drive the decoder against a test-only implementation of the +//! spec's reference encoder (8.3.3, the carry-propagating writer) and +//! assert bit-exact round-trips. + +use ec_core::Result; + +/// Boolean arithmetic decoder over one data partition (spec 8.3.2). +pub struct BoolDecoder<'a> { + data: &'a [u8], + /// Index of the next byte to shift into `value`. + pos: usize, + /// 128..=255; identical to the encoder's range. + range: u32, + /// Encoded number minus the current interval's left endpoint; the top + /// bits hold what has been read, bytes shift in at the bottom. + value: u32, + /// Bits shifted out of `value` since the last byte was shifted in. + bit_count: u32, + /// Bytes consumed past the end of the partition (read as 0, per the + /// spec's zero-extension of x). A healthy partition stays at 0. + overreads: u32, +} + +impl<'a> BoolDecoder<'a> { + /// Start decoding the partition `data` (spec 8.3.2 `init_bool`): the + /// first two bytes are read into `value`, big-endian. A partition + /// shorter than two bytes is zero-extended like the reference + /// decoder does, and the shortfall shows up in [`Self::overreads`]. + pub fn new(data: &'a [u8]) -> Result { + if data.is_empty() { + return Ok(Self { + data, + pos: 0, + range: 255, + value: 0, + bit_count: 0, + overreads: 0, + }); + } + let mut value = u32::from(data[0]) << 8; + if data.len() > 1 { + value |= u32::from(data[1]); + } + Ok(Self { + data, + pos: data.len().min(2), + range: 255, + value, + bit_count: 0, + overreads: 0, + }) + } + + /// Bytes consumed past the end of the partition, read as zero. Any + /// non-zero value on a complete, valid partition is a desync symptom. + pub fn overreads(&self) -> u32 { + self.overreads + } + + /// Offset of the next unread input byte, for desync diagnostics. + pub fn byte_offset(&self) -> usize { + self.pos + } + + fn next_byte(&mut self) -> u32 { + match self.data.get(self.pos) { + Some(&b) => { + self.pos += 1; + u32::from(b) + } + None => { + self.overreads += 1; + 0 + } + } + } + + /// Decode one bool whose zero-probability is `prob`/256 (spec 8.3.2 + /// `read_bool`; libvpx `vpx_read`). Under `EC_VP9_TRACE`, prints the + /// decoder state after the read — `B `. + pub fn read_bool(&mut self, prob: u8) -> bool { + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + let bigsplit = split << 8; + let bit = if self.value >= bigsplit { + self.range -= split; + self.value -= bigsplit; + true + } else { + self.range = split; + false + }; + while self.range < 128 { + self.value <<= 1; + self.range <<= 1; + self.bit_count += 1; + if self.bit_count == 8 { + self.bit_count = 0; + self.value |= self.next_byte(); + } + } + if crate::trace_enabled() { + eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit)); + } + bit + } + + /// Unsigned `n`-bit literal, bits high- to low-order, each at + /// probability 128 (spec `read_literal`). + pub fn read_literal(&mut self, n: u32) -> u32 { + let mut v = 0; + for _ in 0..n { + v = (v << 1) + u32::from(self.read_bool(128)); + } + v + } + + /// Signed `n`-bit literal (spec `s(n)`, 4.10): an `n`-bit magnitude + /// followed by a sign flag, 1 meaning negative. `n = 0` yields 0. + pub fn read_signed_literal(&mut self, n: u32) -> i32 { + if n == 0 { + return 0; + } + let mut v: i32 = self.read_literal(n) as i32; + if self.read_bool(128) { + v = -v; + } + v + } + + /// Decode a tree-coded value (spec 8.3.2 `read_tree`; libvpx + /// `vpx_read_tree`): `tree` holds the left/right branch entries + /// (positive = interior node index, negative = `-leaf`), `probs[i]` + /// is the probability of interior node `i` (the tree position + /// halved). + pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 { + let mut i: i32 = 0; + loop { + let b = self.read_bool(probs[(i >> 1) as usize]); + i = i32::from(tree[(i + i32::from(b as i8)) as usize]); + if i <= 0 { + return (-i) as u8; + } + } + } +} + +/// The spec 8.3.3 reference bool encoder (the carry-propagating writer +/// libvpx ships as `vpx_writer`), test-only: it lets the tests drive +/// [`BoolDecoder`] against known bitstreams instead of trusting the +/// decoder to decode its own idea of the format. +#[cfg(test)] +struct BoolEncoder { + out: Vec, + range: u32, + bottom: u32, + bit_count: u32, +} + +#[cfg(test)] +impl BoolEncoder { + fn new() -> Self { + Self { + out: Vec::new(), + range: 255, + bottom: 0, + bit_count: 24, + } + } + + fn add_one_to_output(out: &mut [u8]) { + for b in out.iter_mut().rev() { + if *b == 255 { + *b = 0; + } else { + *b += 1; + return; + } + } + // Carry out of the beginning cannot happen: x < 1 always. + unreachable!("bool encoder carry propagated past the first byte"); + } + + fn write_bool(&mut self, val: bool, prob: u8) { + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + if val { + self.bottom += split; + self.range -= split; + } else { + self.range = split; + } + while self.range < 128 { + self.range <<= 1; + if self.bottom & (1 << 31) != 0 { + Self::add_one_to_output(&mut self.out); + } + self.bottom <<= 1; + self.bit_count -= 1; + if self.bit_count == 0 { + self.out.push((self.bottom >> 24) as u8); + self.bottom &= (1 << 24) - 1; + self.bit_count = 8; + } + } + } + + fn write_literal(&mut self, v: u32, n: u32) { + for i in (0..n).rev() { + self.write_bool((v >> i) & 1 != 0, 128); + } + } + + /// Spec `flush_bool_encoder`. + fn flush(mut self) -> Vec { + let c = self.bit_count; + let mut v = self.bottom; + if v & (1 << (32 - c)) != 0 { + Self::add_one_to_output(&mut self.out); + } + v <<= c & 7; + let mut c = c >> 3; + while c > 0 { + v <<= 8; + c -= 1; + } + for _ in 0..4 { + self.out.push((v >> 24) as u8); + v <<= 8; + } + self.out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip_bools(pattern: &[(&[bool], u8)]) { + let mut e = BoolEncoder::new(); + for (vals, p) in pattern { + for &v in *vals { + e.write_bool(v, *p); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (vals, p) in pattern { + for &v in *vals { + assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p); + } + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_bools_at_every_extreme() { + // p = 1 (all zeros essentially free) through p = 255, with 1s at + // the most improbable settings to force carry propagation. + roundtrip_bools(&[ + (&[false; 64], 1), + (&[true], 1), + (&[false, true, false, true], 128), + (&[true; 3], 255), + (&[false; 32], 255), + (&[true; 16], 1), + ]); + } + + #[test] + fn roundtrips_long_random_streams() { + // Deterministic LCG so failures reproduce. + let mut state: u64 = 0x9E3779B97F4A7C15; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let probs = [1u8, 2, 32, 128, 200, 254, 255]; + let mut e = BoolEncoder::new(); + let mut expected = Vec::new(); + for &p in &probs { + for _ in 0..200 { + let v = next() & 1 == 1; + e.write_bool(v, p); + expected.push((v, p)); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (v, p) in expected { + assert_eq!(d.read_bool(p), v); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_literals() { + let mut e = BoolEncoder::new(); + for n in 1..=19u32 { + let ones = (1 << n) - 1; + e.write_literal(ones, n); + e.write_literal(0, n); + e.write_literal(0x15 & ones, n); // 0b10101 truncated + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for n in 1..=19u32 { + let ones = (1 << n) - 1; + assert_eq!(d.read_literal(n), ones); + assert_eq!(d.read_literal(n), 0); + assert_eq!(d.read_literal(n), 0x15 & ones); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_signed_literals() { + // Spec s(5): 5-bit magnitude then sign flag. + let mut e = BoolEncoder::new(); + for mag in 0..=15u32 { + e.write_literal(mag, 4); + e.write_bool(false, 128); + e.write_literal(mag, 4); + e.write_bool(true, 128); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for mag in 0..=15i32 { + assert_eq!(d.read_signed_literal(4), mag); + assert_eq!(d.read_signed_literal(4), -mag); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_tree_values() { + // The spec's intra mode tree (8.2 `read_intra_mode`). + let intra: [i8; 18] = [ + -0, 2, -9, 4, -1, 6, 8, 12, -2, 10, -5, -6, -3, 14, -7, 16, -8, -4, + ]; + let probs = [159u8; 9]; + // Bit paths per the tree above: DC="0", TM="100", V="101", + // H="1100 00"? — walk a few leaves via the decoder itself, then + // verify against the encoder paths. + let leaves: [(&[bool], u8); 4] = [ + (&[false], 0), + (&[true, false], 9), + (&[true, true, false], 1), + (&[true, true, true, false, false, false], 2), + ]; + for (path, val) in leaves { + let mut e = BoolEncoder::new(); + for (i, &b) in path.iter().enumerate() { + e.write_bool(b, probs[(i + i) >> 1]); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + assert_eq!(d.read_tree(&intra, &probs), val, "path {path:?}"); + } + } + + #[test] + fn short_partitions_zero_extend() { + // An empty partition is legal (a degenerate tile); init reads + // zeros and the shortfall shows in overreads. + let mut d = BoolDecoder::new(&[]).unwrap(); + assert_eq!(d.read_bool(128), false); + let mut d = BoolDecoder::new(&[0]).unwrap(); + assert_eq!(d.read_bool(128), false); + } + + #[test] + fn overreads_are_counted_not_panicked() { + // Two bytes of init, then nothing: any read shifts in zeros. + let data = [0u8, 0]; + let mut d = BoolDecoder::new(&data).unwrap(); + for _ in 0..100 { + d.read_bool(128); + } + assert!(d.overreads() > 0); + } +} diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs new file mode 100644 index 00000000..c9441254 --- /dev/null +++ b/crates/ec-vp9/src/decode.rs @@ -0,0 +1,643 @@ +//! Frame decoding: superframe split, uncompressed header (via +//! [`ec_vp9_syntax::Vp9Parser`]), compressed header, tile parsing, +//! partition recursion, intra prediction, token decoding, +//! reconstruction and the loop filter (spec 6, 7, 8; libvpx +//! `vp9_decodeframe.c`). +//! +//! Lane scope: profile-0 8-bit 4:2:0 keyframes. Inter frames and other +//! profiles/subsamplings are refused by name; `show_existing_frame` +//! returns the buffered reference picture instead of pretending to +//! decode. + +use crate::header::{read_compressed_header, FrameContext}; +use crate::intra::build_intra_predictors; +use crate::loopfilter::LfGrids; +use crate::modes::{read_intra_frame_mode_info, MiInfo, MiState}; +use crate::tables::*; +use crate::tokens::{decode_coefs, scan_for, PlaneContexts}; +use crate::transform::inverse_transform_add; +use crate::{Error, Result}; +use ec_vp9_syntax::{superframe, FrameHeader, FrameType, Vp9Parser}; + +const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units + +/// A decoded, displayable frame: cropped contiguous planes. +#[derive(Clone, Debug)] +pub struct Picture { + /// Luma plane, `stride`-spaced rows of `width` pixels. + pub y: Vec, + /// U (Cb) plane, half resolution. + pub u: Vec, + /// V (Cr) plane, half resolution. + pub v: Vec, + /// Frame width in pixels. + pub width: u16, + /// Frame height in pixels. + pub height: u16, + /// Luma row pitch of the returned planes. + pub stride: usize, + /// Chroma row pitch of the returned planes. + pub uv_stride: usize, +} + +struct Planes { + y: Vec, + u: Vec, + v: Vec, + ys: usize, + uvs: usize, + aw: usize, + ah: usize, +} + +impl Planes { + fn plane(&mut self, plane: usize) -> (&mut [u8], usize) { + match plane { + 0 => (&mut self.y, self.ys), + 1 => (&mut self.u, self.uvs), + _ => (&mut self.v, self.uvs), + } + } + fn dims(&self, plane: usize) -> (usize, usize) { + if plane == 0 { + (self.aw, self.ah) + } else { + (self.aw / 2, self.ah / 2) + } + } +} + +/// The VP9 decoder. Feed complete frames — one full VP9 frame payload +/// or one superframe chunk, exactly what a container demuxer hands over +/// for the `VP90` codec. +pub struct Decoder { + parser: Vp9Parser, + ctx: FrameContext, + refs: [Option; 8], + /// Frame scratch, live only inside `decode_keyframe`. + planes: Option, +} + +impl Decoder { + /// Create an empty decoder; the first key frame sets the size. + pub fn new() -> Self { + Decoder { + parser: Vp9Parser::new(), + ctx: FrameContext::new(), + refs: [const { None }; 8], + planes: None, + } + } + + /// Decode one frame (or one superframe chunk); returns the picture + /// when a frame is for display. Hidden frames still update state. + pub fn decode(&mut self, frame: &[u8]) -> Result> { + let mut out = None; + for sub in superframe::split(frame)? { + if let Some(pic) = self.decode_one(sub)? { + out = Some(pic); + } + } + Ok(out) + } + + fn decode_one(&mut self, frame: &[u8]) -> Result> { + let hdr = self.parser.parse_frame(frame)?; + if hdr.show_existing_frame { + let slot = hdr.frame_to_show_map_idx as usize; + return match self.refs.get(slot).and_then(|p| p.as_ref()) { + Some(p) => Ok(Some(p.clone())), + None => Err(corrupt("show_existing_frame names an empty slot")), + }; + } + if hdr.profile != 0 { + return Err(Error::unsupported( + format!("vp9 profile {}", hdr.profile), + "this lane decodes profile 0 only", + )); + } + if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 { + return Err(Error::unsupported( + "vp9 subsampling", + format!( + "this lane decodes 4:2:0 only (subsampling {}/{} at profile {})", + hdr.subsampling_x, hdr.subsampling_y, hdr.profile + ), + )); + } + if hdr.frame_type != FrameType::Key { + return Err(Error::unsupported( + "vp9 inter", + "this lane decodes keyframes only", + )); + } + // A keyframe resets the frame context (spec 7.2) before the + // compressed header codes this frame's updates on top. + self.ctx = FrameContext::new(); + let hdr_start = hdr.uncompressed_header_size as usize; + let tx_mode = read_compressed_header( + &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], + &mut self.ctx, + )?; + + let pic = self.decode_keyframe(&hdr, frame, tx_mode)?; + // Reference refresh (spec 8.10): a keyframe updates all slots. + for slot in self.refs.iter_mut() { + *slot = Some(pic.clone()); + } + Ok(if hdr.show_frame { Some(pic) } else { None }) + } + + fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result { + let width = hdr.width as usize; + let height = hdr.height as usize; + let aw = width.div_ceil(8) * 8; + let ah = height.div_ceil(8) * 8; + self.planes = Some(Planes { + y: vec![128u8; aw * ah], + u: vec![128u8; aw / 2 * ah / 2], + v: vec![128u8; aw / 2 * ah / 2], + ys: aw, + uvs: aw / 2, + aw, + ah, + }); + let tail_start = + hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize; + let tail: Vec = frame[tail_start..].to_vec(); + let res = self.decode_keyframe_inner(hdr, tx_mode, &tail); + self.planes = None; + res + } + + fn decode_keyframe_inner(&mut self, hdr: &FrameHeader, tx_mode: u8, tail: &[u8]) -> Result { + let aw = self.planes.as_ref().expect("frame scratch").aw; + let ah = self.planes.as_ref().expect("frame scratch").ah; + let width = hdr.width as usize; + let height = hdr.height as usize; + let mi_cols = hdr.mi_cols() as usize; + let mi_rows = hdr.mi_rows() as usize; + let sb64_cols = mi_cols.div_ceil(SB_MI); + let sb64_rows = mi_rows.div_ceil(SB_MI); + let tile_cols = 1usize << hdr.tile_info.cols_log2; + let tile_rows = 1usize << hdr.tile_info.rows_log2; + + // Tile data: every tile except the overall last carries a + // 32-bit LE size prefix (spec 6.4). + let mut data: &[u8] = tail; + let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows); + for tr in 0..tile_rows { + for tc in 0..tile_cols { + let last = tr == tile_rows - 1 && tc == tile_cols - 1; + if last { + tiles.push(data); + } else { + ensure(data.len() >= 4, "truncated tile size")?; + let sz = u32::from_le_bytes(data[..4].try_into().unwrap()) as usize; + data = &data[4..]; + ensure(data.len() >= sz, "truncated tile data")?; + tiles.push(&data[..sz]); + data = &data[sz..]; + } + } + } + + // Keyframe loop filter levels: intra ref, no mode class, per + // segment (spec 8.8.1). + let mut level_of_seg = [[0u8; 2]; 8]; + for (seg, slot) in level_of_seg.iter_mut().enumerate() { + *slot = hdr.loop_filter_levels(seg)[0]; + } + + let mut grids = LfGrids { + tx4: vec![0; mi_cols * 2 * mi_rows * 2], + level8: vec![0; mi_cols * mi_rows], + blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows], + otx: vec![0; mi_cols * mi_rows], + mi_cols, + mi_rows, + }; + let mut ti = 0usize; + for tr in 0..tile_rows { + let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; + let row_hi = ((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2).min(mi_rows); + for tc in 0..tile_cols { + let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI; + let col_hi = ((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2).min(mi_cols); + let mut r = crate::bool::BoolDecoder::new(tiles[ti])?; + ti += 1; + let mut ectx = [ + PlaneContexts::new(mi_cols * 2), + PlaneContexts::new(mi_cols), + PlaneContexts::new(mi_cols), + ]; + let mut mi = MiState::new(mi_cols, mi_rows); + ectx.iter_mut().for_each(|p| p.above.fill(0)); + mi.above_seg.fill(0); + for sb_row in row_lo..row_hi { + if sb_row % SB_MI == 0 { + ectx.iter_mut().for_each(|p| p.left = [0; 32]); + mi.left_seg = [0; 32]; + } + for sb_col in col_lo..col_hi { + self.decode_partition( + &mut r, + &mut mi, + &mut ectx, + &mut grids, + &level_of_seg, + hdr, + sb_row, + sb_col, + 4, + row_lo, + col_lo, + tx_mode, + )?; + } + } + ensure(r.overreads() == 0, "tile bool decoder desync")?; + } + } + + // Loop filter post-pass (level 0 disables it for the frame). + if hdr.loop_filter.level > 0 { + let p = self.planes.as_mut().expect("frame scratch"); + grids.filter_frame( + &mut p.y, p.ys, &mut p.u, &mut p.v, p.uvs, aw, ah, aw / 2, ah / 2, + hdr.loop_filter.sharpness, + ); + } + + let crop = |src: &[u8], stride: usize, w: usize, h: usize| -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + out.extend_from_slice(&src[row * stride..row * stride + w]); + } + out + }; + let planes = self.planes.as_ref().expect("frame scratch"); + Ok(Picture { + y: crop(&planes.y, planes.ys, width, height), + u: crop(&planes.u, planes.uvs, width / 2, height / 2), + v: crop(&planes.v, planes.uvs, width / 2, height / 2), + width: width as u16, + height: height as u16, + stride: aw, + uv_stride: aw / 2, + }) + } + + /// `decode_partition` (decodeframe.c:1173). + #[allow(clippy::too_many_arguments)] + fn decode_partition( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &mut MiState, + ectx: &mut [PlaneContexts; 3], + grids: &mut LfGrids, + level_of_seg: &[[u8; 2]; 8], + hdr: &FrameHeader, + row: usize, + col: usize, + n4: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + ) -> Result<()> { + if row >= mi.mi_rows || col >= mi.mi_cols { + return Ok(()); + } + let n8 = n4 - 1; + let hbs = (1usize << n8) >> 1; + let has_rows = row + hbs < mi.mi_rows; + let has_cols = col + hbs < mi.mi_cols; + // Spec 6.3.5: partition symbols are coded only for blocks >= 8x8; + // the 4x4 sub-blocks of a split 8x8 carry none (implicitly NONE). + let partition = if n4 == 1 { + 0 + } else { + let partition = { + let ctx = mi.partition_ctx(row, col, n8 as u32); + let probs = &self.ctx.partition[ctx]; + if has_rows && has_cols { + r.read_tree(&PARTITION_TREE, probs) + } else if !has_rows && has_cols { + if r.read_bool(probs[1]) { 3 } else { 1 } + } else if has_rows && !has_cols { + if r.read_bool(probs[2]) { 3 } else { 2 } + } else { + 3 + } + }; + partition + }; + let bsize = bsize_of_n4(n4); + let subsize = SUBSIZE_LOOKUP[partition as usize * 13 + bsize] as usize; + if hbs == 0 { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, 1, 1, + tile_row_start, tile_col_start, tx_mode)?; + } else { + match partition { + 0 => self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n4, n4, tile_row_start, tile_col_start, tx_mode)?, + 1 => { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n4, n8, tile_row_start, tile_col_start, tx_mode)?; + if has_rows { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row + hbs, col, + subsize, n4, n8, tile_row_start, tile_col_start, tx_mode)?; + } + } + 2 => { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n8, n4, tile_row_start, tile_col_start, tx_mode)?; + if has_cols { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col + hbs, + subsize, n8, n4, tile_row_start, tile_col_start, tx_mode)?; + } + } + _ => { + for (rr, cc) in [ + (row, col), + (row, col + hbs), + (row + hbs, col), + (row + hbs, col + hbs), + ] { + self.decode_partition(r, mi, ectx, grids, level_of_seg, hdr, rr, cc, n8, + tile_row_start, tile_col_start, tx_mode)?; + } + } + } + } + if bsize >= 3 && (bsize == 3 || partition != 3) { + mi.update_partition_ctx(row, col, subsize, 1 << n8); + } + Ok(()) + } + + /// `decode_block` intra path (decodeframe.c:913). + #[allow(clippy::too_many_arguments)] + fn decode_block( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &mut MiState, + ectx: &mut [PlaneContexts; 3], + grids: &mut LfGrids, + level_of_seg: &[[u8; 2]; 8], + hdr: &FrameHeader, + row: usize, + col: usize, + sb_type: usize, + bwl: usize, + bhl: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + ) -> Result<()> { + let bw = 1 << (bwl - 1); + let bh = 1 << (bhl - 1); + let x_mis = bw.min(mi.mi_cols - col); + let y_mis = bh.min(mi.mi_rows - row); + + let info = read_intra_frame_mode_info( + r, mi, &hdr.segmentation, &self.ctx.partition, row, col, sb_type, x_mis, y_mis, + tile_row_start, tile_col_start, tx_mode, &self.ctx.skip, + )?; + + // Per-plane 4x4 counts; sub-8x8 blocks use their block-size dims + // (luma 1x1 / 1x2 / 2x1), chroma is processed once per 8x8 (TL). + let sub = sb_type < 3; + let n4w = if sub { + [NUM_4X4_BLOCKS_WIDE_LOOKUP[sb_type] as usize, 1, 1] + } else { + [bw * 2, bw, bw] + }; + let n4h = if sub { + [NUM_4X4_BLOCKS_HIGH_LOOKUP[sb_type] as usize, 1, 1] + } else { + [bh * 2, bh, bh] + }; + let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32; + let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32; + + let level = level_of_seg[info.segment as usize][0]; + for dy in 0..y_mis { + for dx in 0..x_mis { + let cell = (row + dy) * mi.mi_cols + col + dx; + grids.level8[cell] = level; + grids.blk[cell] = (sb_type as u8, row as u32, col as u32); + grids.otx[cell] = if sb_type < 3 { TX_4X4 as u8 } else { info.tx_size as u8 }; + } + } + // Luma tx4 grid (block-uniform in VP9). + { + let maxw = (n4w[0] as i32 + (mb_to_right.min(0) >> 5)).max(0) as usize; + let maxh = (n4h[0] as i32 + (mb_to_bottom.min(0) >> 5)).max(0) as usize; + for rr in 0..maxh.min(n4h[0]) { + for cc in 0..maxw.min(n4w[0]) { + grids.tx4[(row * 2 + rr) * mi.mi_cols * 2 + col * 2 + cc] = + info.tx_size as u8; + } + } + } + + if info.skip { + for plane in 0..3usize { + let s = usize::from(plane != 0); + let offx = (col << 1) >> s; + let offy = (row << 1) >> s; + for i in 0..n4w[plane] { + ectx[plane].above[offx + i] = 0; + } + let lrows = 32usize >> s; + for i in 0..n4h[plane].min(lrows) { + ectx[plane].left[(offy + i) % lrows] = 0; + } + } + } + + for plane in 0..3usize { + let s = usize::from(plane != 0); + let tx_size = if plane == 0 { + info.tx_size + } else { + get_uv_tx_size(info.tx_size, sb_type) + }; + let step = 1usize << tx_size; + let max_blocks_wide = + (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let max_blocks_high = + (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + // Sub-8x8 chroma is coded once per 8x8, with the first + // (top-left) sub-block. + if sub && plane != 0 && !(row % 2 == 0 && col % 2 == 0) { + continue; + } + for brow in (0..max_blocks_high).step_by(step) { + for bcol in (0..max_blocks_wide).step_by(step) { + self.predict_and_reconstruct(r, ectx, hdr, &info, plane, row, col, brow, bcol, + tx_size, sb_type, bw, bh, mb_to_right, mb_to_bottom, tile_row_start, + tile_col_start)?; + } + } + } + + for dy in 0..y_mis { + for dx in 0..x_mis { + mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone()); + } + } + Ok(()) + } + + /// `predict_and_reconstruct_intra_block` (decodeframe.c:309): + /// predict, then tokens, then residual add; plus + /// `vp9_decode_block_tokens` context bookkeeping (the v1.15 edge + /// shifts included). + #[allow(clippy::too_many_arguments)] + fn predict_and_reconstruct( + &mut self, + r: &mut crate::bool::BoolDecoder, + ectx: &mut [PlaneContexts; 3], + hdr: &FrameHeader, + info: &MiInfo, + plane: usize, + mi_row: usize, + mi_col: usize, + tx_row: usize, + tx_col: usize, + tx_size: usize, + sb_type: usize, + bw: usize, + bh: usize, + mb_to_right: i32, + mb_to_bottom: i32, + tile_row_start: usize, + tile_col_start: usize, + ) -> Result<()> { + let s = usize::from(plane != 0); + let mode = if plane == 0 { + if sb_type < 3 { + info.bmi[(tx_row << 1) + tx_col] + } else { + info.mode + } + } else { + info.uv_mode + }; + let planes = self.planes.as_mut().expect("frame scratch"); + let (pw, ph) = planes.dims(plane); + let stride = pw; + let bs = 4 << tx_size; + let x0 = ((mi_col * 8) >> s) + tx_col * 4; + let y0 = ((mi_row * 8) >> s) + tx_row * 4; + let up = tx_row != 0 || mi_row > tile_row_start; + let lft = tx_col != 0 || mi_col > tile_col_start; + + // 1. Intra prediction (reads reconstructed neighbours). + { + let (data, _) = planes.plane(plane); + build_intra_predictors(data, stride, pw, ph, x0, y0, mode, bs, up, lft, x0 + bs < pw); + } + + if info.skip { + return Ok(()); + } + + // 2. Tokens. + let lossless = hdr.quantization.lossless(); + let tx_type = if plane != 0 || lossless { + DCT_DCT + } else { + MODE_TO_TXTYPE_LOOKUP[mode as usize] as usize + }; + let (scan, nb) = scan_for(tx_size, tx_type); + let q = hdr.segment_dequant(info.segment as usize); + let dequant: [i16; 2] = if plane == 0 { + [q.luma_dc, q.luma_ac] + } else { + [q.chroma_dc, q.chroma_ac] + }; + let ptype = usize::from(plane != 0); + let ax = ((mi_col << 1) >> s) + tx_col; + let lrows = 32usize >> s; + let ay = ((mi_row << 1) >> s) % lrows; + let ctx_in = + usize::from(ectx[plane].above[ax] != 0) + usize::from(ectx[plane].left[ay] != 0); + let coef = + decode_coefs(r, ptype, tx_size, &dequant, ctx_in, scan, nb, &self.ctx.coef[tx_size]); + + // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts). + let n4w = bw * 2 >> s; + let n4h = bh * 2 >> s; + let maxw = (n4w as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let maxh = (n4h as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + let nblocks = 1usize << tx_size; + let eob_pos = usize::from(coef.eob > 0); + let shift_a = if maxw > 0 && nblocks + tx_col > maxw { + (nblocks - (maxw - tx_col)) * 8 + } else { + 0 + }; + let shift_l = if maxh > 0 && nblocks + tx_row > maxh { + (nblocks - (maxh - tx_row)) * 8 + } else { + 0 + }; + match tx_size { + TX_4X4 => { + ectx[plane].above[ax] = eob_pos as u8; + ectx[plane].left[ay] = eob_pos as u8; + } + TX_8X8 => { + let va = ((eob_pos as u16) * 0x0101) >> shift_a; + ectx[plane].above[ax] = va as u8; + ectx[plane].above[ax + 1] = (va >> 8) as u8; + let vl = ((eob_pos as u16) * 0x0101) >> shift_l; + ectx[plane].left[ay] = vl as u8; + ectx[plane].left[ay + 1] = (vl >> 8) as u8; + } + TX_16X16 => { + for k in 0..4 { + let va = ((eob_pos as u32) * 0x01010101) >> shift_a; + ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; + let vl = ((eob_pos as u32) * 0x01010101) >> shift_l; + ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; + } + } + _ => { + for k in 0..8 { + let va = ((eob_pos as u64) * 0x0101010101010101) >> shift_a; + ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; + let vl = ((eob_pos as u64) * 0x0101010101010101) >> shift_l; + ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; + } + } + } + + // 4. Residual add. + if coef.eob > 0 { + let dst_off = y0 * stride + x0; + let (data, _) = planes.plane(plane); + inverse_transform_add(tx_size, tx_type, &coef.coeffs, data, dst_off, stride, lossless); + } + Ok(()) + } +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +/// `BLOCK_SIZE` from `log2(4x4s per side)`. +fn bsize_of_n4(n4: usize) -> usize { + match n4 { + 4 => 12, // BLOCK_64X64 + 3 => 9, // BLOCK_32X32 + 2 => 3, // BLOCK_8X8 + _ => 0, // BLOCK_4X4 + } +} diff --git a/crates/ec-vp9/src/decode.rsdecode.rs b/crates/ec-vp9/src/decode.rsdecode.rs new file mode 100644 index 00000000..6c0516d7 --- /dev/null +++ b/crates/ec-vp9/src/decode.rsdecode.rs @@ -0,0 +1,620 @@ +//! Frame decoding: superframe split, uncompressed header (via +//! [`ec_vp9_syntax::Vp9Parser`]), compressed header, tile parsing, +//! partition recursion, intra prediction, token decoding, +//! reconstruction and the loop filter (spec 6, 7, 8; libvpx +//! `vp9_decodeframe.c`). +//! +//! Lane scope: profile-0 8-bit 4:2:0 keyframes. Inter frames and other +//! profiles/subsamplings are refused by name; `show_existing_frame` +//! returns the buffered reference picture instead of pretending to +//! decode. + +use crate::header::{read_compressed_header, FrameContext}; +use crate::intra::build_intra_predictors; +use crate::loopfilter::LfGrids; +use crate::modes::{read_intra_frame_mode_info, MiInfo, MiState}; +use crate::tables::*; +use crate::tokens::{decode_coefs, scan_for, PlaneContexts}; +use crate::transform::inverse_transform_add; +use crate::{Error, Result}; +use ec_vp9_syntax::{superframe, FrameHeader, FrameType, Vp9Parser}; + +const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units + +/// A decoded, displayable frame: cropped contiguous planes. +#[derive(Clone, Debug)] +pub struct Picture { + /// Luma plane, `stride`-spaced rows of `width` pixels. + pub y: Vec, + /// U (Cb) plane, half resolution. + pub u: Vec, + /// V (Cr) plane, half resolution. + pub v: Vec, + /// Frame width in pixels. + pub width: u16, + /// Frame height in pixels. + pub height: u16, + /// Luma row pitch of the returned planes. + pub stride: usize, + /// Chroma row pitch of the returned planes. + pub uv_stride: usize, +} + +struct Planes { + y: Vec, + u: Vec, + v: Vec, + ys: usize, + uvs: usize, + aw: usize, + ah: usize, +} + +impl Planes { + fn plane(&mut self, plane: usize) -> (&mut [u8], usize) { + match plane { + 0 => (&mut self.y, self.ys), + 1 => (&mut self.u, self.uvs), + _ => (&mut self.v, self.uvs), + } + } + fn dims(&self, plane: usize) -> (usize, usize) { + if plane == 0 { + (self.aw, self.ah) + } else { + (self.aw / 2, self.ah / 2) + } + } +} + +/// The VP9 decoder. Feed complete frames — one full VP9 frame payload +/// or one superframe chunk, exactly what a container demuxer hands over +/// for the `VP90` codec. +pub struct Decoder { + parser: Vp9Parser, + ctx: FrameContext, + refs: [Option; 8], + /// Frame scratch, live only inside `decode_keyframe`. + planes: Option, +} + +impl Decoder { + /// Create an empty decoder; the first key frame sets the size. + pub fn new() -> Self { + Decoder { + parser: Vp9Parser::new(), + ctx: FrameContext::new(), + refs: [const { None }; 8], + planes: None, + } + } + + /// Decode one frame (or one superframe chunk); returns the picture + /// when a frame is for display. Hidden frames still update state. + pub fn decode(&mut self, frame: &[u8]) -> Result> { + let mut out = None; + for sub in superframe::split(frame)? { + if let Some(pic) = self.decode_one(sub)? { + out = Some(pic); + } + } + Ok(out) + } + + fn decode_one(&mut self, frame: &[u8]) -> Result> { + let hdr = self.parser.parse_frame(frame)?; + if hdr.show_existing_frame { + let slot = hdr.frame_to_show_map_idx as usize; + return match self.refs.get(slot).and_then(|p| p.as_ref()) { + Some(p) => Ok(Some(p.clone())), + None => Err(corrupt("show_existing_frame names an empty slot")), + }; + } + if hdr.profile != 0 { + return Err(Error::unsupported( + format!("vp9 profile {}", hdr.profile), + "this lane decodes profile 0 only", + )); + } + if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 { + return Err(Error::unsupported( + "vp9 subsampling", + format!( + "this lane decodes 4:2:0 only (subsampling {}/{} at profile {})", + hdr.subsampling_x, hdr.subsampling_y, hdr.profile + ), + )); + } + if hdr.frame_type != FrameType::Key { + return Err(Error::unsupported( + "vp9 inter", + "this lane decodes keyframes only", + )); + } + // A keyframe resets the frame context (spec 7.2) before the + // compressed header codes this frame's updates on top. + self.ctx = FrameContext::new(); + let hdr_start = hdr.uncompressed_header_size as usize; + let tx_mode = read_compressed_header( + &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], + &mut self.ctx, + )?; + + let pic = self.decode_keyframe(&hdr, frame, tx_mode)?; + // Reference refresh (spec 8.10): a keyframe updates all slots. + for slot in self.refs.iter_mut() { + *slot = Some(pic.clone()); + } + Ok(if hdr.show_frame { Some(pic) } else { None }) + } + + fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result { + let width = hdr.width as usize; + let height = hdr.height as usize; + let aw = width.div_ceil(8) * 8; + let ah = height.div_ceil(8) * 8; + self.planes = Some(Planes { + y: vec![128u8; aw * ah], + u: vec![128u8; aw / 2 * ah / 2], + v: vec![128u8; aw / 2 * ah / 2], + ys: aw, + uvs: aw / 2, + aw, + ah, + }); + let tail_start = + hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize; + let tail: Vec = frame[tail_start..].to_vec(); + let res = self.decode_keyframe_inner(hdr, tx_mode, &tail); + self.planes = None; + res + } + + fn decode_keyframe_inner(&mut self, hdr: &FrameHeader, tx_mode: u8, tail: &[u8]) -> Result { + let aw = self.planes.as_ref().expect("frame scratch").aw; + let ah = self.planes.as_ref().expect("frame scratch").ah; + let width = hdr.width as usize; + let height = hdr.height as usize; + let mi_cols = hdr.mi_cols() as usize; + let mi_rows = hdr.mi_rows() as usize; + let sb64_cols = mi_cols.div_ceil(SB_MI); + let sb64_rows = mi_rows.div_ceil(SB_MI); + let tile_cols = 1usize << hdr.tile_info.cols_log2; + let tile_rows = 1usize << hdr.tile_info.rows_log2; + + // Tile data: every tile except the overall last carries a + // 32-bit LE size prefix (spec 6.4). + let mut data: &[u8] = tail; + let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows); + for tr in 0..tile_rows { + for tc in 0..tile_cols { + let last = tr == tile_rows - 1 && tc == tile_cols - 1; + if last { + tiles.push(data); + } else { + ensure(data.len() >= 4, "truncated tile size")?; + let sz = u32::from_le_bytes(data[..4].try_into().unwrap()) as usize; + data = &data[4..]; + ensure(data.len() >= sz, "truncated tile data")?; + tiles.push(&data[..sz]); + data = &data[sz..]; + } + } + } + + // Keyframe loop filter levels: intra ref, no mode class, per + // segment (spec 8.8.1). + let mut level_of_seg = [[0u8; 2]; 8]; + for (seg, slot) in level_of_seg.iter_mut().enumerate() { + *slot = hdr.loop_filter_levels(seg)[0]; + } + + let mut grids = LfGrids { + tx4: vec![0; mi_cols * 2 * mi_rows * 2], + level8: vec![0; mi_cols * mi_rows], + blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows], + otx: vec![0; mi_cols * mi_rows], + mi_cols, + mi_rows, + }; + let mut ti = 0usize; + for tr in 0..tile_rows { + let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; + let row_hi = ((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2).min(mi_rows); + for tc in 0..tile_cols { + let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI; + let col_hi = ((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2).min(mi_cols); + let mut r = crate::bool::BoolDecoder::new(tiles[ti])?; + ti += 1; + let mut ectx = [ + PlaneContexts::new(mi_cols * 2), + PlaneContexts::new(mi_cols), + PlaneContexts::new(mi_cols), + ]; + let mut mi = MiState::new(mi_cols, mi_rows); + ectx.iter_mut().for_each(|p| p.above.fill(0)); + mi.above_seg.fill(0); + for sb_row in row_lo..row_hi { + if sb_row % SB_MI == 0 { + ectx.iter_mut().for_each(|p| p.left = [0; 32]); + mi.left_seg = [0; 32]; + } + for sb_col in col_lo..col_hi { + self.decode_partition( + &mut r, + &mut mi, + &mut ectx, + &mut grids, + &level_of_seg, + hdr, + sb_row, + sb_col, + 4, + row_lo, + col_lo, + tx_mode, + )?; + } + } + ensure(r.overreads() == 0, "tile bool decoder desync")?; + } + } + + // Loop filter post-pass (level 0 disables it for the frame). + if hdr.loop_filter.level > 0 { + let p = self.planes.as_mut().expect("frame scratch"); + grids.filter_frame( + &mut p.y, p.ys, &mut p.u, &mut p.v, p.uvs, aw, ah, aw / 2, ah / 2, + hdr.loop_filter.sharpness, + ); + } + + let crop = |src: &[u8], stride: usize, w: usize, h: usize| -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + out.extend_from_slice(&src[row * stride..row * stride + w]); + } + out + }; + let planes = self.planes.as_ref().expect("frame scratch"); + Ok(Picture { + y: crop(&planes.y, planes.ys, width, height), + u: crop(&planes.u, planes.uvs, width / 2, height / 2), + v: crop(&planes.v, planes.uvs, width / 2, height / 2), + width: width as u16, + height: height as u16, + stride: aw, + uv_stride: aw / 2, + }) + } + + /// `decode_partition` (decodeframe.c:1173). + #[allow(clippy::too_many_arguments)] + fn decode_partition( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &mut MiState, + ectx: &mut [PlaneContexts; 3], + grids: &mut LfGrids, + level_of_seg: &[[u8; 2]; 8], + hdr: &FrameHeader, + row: usize, + col: usize, + n4: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + ) -> Result<()> { + if row >= mi.mi_rows || col >= mi.mi_cols { + return Ok(()); + } + let n8 = n4 - 1; + let hbs = 1usize << (n8 - 1); + let has_rows = row + hbs < mi.mi_rows; + let has_cols = col + hbs < mi.mi_cols; + let partition = { + let ctx = mi.partition_ctx(row, col, n8 as u32); + let probs = &self.ctx.partition[ctx]; + if has_rows && has_cols { + r.read_tree(&PARTITION_TREE, probs) + } else if !has_rows && has_cols { + if r.read_bool(probs[1]) { 3 } else { 1 } + } else if has_rows && !has_cols { + if r.read_bool(probs[2]) { 3 } else { 2 } + } else { + 3 + } + }; + let bsize = bsize_of_n4(n4); + let subsize = SUBSIZE_LOOKUP[partition as usize * 13 + bsize] as usize; + if hbs == 0 { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, 1, 1, + tile_row_start, tile_col_start, tx_mode)?; + } else { + match partition { + 0 => self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n4, n4, tile_row_start, tile_col_start, tx_mode)?, + 1 => { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n4, n8, tile_row_start, tile_col_start, tx_mode)?; + if has_rows { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row + hbs, col, + subsize, n4, n8, tile_row_start, tile_col_start, tx_mode)?; + } + } + 2 => { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col, subsize, + n8, n4, tile_row_start, tile_col_start, tx_mode)?; + if has_cols { + self.decode_block(r, mi, ectx, grids, level_of_seg, hdr, row, col + hbs, + subsize, n8, n4, tile_row_start, tile_col_start, tx_mode)?; + } + } + _ => { + for (rr, cc) in [ + (row, col), + (row, col + hbs), + (row + hbs, col), + (row + hbs, col + hbs), + ] { + self.decode_partition(r, mi, ectx, grids, level_of_seg, hdr, rr, cc, n8, + tile_row_start, tile_col_start, tx_mode)?; + } + } + } + } + if bsize >= 3 && (bsize == 3 || partition != 3) { + mi.update_partition_ctx(row, col, subsize, 1 << n8); + } + Ok(()) + } + + /// `decode_block` intra path (decodeframe.c:913). + #[allow(clippy::too_many_arguments)] + fn decode_block( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &mut MiState, + ectx: &mut [PlaneContexts; 3], + grids: &mut LfGrids, + level_of_seg: &[[u8; 2]; 8], + hdr: &FrameHeader, + row: usize, + col: usize, + sb_type: usize, + bwl: usize, + bhl: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + ) -> Result<()> { + let bw = 1 << (bwl - 1); + let bh = 1 << (bhl - 1); + let x_mis = bw.min(mi.mi_cols - col); + let y_mis = bh.min(mi.mi_rows - row); + + let info = read_intra_frame_mode_info( + r, mi, &hdr.segmentation, &self.ctx.partition, row, col, sb_type, x_mis, y_mis, + tile_row_start, tile_col_start, tx_mode, &self.ctx.skip, + )?; + + let n4w = [bw * 2, bw, bw]; + let n4h = [bh * 2, bh, bh]; + let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32; + let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32; + + let level = level_of_seg[info.segment as usize][0]; + for dy in 0..y_mis { + for dx in 0..x_mis { + let cell = (row + dy) * mi.mi_cols + col + dx; + grids.level8[cell] = level; + grids.blk[cell] = (sb_type as u8, row as u32, col as u32); + grids.otx[cell] = if sb_type < 3 { TX_4X4 as u8 } else { info.tx_size as u8 }; + } + } + // Luma tx4 grid (block-uniform in VP9). + { + let maxw = (n4w[0] as i32 + (mb_to_right.min(0) >> 5)).max(0) as usize; + let maxh = (n4h[0] as i32 + (mb_to_bottom.min(0) >> 5)).max(0) as usize; + for rr in 0..maxh.min(n4h[0]) { + for cc in 0..maxw.min(n4w[0]) { + grids.tx4[(row * 2 + rr) * mi.mi_cols * 2 + col * 2 + cc] = + info.tx_size as u8; + } + } + } + + if info.skip { + for plane in 0..3usize { + let s = usize::from(plane != 0); + let offx = (col << 1) >> s; + let offy = (row << 1) >> s; + for i in 0..n4w[plane] { + ectx[plane].above[offx + i] = 0; + } + let lrows = 32usize >> s; + for i in 0..n4h[plane].min(lrows) { + ectx[plane].left[(offy + i) % lrows] = 0; + } + } + } + + for plane in 0..3usize { + let s = usize::from(plane != 0); + let tx_size = if plane == 0 { + info.tx_size + } else { + get_uv_tx_size(info.tx_size, sb_type) + }; + let step = 1usize << tx_size; + let max_blocks_wide = + (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let max_blocks_high = + (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + for brow in (0..max_blocks_high).step_by(step) { + for bcol in (0..max_blocks_wide).step_by(step) { + self.predict_and_reconstruct(r, ectx, hdr, &info, plane, row, col, brow, bcol, + tx_size, sb_type, bw, bh, mb_to_right, mb_to_bottom, tile_row_start, + tile_col_start)?; + } + } + } + + for dy in 0..y_mis { + for dx in 0..x_mis { + mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone()); + } + } + Ok(()) + } + + /// `predict_and_reconstruct_intra_block` (decodeframe.c:309): + /// predict, then tokens, then residual add; plus + /// `vp9_decode_block_tokens` context bookkeeping (the v1.15 edge + /// shifts included). + #[allow(clippy::too_many_arguments)] + fn predict_and_reconstruct( + &mut self, + r: &mut crate::bool::BoolDecoder, + ectx: &mut [PlaneContexts; 3], + hdr: &FrameHeader, + info: &MiInfo, + plane: usize, + mi_row: usize, + mi_col: usize, + tx_row: usize, + tx_col: usize, + tx_size: usize, + sb_type: usize, + bw: usize, + bh: usize, + mb_to_right: i32, + mb_to_bottom: i32, + tile_row_start: usize, + tile_col_start: usize, + ) -> Result<()> { + let s = usize::from(plane != 0); + let mode = if plane == 0 { + if sb_type < 3 { + info.bmi[(tx_row << 1) + tx_col] + } else { + info.mode + } + } else { + info.uv_mode + }; + let planes = self.planes.as_mut().expect("frame scratch"); + let (pw, ph) = planes.dims(plane); + let stride = pw; + let bs = 4 << tx_size; + let x0 = ((mi_col * 8) >> s) + tx_col * 4; + let y0 = ((mi_row * 8) >> s) + tx_row * 4; + let up = tx_row != 0 || mi_row > tile_row_start; + let lft = tx_col != 0 || mi_col > tile_col_start; + + // 1. Intra prediction (reads reconstructed neighbours). + { + let (data, _) = planes.plane(plane); + build_intra_predictors(data, stride, pw, ph, x0, y0, mode, bs, up, lft, x0 + bs < pw); + } + + if info.skip { + return Ok(()); + } + + // 2. Tokens. + let lossless = hdr.quantization.lossless(); + let tx_type = if plane != 0 || lossless { + DCT_DCT + } else { + MODE_TO_TXTYPE_LOOKUP[mode as usize] as usize + }; + let (scan, nb) = scan_for(tx_size, tx_type); + let q = hdr.segment_dequant(info.segment as usize); + let dequant: [i16; 2] = if plane == 0 { + [q.luma_dc, q.luma_ac] + } else { + [q.chroma_dc, q.chroma_ac] + }; + let ptype = usize::from(plane != 0); + let ax = ((mi_col << 1) >> s) + tx_col; + let lrows = 32usize >> s; + let ay = ((mi_row << 1) >> s) % lrows; + let ctx_in = + usize::from(ectx[plane].above[ax] != 0) + usize::from(ectx[plane].left[ay] != 0); + let coef = + decode_coefs(r, ptype, tx_size, &dequant, ctx_in, scan, nb, &self.ctx.coef[tx_size]); + + // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts). + let n4w = bw * 2 >> s; + let n4h = bh * 2 >> s; + let maxw = (n4w as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let maxh = (n4h as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + let nblocks = 1usize << tx_size; + let eob_pos = usize::from(coef.eob > 0); + let shift_a = if maxw > 0 && nblocks + tx_col > maxw { + (nblocks - (maxw - tx_col)) * 8 + } else { + 0 + }; + let shift_l = if maxh > 0 && nblocks + tx_row > maxh { + (nblocks - (maxh - tx_row)) * 8 + } else { + 0 + }; + match tx_size { + TX_4X4 => { + ectx[plane].above[ax] = eob_pos as u8; + ectx[plane].left[ay] = eob_pos as u8; + } + TX_8X8 => { + let va = ((eob_pos as u16) * 0x0101) >> shift_a; + ectx[plane].above[ax] = va as u8; + ectx[plane].above[ax + 1] = (va >> 8) as u8; + let vl = ((eob_pos as u16) * 0x0101) >> shift_l; + ectx[plane].left[ay] = vl as u8; + ectx[plane].left[ay + 1] = (vl >> 8) as u8; + } + TX_16X16 => { + for k in 0..4 { + let va = ((eob_pos as u32) * 0x01010101) >> shift_a; + ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; + let vl = ((eob_pos as u32) * 0x01010101) >> shift_l; + ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; + } + } + _ => { + for k in 0..8 { + let va = ((eob_pos as u64) * 0x0101010101010101) >> shift_a; + ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; + let vl = ((eob_pos as u64) * 0x0101010101010101) >> shift_l; + ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; + } + } + } + + // 4. Residual add. + if coef.eob > 0 { + let dst_off = y0 * stride + x0; + let (data, _) = planes.plane(plane); + inverse_transform_add(tx_size, tx_type, &coef.coeffs, data, dst_off, stride, lossless); + } + Ok(()) + } +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +/// `BLOCK_SIZE` from `log2(4x4s per side)`. +fn bsize_of_n4(n4: usize) -> usize { + match n4 { + 4 => 12, // BLOCK_64X64 + 3 => 9, // BLOCK_32X32 + 2 => 3, // BLOCK_8X8 + _ => 0, // BLOCK_4X4 + } +} diff --git a/crates/ec-vp9/src/header.rs b/crates/ec-vp9/src/header.rs new file mode 100644 index 00000000..0f173e55 --- /dev/null +++ b/crates/ec-vp9/src/header.rs @@ -0,0 +1,189 @@ +//! The frame context (bool-coded probabilities) and the compressed +//! header (spec 6.2 `compressed_header` / 8.2): thin wrap over +//! [`ec_vp9_syntax::Vp9Parser`] for the uncompressed part, plus the +//! differential probability-update machinery (libvpx `vp9_dsubexp.c`). + +use crate::bool::BoolDecoder; +use crate::tables::*; + +/// All bool-coded probabilities a keyframe reads. +#[derive(Clone)] +pub(crate) struct FrameContext { + pub coef: [[[[[[u8; 3]; 6]; 6]; 2]; 2]; 4], + pub partition: [[u8; 3]; 16], + pub tx_p8x8: [[u8; 1]; 2], + pub tx_p16x16: [[u8; 2]; 2], + pub tx_p32x32: [[u8; 3]; 2], + pub skip: [u8; 3], +} + +impl FrameContext { + /// Spec 7.2 `setup_past_independence`: back to the defaults. + pub(crate) fn new() -> Self { + FrameContext { + coef: [ + DEFAULT_COEF_PROBS_4X4, + DEFAULT_COEF_PROBS_8X8, + DEFAULT_COEF_PROBS_16X16, + DEFAULT_COEF_PROBS_32X32, + ], + partition: { + let mut p = [[0u8; 3]; 16]; + for (i, row) in p.iter_mut().enumerate() { + row.copy_from_slice(&DEFAULT_PARTITION_PROBS[i * 3..i * 3 + 3]); + } + p + }, + tx_p8x8: [[TX_P8X8_PROB[0]], [TX_P8X8_PROB[1]]], + tx_p16x16: [ + [TX_P16X16_PROB[0], TX_P16X16_PROB[1]], + [TX_P16X16_PROB[2], TX_P16X16_PROB[3]], + ], + tx_p32x32: [ + [TX_P32X32_PROB[0], TX_P32X32_PROB[1], TX_P32X32_PROB[2]], + [TX_P32X32_PROB[3], TX_P32X32_PROB[4], TX_P32X32_PROB[5]], + ], + skip: DEFAULT_SKIP_PROBS, + } + } +} + +/// `inv_recenter_nonneg` (vp9_dsubexp.c). +fn inv_recenter_nonneg(v: i32, m: i32) -> i32 { + if v > 2 * m { + return v; + } + if v & 1 != 0 { + m - ((v + 1) >> 1) + } else { + m + (v >> 1) + } +} + +/// `decode_uniform` (vp9_dsubexp.c): l = 8. +fn decode_uniform(r: &mut BoolDecoder) -> i32 { + let l = 8; + let m = (1 << l) - 191; + let v = r.read_literal(7) as i32; + if v < m { + v + } else { + (v << 1) - m + r.read_bool(128) as i32 + } +} + +/// `decode_term_subexp` (vp9_dsubexp.c). +fn decode_term_subexp(r: &mut BoolDecoder) -> i32 { + if !r.read_bool(128) { + return r.read_literal(4) as i32; + } + if !r.read_bool(128) { + return r.read_literal(4) as i32 + 16; + } + if !r.read_bool(128) { + return r.read_literal(5) as i32 + 32; + } + decode_uniform(r) + 64 +} + +/// `inv_remap_prob` with libvpx's 255-entry map table. +fn inv_remap_prob(v: i32, m: u8) -> u8 { + const MAP: [u8; 255] = [ + 7, 20, 33, 46, 59, 72, 85, 98, 111, 124, 137, 150, 163, 176, 189, 202, 215, 228, 241, 254, + 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, + 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, + 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, + 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 190, 191, 192, 193, 194, 195, + 196, 197, 198, 199, 200, 201, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, + 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 229, 230, 231, 232, 233, 234, + 235, 236, 237, 238, 239, 240, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, + 253, + ]; + let v = MAP[v as usize] as i32; + let m = m as i32 - 1; + if (m << 1) <= 255 { + (1 + inv_recenter_nonneg(v, m)) as u8 + } else { + (255 - inv_recenter_nonneg(v, 255 - 1 - m)) as u8 + } +} + +/// `vp9_diff_update_prob`. +fn diff_update_prob(r: &mut BoolDecoder, p: &mut u8) { + if r.read_bool(DIFF_UPDATE_PROB) { + let delp = decode_term_subexp(r); + *p = inv_remap_prob(delp, *p); + } +} + +/// `read_coef_probs_common` (decodeframe.c:1314): one flag per tx size +/// covers all plane/ref/band/context updates of the first three (base) +/// probs per slot. +fn read_coef_probs(r: &mut BoolDecoder, ctx: &mut FrameContext, tx_mode: u8) { + let max_tx = TX_MODE_TO_BIGGEST_TX_SIZE[tx_mode as usize]; + for tx in 0..=max_tx { + if r.read_bool(128) { + for plane in 0..2 { + for _ref in 0..2 { + for band in 0..6 { + let n_ctx = if band == 0 { 3 } else { 6 }; + for ci in 0..n_ctx { + for m in 0..3 { + diff_update_prob(r, &mut ctx.coef[tx][plane][_ref][band][ci][m]); + } + } + } + } + } + } + } +} + +/// `read_tx_mode` (decodeframe.c:58). +fn read_tx_mode(r: &mut BoolDecoder) -> u8 { + let mut m = r.read_literal(2) as u8; + if m == ALLOW_32X32 { + m += r.read_bool(128) as u8; + } + m +} + +/// `read_compressed_header` for intra frames (the inter branch is dead +/// in this lane): tx mode, tx probs, coef probs, skip probs. +pub(crate) fn read_compressed_header(data: &[u8], ctx: &mut FrameContext) -> crate::Result { + let mut r = BoolDecoder::new(data)?; + let tx_mode = read_tx_mode(&mut r); + if tx_mode == TX_MODE_SELECT { + for row in 0..2 { + for j in 0..1 { + diff_update_prob(&mut r, &mut ctx.tx_p8x8[row][j]); + } + } + for row in 0..2 { + for j in 0..2 { + diff_update_prob(&mut r, &mut ctx.tx_p16x16[row][j]); + } + } + for row in 0..2 { + for j in 0..3 { + diff_update_prob(&mut r, &mut ctx.tx_p32x32[row][j]); + } + } + } + read_coef_probs(&mut r, ctx, tx_mode); + for p in &mut ctx.skip { + diff_update_prob(&mut r, p); + } + if std::env::var_os("EC_VP9_DBG").is_some() { + eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset()); + eprintln!("DBG skip_probs={:?} p8x8={:?} p16={:?}", ctx.skip, ctx.tx_p8x8, ctx.tx_p16x16); + eprintln!("DBG coef[0][0][0][0][0..3]={:?} coef[0][0][1][1][0..3]={:?}", ctx.coef[0][0][0][0], ctx.coef[0][0][1][1]); + } + ensure(r.overreads() == 0, "compressed header desync")?; + Ok(tx_mode) +} diff --git a/crates/ec-vp9/src/intra.rs b/crates/ec-vp9/src/intra.rs new file mode 100644 index 00000000..248e0b0c --- /dev/null +++ b/crates/ec-vp9/src/intra.rs @@ -0,0 +1,329 @@ +//! Intra prediction (spec 7.11; libvpx `vp9_reconintra.c +//! build_intra_predictors` + `vpx_dsp/intrapred.c` kernels, ported +//! verbatim — including the 127/129 border fills and the edge +//! replication rules at frame boundaries). +//! +//! Neighbour staging: `above_data[15]` is `above[-1]` (the above-left +//! corner), `above_data[16 + i]` is `above[i]` — exactly the C's +//! 16-pixel offset into `above_data[64 + 16]`. + +/// `AVG3`. +#[inline] +fn avg3(a: u8, b: u8, c: u8) -> u8 { + ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as u8 +} + +/// `AVG2`. +#[inline] +fn avg2(a: u8, b: u8) -> u8 { + ((a as u32 + b as u32 + 1) >> 1) as u8 +} + +const A: usize = 16; + +/// `extend_modes` (vp9_reconintra.c): (NEED_LEFT, NEED_ABOVE, +/// NEED_ABOVERIGHT) per mode. +fn needs(mode: u8) -> (bool, bool, bool) { + match mode { + 0 => (true, true, false), // DC + 1 => (false, true, false), // V + 2 => (true, false, false), // H + 3 => (false, false, true), // D45 + 4 => (true, true, false), // D135 + 5 => (true, true, false), // D117 + 6 => (true, true, false), // D153 + 7 => (true, false, false), // D207 + 8 => (false, false, true), // D63 + _ => (true, true, false), // TM + } +} + +/// `build_intra_predictors` + mode dispatch for one plane of the +/// reconstructed frame. `data` is the whole plane; `(x0, y0)` the +/// block's absolute sample position; `frame_w`/`frame_h` the coded +/// (aligned) plane size. +pub(crate) fn build_intra_predictors( + data: &mut [u8], + stride: usize, + frame_w: usize, + frame_h: usize, + x0: usize, + y0: usize, + mode: u8, + bs: usize, + up_available: bool, + left_available: bool, + right_available: bool, +) { + let (need_left, need_above, need_aboveright) = needs(mode); + let mut left_col = [0u8; 32]; + let mut above_data = [0u8; 64 + 16]; + let at = |dx: isize, dy: isize| -> u8 { + data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize] + }; + + if need_left { + if left_available { + if y0 + bs <= frame_h { + for i in 0..bs { + left_col[i] = at(-1, i as isize); + } + } else { + let extend_bottom = frame_h - y0; + for i in 0..extend_bottom { + left_col[i] = at(-1, i as isize); + } + for i in extend_bottom..bs { + left_col[i] = at(-1, extend_bottom as isize - 1); + } + } + } else { + left_col[..bs].fill(129); + } + } + + if need_above { + if up_available { + if x0 + bs <= frame_w { + for i in 0..bs { + above_data[A + i] = at(i as isize, -1); + } + } else if x0 <= frame_w { + let r = frame_w - x0; + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + let v = above_data[A + r - 1]; + let n = x0 + bs - frame_w; + above_data[A + r..A + r + n].fill(v); + } + above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; + } else { + above_data[A..A + bs].fill(127); + above_data[A - 1] = 127; + } + } + + if need_aboveright { + if up_available { + if x0 + 2 * bs <= frame_w { + for i in 0..2 * bs { + above_data[A + i] = at(i as isize, -1); + } + if !(bs == 4 && right_available) { + let v = above_data[A + bs - 1]; + above_data[A + bs..A + 2 * bs].fill(v); + } + } else if x0 + bs <= frame_w { + let r = frame_w - x0; + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + if bs == 4 && right_available { + let v = above_data[A + r - 1]; + let n = x0 + 2 * bs - frame_w; + above_data[A + r..A + r + n].fill(v); + } else { + let v = above_data[A + bs - 1]; + above_data[A + bs..A + 2 * bs].fill(v); + } + } else if x0 <= frame_w { + let r = frame_w - x0; + for i in 0..r { + above_data[A + i] = at(i as isize, -1); + } + let v = above_data[A + r - 1]; + let n = x0 + 2 * bs - frame_w; + above_data[A + r..A + r + n].fill(v); + } + above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; + } else { + above_data[A..A + 2 * bs].fill(127); + above_data[A - 1] = 127; + } + } + + // The C's `const_above_row = above_ref` shortcut for bs==4 && + // right&&left stages the same bytes, so above_data is equivalent. + let dst = &mut data[y0 * stride + x0..]; + dispatch( + mode, bs, dst, stride, &above_data, &left_col, up_available, left_available, + ); +} + +fn dispatch( + mode: u8, + bs: usize, + dst: &mut [u8], + stride: usize, + above: &[u8], + left: &[u8], + up: bool, + lft: bool, +) { + // `above` is the full above_data: [A-1] = above[-1], [A + i] = above[i]. + let cor = above[A - 1]; + let ab = &above[A..]; + match mode { + 0 if up && lft => { + let sum: u32 = ab[..bs] + .iter() + .chain(left[..bs].iter()) + .map(|&v| v as u32) + .sum(); + fill_dc(dst, stride, bs, ((sum + bs as u32) / (2 * bs as u32)) as u8); + } + 0 if lft => { + let sum: u32 = left[..bs].iter().map(|&v| v as u32).sum(); + fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8); + } + 0 if up => { + let sum: u32 = ab[..bs].iter().map(|&v| v as u32).sum(); + fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8); + } + 0 => fill_dc(dst, stride, bs, 128), + 1 => { + for r in 0..bs { + dst[r * stride..r * stride + bs].copy_from_slice(&ab[..bs]); + } + } + 2 => { + for r in 0..bs { + dst[r * stride..r * stride + bs].fill(left[r]); + } + } + 3 => { + // d45 + let above_right = ab[bs - 1]; + for x in 0..bs - 1 { + dst[x] = avg3(ab[x], ab[x + 1], ab[x + 2]); + } + dst[bs - 1] = above_right; + let mut x = 1; + let mut size = bs - 2; + while x < bs { + let src: Vec = dst[..x + size].to_vec(); + let off = x * stride; + dst[off..off + size].copy_from_slice(&src[x..x + size]); + dst[off + size..off + bs].fill(above_right); + x += 1; + size = size.saturating_sub(1); + } + } + 4 => { + // d135 + let mut border = [0u8; 64]; + for i in 0..bs - 2 { + border[i] = avg3(left[bs - 3 - i], left[bs - 2 - i], left[bs - 1 - i]); + } + border[bs - 2] = avg3(cor, left[0], left[1]); + border[bs - 1] = avg3(left[0], cor, ab[0]); + border[bs] = avg3(cor, ab[0], ab[1]); + for i in 0..bs - 2 { + border[bs + 1 + i] = avg3(ab[i], ab[i + 1], ab[i + 2]); + } + for i in 0..bs { + dst[i * stride..i * stride + bs] + .copy_from_slice(&border[bs - 1 - i..bs - 1 - i + bs]); + } + } + 5 => { + // d117 + for c in 0..bs { + dst[c] = avg2(above[A - 1 + c], ab[c]); + } + dst[stride] = avg3(left[0], cor, ab[0]); + for c in 1..bs { + dst[stride + c] = avg3(above[A + c - 2], ab[c - 1], ab[c]); + } + dst[2 * stride] = avg3(cor, left[0], left[1]); + for r in 3..bs { + dst[(r - 2) * stride] = avg3(left[r - 3], left[r - 2], left[r - 1]); + } + for r in 2..bs { + for c in 1..bs { + dst[r * stride + c] = dst[(r - 2) * stride + c - 1]; + } + } + } + 6 => { + // d153 + dst[0] = avg2(cor, left[0]); + for r in 1..bs { + dst[r * stride] = avg2(left[r - 1], left[r]); + } + dst[1] = avg3(left[0], cor, ab[0]); + dst[stride + 1] = avg3(cor, left[0], left[1]); + for r in 2..bs { + dst[r * stride + 1] = avg3(left[r - 2], left[r - 1], left[r]); + } + for c in 0..bs - 2 { + dst[2 + c] = avg3(above[A - 1 + c], ab[c], ab[c + 1]); + } + for r in 1..bs { + for c in 0..bs - 2 { + dst[(r + 1) * stride + 2 + c] = dst[r * stride + c]; + } + } + } + 7 => { + // d207 + for r in 0..bs - 1 { + dst[r * stride] = avg2(left[r], left[r + 1]); + } + dst[(bs - 1) * stride] = left[bs - 1]; + for r in 0..bs.saturating_sub(2) { + dst[r * stride + 1] = avg3(left[r], left[r + 1], left[r + 2]); + } + if bs >= 2 { + dst[(bs - 2) * stride + 1] = avg3(left[bs - 2], left[bs - 1], left[bs - 1]); + } + dst[(bs - 1) * stride + 1] = left[bs - 1]; + for c in 0..bs - 2 { + dst[(bs - 1) * stride + 2 + c] = left[bs - 1]; + } + for r in (0..bs - 1).rev() { + for c in 0..bs - 2 { + dst[r * stride + 2 + c] = dst[(r + 1) * stride + c]; + } + } + } + 8 => { + // d63 + for c in 0..bs { + dst[c] = avg2(ab[c], ab[c + 1]); + dst[stride + c] = avg3(ab[c], ab[c + 1], ab[c + 2]); + } + let mut r = 2; + let mut size = bs - 2; + while r < bs { + let src0: Vec = dst[(r >> 1)..(r >> 1) + size].to_vec(); + let base1 = stride + (r >> 1); + let src1: Vec = dst[base1..base1 + size].to_vec(); + let o0 = r * stride; + dst[o0..o0 + size].copy_from_slice(&src0); + dst[o0 + size..o0 + bs].fill(ab[bs - 1]); + let o1 = (r + 1) * stride; + dst[o1..o1 + size].copy_from_slice(&src1); + dst[o1 + size..o1 + bs].fill(ab[bs - 1]); + r += 2; + size -= 1; + } + } + _ => { + // TM + for r in 0..bs { + for c in 0..bs { + dst[r * stride + c] = + (left[r] as i32 + ab[c] as i32 - cor as i32).clamp(0, 255) as u8; + } + } + } + } +} + +fn fill_dc(dst: &mut [u8], stride: usize, bs: usize, v: u8) { + for r in 0..bs { + dst[r * stride..r * stride + bs].fill(v); + } +} diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs new file mode 100644 index 00000000..e0c9ceb2 --- /dev/null +++ b/crates/ec-vp9/src/lib.rs @@ -0,0 +1,47 @@ +//! Native VP9 (profile 0, 8-bit 4:2:0 keyframes) decoder. +//! +//! The crate implements the VP9 bitstream specification directly +//! ([spec]); libvpx's output is used only as a test oracle +//! (sample-exactness witnesses against ffmpeg's libvpx-based decoder), +//! never as code linked at runtime. Every module documents the spec +//! section it implements. Inter-frame prediction is refused by name; +//! this lane is keyframes only. +//! +//! [spec]: https://www.webmproject.org/docs/vp9/ +//! +//! # Unsafe +//! +//! This crate contains no `unsafe` code. + +#![deny(unsafe_code)] +#![warn(missing_docs)] + +pub mod bool; +pub mod decode; +pub mod header; +pub mod intra; +pub mod loopfilter; +pub mod modes; +pub mod stream; +pub mod tables; +pub mod tokens; +pub mod transform; + +pub use ec_core::{Error, Result}; + +/// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per +/// process. An `var_os` per bool read would lock std's ENV lock on every +/// coefficient; the hot path is a single relaxed atomic load. +pub(crate) fn trace_enabled() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static STATE: AtomicU8 = AtomicU8::new(0); + match STATE.load(Ordering::Relaxed) { + 0 => { + let on = std::env::var_os("EC_VP9_TRACE").is_some(); + STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); + on + } + 1 => false, + _ => true, + } +} diff --git a/crates/ec-vp9/src/loopfilter.rs b/crates/ec-vp9/src/loopfilter.rs new file mode 100644 index 00000000..7538634d --- /dev/null +++ b/crates/ec-vp9/src/loopfilter.rs @@ -0,0 +1,317 @@ +//! Loop filter for keyframes (spec 8.8; libvpx `vpx_dsp/loopfilter.c` +//! kernels + `vp9_loopfilter.c` edge selection, ported verbatim). +//! +//! Rather than libvpx's per-superblock LOOP_FILTER_MASK bitmaps, the +//! pass re-derives the same per-edge decisions from decode-time grids +//! (per-4x4 luma tx sizes, per-8x8 block map, block transform sizes and +//! levels). The rules `build_masks`/`build_y_mask` encode: +//! +//! - an internal 4x4 edge is filtered (4-tap) iff its tx size is 4x4; +//! - a prediction-block edge uses 16 taps for 16x16/32x32 transforms, +//! 8 taps for 8x8, and 4 taps for 4x4 — promoted to 8 taps on +//! 32x32 (luma) / 64x64 (chroma) borders; +//! - chroma edges exist for >=16x16 blocks (pred edges at the block's +//! own left/top sized by the uv transform, internal 4x4 uv edges when +//! the uv transform is 4x4) and for 8x8-region blocks only on the +//! z-(0,0) slot of each 16x16 area (4-tap, 8-tap at the 64-luma +//! border); +//! - intra skip blocks filter like any other (the early return in +//! `build_masks` is gated on `is_inter_block`). + +use crate::tables::*; + +#[inline] +fn sc(x: i32) -> i32 { + x.clamp(-128, 127) +} + +/// `filter4` kernel; `idx` = [op1, op0, oq0, oq1]. +fn filter4(s: &mut [u8], idx: [usize; 4], thresh: i32, mask: bool) { + if !mask { + return; + } + let (p1, p0, q0, q1) = (s[idx[0]], s[idx[1]], s[idx[2]], s[idx[3]]); + let hev = (p1 as i32 - p0 as i32).abs() > thresh || (q1 as i32 - q0 as i32).abs() > thresh; + let (ps1, ps0, qs0, qs1) = ( + (p1 ^ 0x80) as i8 as i32, + (p0 ^ 0x80) as i8 as i32, + (q0 ^ 0x80) as i8 as i32, + (q1 ^ 0x80) as i8 as i32, + ); + let mut filter = sc(ps1 - qs1); + if !hev { + filter = 0; + } + filter = sc(filter + 3 * (qs0 - ps0)); + let filter1 = sc(filter + 4) >> 3; + let filter2 = sc(filter + 3) >> 3; + s[idx[3]] = (sc(qs0 - filter1) ^ 0x80) as u8; + s[idx[2]] = (sc(ps0 + filter2) ^ 0x80) as u8; + let mut f = (filter1 + 1) >> 1; + if hev { + f = 0; + } + s[idx[1]] = (sc(ps1 + f) ^ 0x80) as u8; + s[idx[0]] = (sc(qs1 - f) ^ 0x80) as u8; +} + +/// The tapped edge filter: `dir` 0 = horizontal edges (rows step by +/// stride), 1 = vertical (columns step by 1). `taps` in {4, 8, 16}. +fn lpf_edge(data: &mut [u8], off: usize, stride: usize, dir: u8, taps: u8, blimit: i32, limit: i32) { + let step: isize = if dir == 0 { stride as isize } else { 1 }; + let edge = off as isize; + if std::env::var_os("EC_VP9_DBG").is_some() { + let need = if taps == 16 { 8 } else if taps == 8 { 4 } else { 2 }; + let lo = edge - need * step; + let hi = edge + need * step; + if lo < 0 || hi >= data.len() as isize { + eprintln!("DBG lpf OOB off={off} dir={dir} taps={taps} len={}", data.len()); + } + } + macro_rules! rd { ($k:expr) => { data[(edge + $k * step) as usize] as i32 } } + macro_rules! put { ($k:expr, $v:expr) => { data[(edge + $k * step) as usize] = $v; } } + // filter_mask (loopfilter.c:30): p3..q3 gradient limits + blimit. + let mask8 = (rd!(-4) - rd!(-3)).abs() <= limit + && (rd!(-3) - rd!(-2)).abs() <= limit + && (rd!(-2) - rd!(-1)).abs() <= limit + && (rd!(1) - rd!(0)).abs() <= limit + && (rd!(2) - rd!(1)).abs() <= limit + && (rd!(3) - rd!(2)).abs() <= limit + && 2 * (rd!(-1) - rd!(0)).abs() + (rd!(-2) - rd!(1)).abs() / 2 <= blimit; + if taps == 4 { + // lpf4 uses the p1/p0/q0/q1 form of the mask. + let mask = (rd!(-1) - rd!(0)).abs() <= limit + && (rd!(1) - rd!(0)).abs() <= limit + && 2 * (rd!(-1) - rd!(0)).abs() + (rd!(-2) - rd!(1)).abs() / 2 <= blimit; + let idx = [ + (edge - 2 * step) as usize, + (edge - step) as usize, + edge as usize, + (edge + step) as usize, + ]; + filter4(data, idx, limit, mask); + return; + } + if !mask8 { + return; + } + // flat_mask4(1, p3..q3) + let flat = (rd!(-2) - rd!(-1)).abs() <= 1 + && (rd!(1) - rd!(0)).abs() <= 1 + && (rd!(-3) - rd!(-1)).abs() <= 1 + && (rd!(2) - rd!(0)).abs() <= 1 + && (rd!(-4) - rd!(-1)).abs() <= 1 + && (rd!(3) - rd!(0)).abs() <= 1; + if taps == 8 || !flat { + if !flat { + let idx = [ + (edge - 2 * step) as usize, + (edge - step) as usize, + edge as usize, + (edge + step) as usize, + ]; + filter4(data, idx, limit, true); + return; + } + // 7-tap [1,1,1,2,1,1,1] outputs (filter8). + let (p3, p2, p1, p0, q0, q1, q2, q3) = + (rd!(-4), rd!(-3), rd!(-2), rd!(-1), rd!(0), rd!(1), rd!(2), rd!(3)); + put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8); + put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8); + put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8); + put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8); + put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8); + put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8); + return; + } + // 16-tap: flat2 via flat_mask5(1, p7..q7) + let flat2 = flat + && (rd!(-8) - rd!(-1)).abs() <= 1 + && (rd!(8) - rd!(0)).abs() <= 1 + && (rd!(-7) - rd!(-1)).abs() <= 1 + && (rd!(7) - rd!(0)).abs() <= 1 + && (rd!(-6) - rd!(-1)).abs() <= 1 + && (rd!(6) - rd!(0)).abs() <= 1 + && (rd!(-5) - rd!(-1)).abs() <= 1 + && (rd!(5) - rd!(0)).abs() <= 1; + if !flat2 { + let (p3, p2, p1, p0, q0, q1, q2, q3) = + (rd!(-4), rd!(-3), rd!(-2), rd!(-1), rd!(0), rd!(1), rd!(2), rd!(3)); + put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8); + put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8); + put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8); + put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8); + put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8); + put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8); + return; + } + // 15-tap filter [1 x 7, 2, 1 x 7] (filter16, weights verbatim). + let (p7, p6, p5, p4) = (rd!(-8), rd!(-7), rd!(-6), rd!(-5)); + let (p3, p2, p1, p0) = (rd!(-4), rd!(-3), rd!(-2), rd!(-1)); + let (q0, q1, q2, q3) = (rd!(0), rd!(1), rd!(2), rd!(3)); + let (q4, q5, q6, q7) = (rd!(4), rd!(5), rd!(6), rd!(7)); + put!(-7, ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as u8); + put!(-6, ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as u8); + put!(-5, ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as u8); + put!(-4, ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4) as u8); + put!(-3, ((p7 * 3 + p6 + p5 + p4 + p3 + p2 * 2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 + 8) >> 4) as u8); + put!(-2, ((p7 * 2 + p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 + q0 + q1 + q2 + q3 + q4 + q5 + 8) >> 4) as u8); + put!(-1, ((p7 + p6 + p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + q3 + q4 + q5 + q6 + 8) >> 4) as u8); + put!(0, ((p6 + p5 + p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + q4 + q5 + q6 + q7 + 8) >> 4) as u8); + put!(1, ((p5 + p4 + p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 + q3 + q4 + q5 + q6 + q7 * 2 + 8) >> 4) as u8); + put!(2, ((p4 + p3 + p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 + q4 + q5 + q6 + q7 * 3 + 8) >> 4) as u8); + put!(3, ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4) as u8); + put!(4, ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as u8); + put!(5, ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as u8); + put!(6, ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as u8); +} + +/// Everything the edge pass needs, recorded during decode. +pub(crate) struct LfGrids { + /// Per-4x4 luma transform size, `mi_cols*2 x mi_rows*2`. + pub tx4: Vec, + /// Per-8x8 filter level (last covering block wins, decode order). + pub level8: Vec, + /// Per-8x8 owning block: (bsize, origin mi_row, origin mi_col). + pub blk: Vec<(u8, u32, u32)>, + /// Per-8x8 BLOCK-level tx size (sub-8x8 blocks record TX_4X4). + pub otx: Vec, + pub mi_cols: usize, + pub mi_rows: usize, +} + +/// limits for a level (spec 8.8.1, `update_sharpness`). +fn limits(level: u8, sharpness: u8) -> (i32, i32) { + let mut bil = level as i32 >> ((usize::from(sharpness > 0)) + (usize::from(sharpness > 4))); + if sharpness > 0 && bil > 9 - sharpness as i32 { + bil = 9 - sharpness as i32; + } + if bil < 1 { + bil = 1; + } + (2 * (level as i32 + 2) + bil, bil) +} + +impl LfGrids { + /// Filter the frame's three planes in place. `y_w/h`, `uv_w/h` are + /// the coded (aligned) plane sizes. + pub(crate) fn filter_frame( + &self, + y: &mut [u8], + stride: usize, + u: &mut [u8], + v: &mut [u8], + uv_stride: usize, + y_w: usize, + y_h: usize, + uv_w: usize, + uv_h: usize, + sharpness: u8, + ) { + let mc2 = self.mi_cols * 2; + let mr2 = self.mi_rows * 2; + // Luma, vertical edges (4x4 column boundaries). + for r4 in 0..mr2 { + for c4 in 1..mc2 { + let cell = (r4 / 2) * self.mi_cols + c4 / 2; + let (_bsize, bor, boc) = self.blk[cell]; + let level = self.level8[cell]; + if level == 0 { + continue; + } + let tx = self.otx[cell] as usize; + let mut taps = if c4 == boc as usize * 2 { + match tx { + TX_16X16 | TX_32X32 => 16, + TX_8X8 => 8, + _ if c4 % 8 == 0 => 8, + _ => 4, + } + } else if self.tx4[r4 * mc2 + c4] as usize == TX_4X4 { + 4 + } else { + continue; + }; + // a 16-tap edge needs 8 samples on each side + if taps == 16 && (c4 * 4 < 8 || c4 * 4 + 8 > y_w) { + taps = 8; + } + let (bl, li) = limits(level, sharpness); + let off = r4 * 4 * stride + c4 * 4; + if y_w >= c4 * 4 + 4 { + lpf_edge(y, off, stride, 1, taps, bl, li); + } + } + } + // Luma, horizontal edges. + for r4 in 1..mr2 { + for c4 in 0..mc2 { + let cell = (r4 / 2) * self.mi_cols + c4 / 2; + let (_bsize, bor, _boc) = self.blk[cell]; + let level = self.level8[cell]; + if level == 0 { + continue; + } + let tx = self.otx[cell] as usize; + let mut taps = if r4 == bor as usize * 2 { + match tx { + TX_16X16 | TX_32X32 => 16, + TX_8X8 => 8, + _ if r4 % 8 == 0 => 8, + _ => 4, + } + } else if self.tx4[r4 * mc2 + c4] as usize == TX_4X4 { + 4 + } else { + continue; + }; + if taps == 16 && (r4 * 4 < 8 || r4 * 4 + 8 > y_h) { + taps = 8; + } + let (bl, li) = limits(level, sharpness); + let off = r4 * 4 * stride + c4 * 4; + if y_h >= r4 * 4 + 4 { + lpf_edge(y, off, stride, 0, taps, bl, li); + } + } + } + // Chroma (uv 4x4 grid = mi grid). + for data in [&mut *u, &mut *v] { + for r in 0..self.mi_rows { + for c in 1..self.mi_cols { + let cell = r * self.mi_cols + c; + let (bsize, _bor, boc) = self.blk[cell]; + let level = self.level8[cell]; + if level == 0 { + continue; + } + let uv_tx = uv_txsize_lookup(bsize as usize, self.otx[cell] as usize); + let taps = if bsize as usize >= 6 { + if c == boc as usize { + match uv_tx { + TX_16X16 if c * 8 >= 8 && c * 8 + 8 <= uv_w => 16, + TX_16X16 => 8, + TX_8X8 => 8, + _ if c % 4 == 0 => 8, + _ => 4, + } + } else if uv_tx == TX_4X4 { + 4 + } else { + continue; + } + } else if c % 2 == 0 && r % 2 == 0 { + if c % 4 == 0 { 8 } else { 4 } + } else { + continue; + }; + let (bl, li) = limits(level, sharpness); + let off = r * 8 * uv_stride + c * 8; + if uv_w >= c * 8 + 8 { + lpf_edge(data, off, uv_stride, 1, taps, bl, li); + } + } + } + } + } +} diff --git a/crates/ec-vp9/src/modes.rs b/crates/ec-vp9/src/modes.rs new file mode 100644 index 00000000..1ef9289e --- /dev/null +++ b/crates/ec-vp9/src/modes.rs @@ -0,0 +1,256 @@ +//! Partition coding and intra-frame mode info (spec 6.3.4/6.3.5, +//! libvpx `vp9_decodeframe.c decode_partition` + `vp9_decodemv.c +//! read_intra_frame_mode_info`). + +use crate::bool::BoolDecoder; +use crate::tables::*; + +/// One block's parsed prediction record (`MODE_INFO`). +#[derive(Clone, Default)] +pub(crate) struct MiInfo { + pub sb_type: usize, + pub segment: u8, + pub skip: bool, + pub tx_size: usize, + pub mode: u8, + pub uv_mode: u8, + /// Per-4x4 sub-block y modes, valid when `sb_type < 3` (BLOCK_8X8). + pub bmi: [u8; 4], +} + +/// The mode-info grid and the partition contexts of one tile pass. +pub(crate) struct MiState { + pub mi_cols: usize, + pub mi_rows: usize, + /// `mi_row * mi_cols + mi_col`; every cell a block covers holds a + /// clone of its record (libvpx shares the pointer). + pub grid: Vec>, + /// `above_seg_context`, one byte per 8x8 column (tile-scoped). + pub above_seg: Vec, + /// `left_seg_context`, one byte per 8x8 row (reset per SB row). + pub left_seg: [u8; 32], +} + +impl MiState { + pub(crate) fn new(mi_cols: usize, mi_rows: usize) -> Self { + MiState { + mi_cols, + mi_rows, + grid: vec![None; mi_cols * mi_rows], + above_seg: vec![0; mi_cols], + left_seg: [0; 32], + } + } + + fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> { + if row > tile_row_start { + self.grid[(row - 1) * self.mi_cols + col].as_ref() + } else { + None + } + } + + fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> { + if col > tile_col_start { + self.grid[row * self.mi_cols + col - 1].as_ref() + } else { + None + } + } + + /// `dec_partition_plane_context`. + pub(crate) fn partition_ctx(&self, row: usize, col: usize, bsl: u32) -> usize { + let above = (self.above_seg[col] >> bsl) & 1; + let left = (self.left_seg[row & 31] >> bsl) & 1; + (left * 2 + above) as usize + (bsl as usize) * 4 + } + + /// `dec_update_partition_context`; `partition_context_lookup[subsize]`. + pub(crate) fn update_partition_ctx(&mut self, row: usize, col: usize, subsize: usize, bw: usize) { + // (above, left) per BLOCK_SIZE, common_data.c:230. + const LOOKUP: [(u8, u8); 13] = [ + (15, 15), (15, 14), (14, 15), (14, 14), (14, 12), (12, 14), (12, 12), + (12, 8), (8, 12), (8, 8), (8, 0), (0, 8), (0, 0), + ]; + let (a, l) = LOOKUP[subsize]; + self.above_seg[col..col + bw].fill(a); + self.left_seg[row & 31..(row & 31) + bw].fill(l); + } +} + +/// `read_partition` (decodeframe.c:1195). +fn read_partition( + r: &mut BoolDecoder, + st: &MiState, + partition_probs: &[[u8; 3]; 16], + row: usize, + col: usize, + has_rows: bool, + has_cols: bool, + bsl: u32, +) -> crate::Result { + let ctx = st.partition_ctx(row, col, bsl); + let probs = &partition_probs[ctx]; + if has_rows && has_cols { + Ok(r.read_tree(&PARTITION_TREE, probs)) + } else if !has_rows && has_cols { + Ok(if r.read_bool(probs[1]) { + 3 /* SPLIT */ + } else { + 1 /* HORZ */ + }) + } else if has_rows && !has_cols { + Ok(if r.read_bool(probs[2]) { + 3 /* SPLIT */ + } else { + 2 /* VERT */ + }) + } else { + Ok(3) + } +} + +/// `read_intra_mode_kf` + `read_intra_frame_mode_info` (decodemv.c). +pub(crate) fn read_intra_frame_mode_info( + r: &mut BoolDecoder, + st: &mut MiState, + seg: &ec_vp9_syntax::SegmentationParams, + partition_probs: &[[u8; 3]; 16], + row: usize, + col: usize, + sb_type: usize, + x_mis: usize, + y_mis: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + skip_probs: &[u8; 3], +) -> crate::Result { + let above_mi = st.above_mi(row, col, tile_row_start).cloned(); + let left_mi = st.left_mi(row, col, tile_col_start).cloned(); + + // read_intra_segment_id: keyframes have no temporal prediction; a + // map that is not updated keeps the previous id, which for a + // keyframe's fresh map is 0 (setup_past_independence cleared it). + let segment = if seg.enabled && seg.update_map { + r.read_tree(&SEGMENT_TREE, &seg.tree_probs) + } else { + 0 + }; + + // read_skip + let skip_ctx = above_mi.as_ref().map_or(0, |m| u32::from(m.skip)) + + left_mi.as_ref().map_or(0, |u| u32::from(u.skip)); + let skip_ctx = skip_ctx as usize; + let seg_skip = seg.enabled + && seg.feature_enabled.get(segment as usize).is_some_and(|f| f[3]); + let skip = if seg_skip { + true + } else { + r.read_bool(skip_probs[skip_ctx]) + }; + + // read_tx_size + let max_tx = MAX_TXSIZE_LOOKUP[sb_type] as usize; + let tx_size = if tx_mode == TX_MODE_SELECT && sb_type >= 3 { + // read_selected_tx_size: ctx from above/left tx sizes. + let ctx = { + let a = above_mi.as_ref().map_or(max_tx, |m| { + if m.skip { + max_tx + } else { + m.tx_size + } + }); + let l = left_mi.as_ref().map_or(a, |m| if m.skip { max_tx } else { m.tx_size }); + usize::from(a + l > max_tx) + }; + let probs: &[u8] = match max_tx { + 1 => &TX_P8X8_PROB[ctx..ctx + 1], + 2 => &TX_P16X16_PROB[ctx * 2..ctx * 2 + 2], + _ => &TX_P32X32_PROB[ctx * 3..ctx * 3 + 3], + }; + let mut tx = r.read_bool(probs[0]) as usize; + if tx != TX_4X4 && max_tx >= TX_16X16 { + tx += r.read_bool(probs[1]) as usize; + if tx != TX_8X8 && max_tx >= TX_32X32 { + tx += r.read_bool(probs[2]) as usize; + } + } + tx + } else { + max_tx.min(TX_MODE_TO_BIGGEST_TX_SIZE[tx_mode as usize]) + }; + + // y mode(s), per sub-block for sub-8x8 blocks + let above_pair: Option<(usize, [u8; 4], u8)> = + above_mi.as_ref().map(|m| (m.sb_type, m.bmi, m.mode)); + let left_pair: Option<(usize, [u8; 4], u8)> = + left_mi.as_ref().map(|m| (m.sb_type, m.bmi, m.mode)); + let mut mi = MiInfo { + sb_type, + segment, + skip, + tx_size, + mode: DC_PRED, + uv_mode: DC_PRED, + bmi: [DC_PRED; 4], + }; + match sb_type { + 0 => { + // BLOCK_4X4 + for i in 0..4 { + let a = above_block_mode(&mi.bmi, above_pair, i); + let l = left_block_mode(&mi.bmi, left_pair, i); + mi.bmi[i] = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a, l)); + } + mi.mode = mi.bmi[3]; + } + 1 => { + // BLOCK_4X8 + let a0 = above_block_mode(&mi.bmi, above_pair, 0); + let l0 = left_block_mode(&mi.bmi, left_pair, 0); + let m0 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a0, l0)); + let a1 = above_block_mode(&mi.bmi, above_pair, 1); + let l1 = left_block_mode(&mi.bmi, left_pair, 1); + let m1 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a1, l1)); + mi.bmi[0] = m0; + mi.bmi[2] = m0; + mi.bmi[1] = m1; + mi.bmi[3] = m1; + mi.mode = m1; + } + 2 => { + // BLOCK_8X4 + let a0 = above_block_mode(&mi.bmi, above_pair, 0); + let l0 = left_block_mode(&mi.bmi, left_pair, 0); + let m0 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a0, l0)); + let a2 = above_block_mode(&mi.bmi, above_pair, 2); + let l2 = left_block_mode(&mi.bmi, left_pair, 2); + let m2 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a2, l2)); + mi.bmi[0] = m0; + mi.bmi[1] = m0; + mi.bmi[2] = m2; + mi.bmi[3] = m2; + mi.mode = m2; + } + _ => { + let a = above_block_mode(&mi.bmi, above_pair, 0); + let l = left_block_mode(&mi.bmi, left_pair, 0); + mi.mode = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a, l)); + } + } + // uv mode: kf_uv table indexed by y mode (decodemv.c read_intra_mode_uv + // for keyframes uses vp9_kf_uv_mode_prob). + mi.uv_mode = r.read_tree(&UV_MODE_TREE, &kf_uv_probs(mi.mode)); + Ok(mi) +} + +/// `vp9_kf_uv_mode_prob` reshaped per y mode. +pub(crate) fn kf_uv_probs(mode: u8) -> [u8; 9] { + let mut out = [0u8; 9]; + let base = mode as usize * 9; + out.copy_from_slice(&KF_UV_MODE_PROB[base..base + 9]); + out +} + diff --git a/crates/ec-vp9/src/stream.rs b/crates/ec-vp9/src/stream.rs new file mode 100644 index 00000000..9e0ca0ff --- /dev/null +++ b/crates/ec-vp9/src/stream.rs @@ -0,0 +1,99 @@ +//! Whole-stream decoding: an IVF file in, decoded pictures out. +//! +//! VP9 frames are not self-delimiting — a frame's total size only the +//! container knows (and one IVF chunk may hold a superframe with hidden +//! ALTREF frames) — so the whole-stream API takes the stream in the +//! container VP9 actually ships in: IVF (`DKIF`/`VP90`). Single frames +//! or chunks from any other demuxer feed +//! [`crate::decode::Decoder::decode`] directly, which splits superframes +//! itself. +//! +//! The shape mirrors `ec-vp8`'s: [`decode_stream`] collects every shown +//! picture into a `Vec`, and [`decode_stream_with`] hands each picture +//! to a sink the moment it exists. + +use crate::decode::{Decoder, Picture}; +use crate::tables::ensure; +use crate::{Error, Result}; + +/// The IVF file magic, `DKIF`. +const DKIF: &[u8; 4] = b"DKIF"; +/// The fourcc for VP9 video (`VP90`). +const VP90: &[u8; 4] = b"VP90"; + +/// One demuxed IVF frame: presentation timestamp plus the compressed +/// VP9 payload (possibly a superframe chunk). +struct IvfFrame<'a> { + pts: u64, + data: &'a [u8], +} + +/// Split an IVF byte stream into its frames, validating the container +/// envelope as [`Error`]s rather than panics. +fn demux(data: &[u8]) -> Result>> { + let mut frames = Vec::new(); + let err = |what: &str| Error::corrupt(format!("ivf: {what}")); + ensure(data.len() >= 32, "truncated IVF header")?; + if &data[0..4] != DKIF { + return Err(err("not DKIF")); + } + if &data[8..12] != VP90 { + return Err(err("fourcc is not VP90")); + } + let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize; + let mut pos = hdr_len.max(32); + while pos + 12 <= data.len() { + let sz = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize; + let pts = u64::from_le_bytes(data[pos + 4..pos + 12].try_into().unwrap()); + pos += 12; + if sz == 0 { + return Err(err("zero-length frame")); + } + if pos + sz > data.len() { + return Err(err("truncated frame payload")); + } + frames.push(IvfFrame { + pts, + data: &data[pos..pos + sz], + }); + pos += sz; + } + Ok(frames) +} + +/// Decode every shown frame in an IVF VP9 stream, in presentation order. +/// +/// The stream must start with a key frame; hidden frames +/// (`show_frame == 0`) update the reference buffers but are not part of +/// the output. +/// +/// # Errors +/// As [`demux`] reports for the container, [`Decoder::decode`] for the +/// frames, plus `vp9 inter` refusals once a lane-ineligible frame shows +/// up. +pub fn decode_stream(data: &[u8]) -> Result> { + let mut out = Vec::new(); + decode_stream_with(data, |pic, _, _| { + out.push(pic.clone()); + Ok(()) + })?; + Ok(out) +} + +/// Streaming form of [`decode_stream`]: hand every shown picture to +/// `sink` the moment it exists. `sink` receives the picture, the +/// decode-order index of the IVF chunk it came from, and the IVF +/// presentation timestamp. An `Err` from `sink` aborts the decode. +pub fn decode_stream_with( + data: &[u8], + mut sink: impl FnMut(&Picture, usize, u64) -> Result<()>, +) -> Result<()> { + let frames = demux(data)?; + let mut decoder = Decoder::new(); + for (i, frame) in frames.iter().enumerate() { + if let Some(pic) = decoder.decode(frame.data)? { + sink(&pic, i, frame.pts)?; + } + } + Ok(()) +} diff --git a/crates/ec-vp9/src/tables/gen_tables.rs b/crates/ec-vp9/src/tables/gen_tables.rs new file mode 100644 index 00000000..e3385605 --- /dev/null +++ b/crates/ec-vp9/src/tables/gen_tables.rs @@ -0,0 +1,66 @@ +//! Constant tables transcribed verbatim from the libvpx reference +//! implementation (the normative VP9 bitstream tables), extracted +//! mechanically from libvpx v1.15.0. Test-oracle provenance; this +//! crate never links libvpx at runtime. +//! +//! Band 0 of the coefficient-probability tables holds only 3 contexts +//! in libvpx (ragged C arrays); it is padded to 6 here with zeros that +//! are never read (band 0 context = sub-block has-coef flags, 0..=2). +//! BLOCK_INVALID (255) survives in SS_SIZE_LOOKUP where a 4:2:0 +//! subsampled block size does not exist. +#![allow(dead_code)] + +pub(crate) const COEF_CON_TREE: [i8; 16] = [2, 6, -2, 4, -3, -4, 8, 10, -5, -6, 12, 14, -7, -8, -9, -10]; +pub(crate) const CAT1_PROB: [u8; 1] = [159]; +pub(crate) const CAT2_PROB: [u8; 2] = [165, 145]; +pub(crate) const CAT3_PROB: [u8; 3] = [173, 148, 140]; +pub(crate) const CAT4_PROB: [u8; 4] = [176, 155, 140, 135]; +pub(crate) const CAT5_PROB: [u8; 5] = [180, 157, 141, 134, 130]; +pub(crate) const CAT6_PROB: [u8; 14] = [254, 254, 254, 252, 249, 243, 230, 196, 177, 153, 140, 133, 130, 129]; +pub(crate) const COEFBAND_TRANS_8X8PLUS: [u8; 1024] = [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]; +pub(crate) const COEFBAND_TRANS_4X4: [u8; 16] = [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5]; +pub(crate) const PT_ENERGY_CLASS: [u8; 12] = [0, 1, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5]; +pub(crate) const PARETO8_FULL: [u8; 2040] = [3, 86, 128, 6, 86, 23, 88, 29, 6, 86, 128, 11, 87, 42, 91, 52, 9, 86, 129, 17, 88, 61, 94, 76, 12, 86, 129, 22, 88, 77, 97, 93, 15, 87, 129, 28, 89, 93, 100, 110, 17, 87, 129, 33, 90, 105, 103, 123, 20, 88, 130, 38, 91, 118, 106, 136, 23, 88, 130, 43, 91, 128, 108, 146, 26, 89, 131, 48, 92, 139, 111, 156, 28, 89, 131, 53, 93, 147, 114, 163, 31, 90, 131, 58, 94, 156, 117, 171, 34, 90, 131, 62, 94, 163, 119, 177, 37, 90, 132, 66, 95, 171, 122, 184, 39, 90, 132, 70, 96, 177, 124, 189, 42, 91, 132, 75, 97, 183, 127, 194, 44, 91, 132, 79, 97, 188, 129, 198, 47, 92, 133, 83, 98, 193, 132, 202, 49, 92, 133, 86, 99, 197, 134, 205, 52, 93, 133, 90, 100, 201, 137, 208, 54, 93, 133, 94, 100, 204, 139, 211, 57, 94, 134, 98, 101, 208, 142, 214, 59, 94, 134, 101, 102, 211, 144, 216, 62, 94, 135, 105, 103, 214, 146, 218, 64, 94, 135, 108, 103, 216, 148, 220, 66, 95, 135, 111, 104, 219, 151, 222, 68, 95, 135, 114, 105, 221, 153, 223, 71, 96, 136, 117, 106, 224, 155, 225, 73, 96, 136, 120, 106, 225, 157, 226, 76, 97, 136, 123, 107, 227, 159, 228, 78, 97, 136, 126, 108, 229, 160, 229, 80, 98, 137, 129, 109, 231, 162, 231, 82, 98, 137, 131, 109, 232, 164, 232, 84, 98, 138, 134, 110, 234, 166, 233, 86, 98, 138, 137, 111, 235, 168, 234, 89, 99, 138, 140, 112, 236, 170, 235, 91, 99, 138, 142, 112, 237, 171, 235, 93, 100, 139, 145, 113, 238, 173, 236, 95, 100, 139, 147, 114, 239, 174, 237, 97, 101, 140, 149, 115, 240, 176, 238, 99, 101, 140, 151, 115, 241, 177, 238, 101, 102, 140, 154, 116, 242, 179, 239, 103, 102, 140, 156, 117, 242, 180, 239, 105, 103, 141, 158, 118, 243, 182, 240, 107, 103, 141, 160, 118, 243, 183, 240, 109, 104, 141, 162, 119, 244, 185, 241, 111, 104, 141, 164, 119, 244, 186, 241, 113, 104, 142, 166, 120, 245, 187, 242, 114, 104, 142, 168, 121, 245, 188, 242, 116, 105, 143, 170, 122, 246, 190, 243, 118, 105, 143, 171, 122, 246, 191, 243, 120, 106, 143, 173, 123, 247, 192, 244, 121, 106, 143, 175, 124, 247, 193, 244, 123, 107, 144, 177, 125, 248, 195, 244, 125, 107, 144, 178, 125, 248, 196, 244, 127, 108, 145, 180, 126, 249, 197, 245, 128, 108, 145, 181, 127, 249, 198, 245, 130, 109, 145, 183, 128, 249, 199, 245, 132, 109, 145, 184, 128, 249, 200, 245, 134, 110, 146, 186, 129, 250, 201, 246, 135, 110, 146, 187, 130, 250, 202, 246, 137, 111, 147, 189, 131, 251, 203, 246, 138, 111, 147, 190, 131, 251, 204, 246, 140, 112, 147, 192, 132, 251, 205, 247, 141, 112, 147, 193, 132, 251, 206, 247, 143, 113, 148, 194, 133, 251, 207, 247, 144, 113, 148, 195, 134, 251, 207, 247, 146, 114, 149, 197, 135, 252, 208, 248, 147, 114, 149, 198, 135, 252, 209, 248, 149, 115, 149, 199, 136, 252, 210, 248, 150, 115, 149, 200, 137, 252, 210, 248, 152, 115, 150, 201, 138, 252, 211, 248, 153, 115, 150, 202, 138, 252, 212, 248, 155, 116, 151, 204, 139, 253, 213, 249, 156, 116, 151, 205, 139, 253, 213, 249, 158, 117, 151, 206, 140, 253, 214, 249, 159, 117, 151, 207, 141, 253, 215, 249, 161, 118, 152, 208, 142, 253, 216, 249, 162, 118, 152, 209, 142, 253, 216, 249, 163, 119, 153, 210, 143, 253, 217, 249, 164, 119, 153, 211, 143, 253, 217, 249, 166, 120, 153, 212, 144, 254, 218, 250, 167, 120, 153, 212, 145, 254, 219, 250, 168, 121, 154, 213, 146, 254, 220, 250, 169, 121, 154, 214, 146, 254, 220, 250, 171, 122, 155, 215, 147, 254, 221, 250, 172, 122, 155, 216, 147, 254, 221, 250, 173, 123, 155, 217, 148, 254, 222, 250, 174, 123, 155, 217, 149, 254, 222, 250, 176, 124, 156, 218, 150, 254, 223, 250, 177, 124, 156, 219, 150, 254, 223, 250, 178, 125, 157, 220, 151, 254, 224, 251, 179, 125, 157, 220, 151, 254, 224, 251, 180, 126, 157, 221, 152, 254, 225, 251, 181, 126, 157, 221, 152, 254, 225, 251, 183, 127, 158, 222, 153, 254, 226, 251, 184, 127, 158, 223, 154, 254, 226, 251, 185, 128, 159, 224, 155, 255, 227, 251, 186, 128, 159, 224, 155, 255, 227, 251, 187, 129, 160, 225, 156, 255, 228, 251, 188, 130, 160, 225, 156, 255, 228, 251, 189, 131, 160, 226, 157, 255, 228, 251, 190, 131, 160, 226, 158, 255, 228, 251, 191, 132, 161, 227, 159, 255, 229, 251, 192, 132, 161, 227, 159, 255, 229, 251, 193, 133, 162, 228, 160, 255, 230, 252, 194, 133, 162, 229, 160, 255, 230, 252, 195, 134, 163, 230, 161, 255, 231, 252, 196, 134, 163, 230, 161, 255, 231, 252, 197, 135, 163, 231, 162, 255, 231, 252, 198, 135, 163, 231, 162, 255, 231, 252, 199, 136, 164, 232, 163, 255, 232, 252, 200, 136, 164, 232, 164, 255, 232, 252, 201, 137, 165, 233, 165, 255, 233, 252, 201, 137, 165, 233, 165, 255, 233, 252, 202, 138, 166, 233, 166, 255, 233, 252, 203, 138, 166, 233, 166, 255, 233, 252, 204, 139, 166, 234, 167, 255, 234, 252, 205, 139, 166, 234, 167, 255, 234, 252, 206, 140, 167, 235, 168, 255, 235, 252, 206, 140, 167, 235, 168, 255, 235, 252, 207, 141, 168, 236, 169, 255, 235, 252, 208, 141, 168, 236, 170, 255, 235, 252, 209, 142, 169, 237, 171, 255, 236, 252, 209, 143, 169, 237, 171, 255, 236, 252, 210, 144, 169, 237, 172, 255, 236, 252, 211, 144, 169, 237, 172, 255, 236, 252, 212, 145, 170, 238, 173, 255, 237, 252, 213, 145, 170, 238, 173, 255, 237, 252, 214, 146, 171, 239, 174, 255, 237, 253, 214, 146, 171, 239, 174, 255, 237, 253, 215, 147, 172, 240, 175, 255, 238, 253, 215, 147, 172, 240, 175, 255, 238, 253, 216, 148, 173, 240, 176, 255, 238, 253, 217, 148, 173, 240, 176, 255, 238, 253, 218, 149, 173, 241, 177, 255, 239, 253, 218, 149, 173, 241, 178, 255, 239, 253, 219, 150, 174, 241, 179, 255, 239, 253, 219, 151, 174, 241, 179, 255, 239, 253, 220, 152, 175, 242, 180, 255, 240, 253, 221, 152, 175, 242, 180, 255, 240, 253, 222, 153, 176, 242, 181, 255, 240, 253, 222, 153, 176, 242, 181, 255, 240, 253, 223, 154, 177, 243, 182, 255, 240, 253, 223, 154, 177, 243, 182, 255, 240, 253, 224, 155, 178, 244, 183, 255, 241, 253, 224, 155, 178, 244, 183, 255, 241, 253, 225, 156, 178, 244, 184, 255, 241, 253, 225, 157, 178, 244, 184, 255, 241, 253, 226, 158, 179, 244, 185, 255, 242, 253, 227, 158, 179, 244, 185, 255, 242, 253, 228, 159, 180, 245, 186, 255, 242, 253, 228, 159, 180, 245, 186, 255, 242, 253, 229, 160, 181, 245, 187, 255, 242, 253, 229, 160, 181, 245, 187, 255, 242, 253, 230, 161, 182, 246, 188, 255, 243, 253, 230, 162, 182, 246, 188, 255, 243, 253, 231, 163, 183, 246, 189, 255, 243, 253, 231, 163, 183, 246, 189, 255, 243, 253, 232, 164, 184, 247, 190, 255, 243, 253, 232, 164, 184, 247, 190, 255, 243, 253, 233, 165, 185, 247, 191, 255, 244, 253, 233, 165, 185, 247, 191, 255, 244, 253, 234, 166, 185, 247, 192, 255, 244, 253, 234, 167, 185, 247, 192, 255, 244, 253, 235, 168, 186, 248, 193, 255, 244, 253, 235, 168, 186, 248, 193, 255, 244, 253, 236, 169, 187, 248, 194, 255, 244, 253, 236, 169, 187, 248, 194, 255, 244, 253, 236, 170, 188, 248, 195, 255, 245, 253, 236, 170, 188, 248, 195, 255, 245, 253, 237, 171, 189, 249, 196, 255, 245, 254, 237, 172, 189, 249, 196, 255, 245, 254, 238, 173, 190, 249, 197, 255, 245, 254, 238, 173, 190, 249, 197, 255, 245, 254, 239, 174, 191, 249, 198, 255, 245, 254, 239, 174, 191, 249, 198, 255, 245, 254, 240, 175, 192, 249, 199, 255, 246, 254, 240, 176, 192, 249, 199, 255, 246, 254, 240, 177, 193, 250, 200, 255, 246, 254, 240, 177, 193, 250, 200, 255, 246, 254, 241, 178, 194, 250, 201, 255, 246, 254, 241, 178, 194, 250, 201, 255, 246, 254, 242, 179, 195, 250, 202, 255, 246, 254, 242, 180, 195, 250, 202, 255, 246, 254, 242, 181, 196, 250, 203, 255, 247, 254, 242, 181, 196, 250, 203, 255, 247, 254, 243, 182, 197, 251, 204, 255, 247, 254, 243, 183, 197, 251, 204, 255, 247, 254, 244, 184, 198, 251, 205, 255, 247, 254, 244, 184, 198, 251, 205, 255, 247, 254, 244, 185, 199, 251, 206, 255, 247, 254, 244, 185, 199, 251, 206, 255, 247, 254, 245, 186, 200, 251, 207, 255, 247, 254, 245, 187, 200, 251, 207, 255, 247, 254, 246, 188, 201, 252, 207, 255, 248, 254, 246, 188, 201, 252, 207, 255, 248, 254, 246, 189, 202, 252, 208, 255, 248, 254, 246, 190, 202, 252, 208, 255, 248, 254, 247, 191, 203, 252, 209, 255, 248, 254, 247, 191, 203, 252, 209, 255, 248, 254, 247, 192, 204, 252, 210, 255, 248, 254, 247, 193, 204, 252, 210, 255, 248, 254, 248, 194, 205, 252, 211, 255, 248, 254, 248, 194, 205, 252, 211, 255, 248, 254, 248, 195, 206, 252, 212, 255, 249, 254, 248, 196, 206, 252, 212, 255, 249, 254, 249, 197, 207, 253, 213, 255, 249, 254, 249, 197, 207, 253, 213, 255, 249, 254, 249, 198, 208, 253, 214, 255, 249, 254, 249, 199, 209, 253, 214, 255, 249, 254, 250, 200, 210, 253, 215, 255, 249, 254, 250, 200, 210, 253, 215, 255, 249, 254, 250, 201, 211, 253, 215, 255, 249, 254, 250, 202, 211, 253, 215, 255, 249, 254, 250, 203, 212, 253, 216, 255, 249, 254, 250, 203, 212, 253, 216, 255, 249, 254, 251, 204, 213, 253, 217, 255, 250, 254, 251, 205, 213, 253, 217, 255, 250, 254, 251, 206, 214, 254, 218, 255, 250, 254, 251, 206, 215, 254, 218, 255, 250, 254, 252, 207, 216, 254, 219, 255, 250, 254, 252, 208, 216, 254, 219, 255, 250, 254, 252, 209, 217, 254, 220, 255, 250, 254, 252, 210, 217, 254, 220, 255, 250, 254, 252, 211, 218, 254, 221, 255, 250, 254, 252, 212, 218, 254, 221, 255, 250, 254, 253, 213, 219, 254, 222, 255, 250, 254, 253, 213, 220, 254, 222, 255, 250, 254, 253, 214, 221, 254, 223, 255, 250, 254, 253, 215, 221, 254, 223, 255, 250, 254, 253, 216, 222, 254, 224, 255, 251, 254, 253, 217, 223, 254, 224, 255, 251, 254, 253, 218, 224, 254, 225, 255, 251, 254, 253, 219, 224, 254, 225, 255, 251, 254, 254, 220, 225, 254, 225, 255, 251, 254, 254, 221, 226, 254, 225, 255, 251, 254, 254, 222, 227, 255, 226, 255, 251, 254, 254, 223, 227, 255, 226, 255, 251, 254, 254, 224, 228, 255, 227, 255, 251, 254, 254, 225, 229, 255, 227, 255, 251, 254, 254, 226, 230, 255, 228, 255, 251, 254, 254, 227, 230, 255, 229, 255, 251, 254, 255, 228, 231, 255, 230, 255, 251, 254, 255, 229, 232, 255, 230, 255, 251, 254, 255, 230, 233, 255, 231, 255, 252, 254, 255, 231, 234, 255, 231, 255, 252, 254, 255, 232, 235, 255, 232, 255, 252, 254, 255, 233, 236, 255, 232, 255, 252, 254, 255, 235, 237, 255, 233, 255, 252, 254, 255, 236, 238, 255, 234, 255, 252, 254, 255, 238, 240, 255, 235, 255, 252, 255, 255, 239, 241, 255, 235, 255, 252, 254, 255, 241, 243, 255, 236, 255, 252, 254, 255, 243, 245, 255, 237, 255, 252, 254, 255, 246, 247, 255, 239, 255, 253, 255]; +pub(crate) const DEFAULT_SCAN_4X4: [i16; 16] = [0, 4, 1, 5, 8, 2, 12, 9, 3, 6, 13, 10, 7, 14, 11, 15]; +pub(crate) const COL_SCAN_4X4: [i16; 16] = [0, 4, 8, 1, 12, 5, 9, 2, 13, 6, 10, 3, 7, 14, 11, 15]; +pub(crate) const ROW_SCAN_4X4: [i16; 16] = [0, 1, 4, 2, 5, 3, 6, 8, 9, 7, 12, 10, 13, 11, 14, 15]; +pub(crate) const DEFAULT_SCAN_8X8: [i16; 64] = [0, 8, 1, 16, 9, 2, 17, 24, 10, 3, 18, 25, 32, 11, 4, 26, 33, 19, 40, 12, 34, 27, 5, 41, 20, 48, 13, 35, 42, 28, 21, 6, 49, 56, 36, 43, 29, 7, 14, 50, 57, 44, 22, 37, 15, 51, 58, 30, 45, 23, 52, 59, 38, 31, 60, 53, 46, 39, 61, 54, 47, 62, 55, 63]; +pub(crate) const COL_SCAN_8X8: [i16; 64] = [0, 8, 16, 1, 24, 9, 32, 17, 2, 40, 25, 10, 33, 18, 48, 3, 26, 41, 11, 56, 19, 34, 4, 49, 27, 42, 12, 35, 20, 57, 50, 28, 5, 43, 13, 36, 58, 51, 21, 44, 6, 29, 59, 37, 14, 52, 22, 7, 45, 60, 30, 15, 38, 53, 23, 46, 31, 61, 39, 54, 47, 62, 55, 63]; +pub(crate) const ROW_SCAN_8X8: [i16; 64] = [0, 1, 2, 8, 9, 3, 16, 10, 4, 17, 11, 24, 5, 18, 25, 12, 19, 26, 32, 6, 13, 20, 33, 27, 7, 34, 40, 21, 28, 41, 14, 35, 48, 42, 29, 36, 49, 22, 43, 15, 56, 37, 50, 44, 30, 57, 23, 51, 58, 45, 38, 52, 31, 59, 53, 46, 60, 39, 61, 47, 54, 55, 62, 63]; +pub(crate) const DEFAULT_SCAN_16X16: [i16; 256] = [0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 64, 34, 49, 19, 65, 80, 50, 4, 35, 66, 20, 81, 96, 51, 5, 36, 82, 97, 67, 112, 21, 52, 98, 37, 83, 113, 6, 68, 128, 53, 22, 99, 114, 84, 7, 129, 38, 69, 100, 115, 144, 130, 85, 54, 23, 8, 145, 39, 70, 116, 101, 131, 160, 146, 55, 86, 24, 71, 132, 117, 161, 40, 9, 102, 147, 176, 162, 87, 56, 25, 133, 118, 177, 148, 72, 103, 41, 163, 10, 192, 178, 88, 57, 134, 149, 119, 26, 164, 73, 104, 193, 42, 179, 208, 11, 135, 89, 165, 120, 150, 58, 194, 180, 27, 74, 209, 105, 151, 136, 43, 90, 224, 166, 195, 181, 121, 210, 59, 12, 152, 106, 167, 196, 75, 137, 225, 211, 240, 182, 122, 91, 28, 197, 13, 226, 168, 183, 153, 44, 212, 138, 107, 241, 60, 29, 123, 198, 184, 227, 169, 242, 76, 213, 154, 45, 92, 14, 199, 139, 61, 228, 214, 170, 185, 243, 108, 77, 155, 30, 15, 200, 229, 124, 215, 244, 93, 46, 186, 171, 201, 109, 140, 230, 62, 216, 245, 31, 125, 78, 156, 231, 47, 187, 202, 217, 94, 246, 141, 63, 232, 172, 110, 247, 157, 79, 218, 203, 126, 233, 188, 248, 95, 173, 142, 219, 111, 249, 234, 158, 127, 189, 204, 250, 235, 143, 174, 220, 205, 159, 251, 190, 221, 175, 236, 237, 191, 206, 252, 222, 253, 207, 238, 223, 254, 239, 255]; +pub(crate) const COL_SCAN_16X16: [i16; 256] = [0, 16, 32, 48, 1, 64, 17, 80, 33, 96, 49, 2, 65, 112, 18, 81, 34, 128, 50, 97, 3, 66, 144, 19, 113, 35, 82, 160, 98, 51, 129, 4, 67, 176, 20, 114, 145, 83, 36, 99, 130, 52, 192, 5, 161, 68, 115, 21, 146, 84, 208, 177, 37, 131, 100, 53, 162, 224, 69, 6, 116, 193, 147, 85, 22, 240, 132, 38, 178, 101, 163, 54, 209, 117, 70, 7, 148, 194, 86, 179, 225, 23, 133, 39, 164, 8, 102, 210, 241, 55, 195, 118, 149, 71, 180, 24, 87, 226, 134, 165, 211, 40, 103, 56, 72, 150, 196, 242, 119, 9, 181, 227, 88, 166, 25, 135, 41, 104, 212, 57, 151, 197, 120, 73, 243, 182, 136, 167, 213, 89, 10, 228, 105, 152, 198, 26, 42, 121, 183, 244, 168, 58, 137, 229, 74, 214, 90, 153, 199, 184, 11, 106, 245, 27, 122, 230, 169, 43, 215, 59, 200, 138, 185, 246, 75, 12, 91, 154, 216, 231, 107, 28, 44, 201, 123, 170, 60, 247, 232, 76, 139, 13, 92, 217, 186, 248, 155, 108, 29, 124, 45, 202, 233, 171, 61, 14, 77, 140, 15, 249, 93, 30, 187, 156, 218, 46, 109, 125, 62, 172, 78, 203, 31, 141, 234, 94, 47, 188, 63, 157, 110, 250, 219, 79, 126, 204, 173, 142, 95, 189, 111, 235, 158, 220, 251, 127, 174, 143, 205, 236, 159, 190, 221, 252, 175, 206, 237, 191, 253, 222, 238, 207, 254, 223, 239, 255]; +pub(crate) const ROW_SCAN_16X16: [i16; 256] = [0, 1, 2, 16, 3, 17, 4, 18, 32, 5, 33, 19, 6, 34, 48, 20, 49, 7, 35, 21, 50, 64, 8, 36, 65, 22, 51, 37, 80, 9, 66, 52, 23, 38, 81, 67, 10, 53, 24, 82, 68, 96, 39, 11, 54, 83, 97, 69, 25, 98, 84, 40, 112, 55, 12, 70, 99, 113, 85, 26, 41, 56, 114, 100, 13, 71, 128, 86, 27, 115, 101, 129, 42, 57, 72, 116, 14, 87, 130, 102, 144, 73, 131, 117, 28, 58, 15, 88, 43, 145, 103, 132, 146, 118, 74, 160, 89, 133, 104, 29, 59, 147, 119, 44, 161, 148, 90, 105, 134, 162, 120, 176, 75, 135, 149, 30, 60, 163, 177, 45, 121, 91, 106, 164, 178, 150, 192, 136, 165, 179, 31, 151, 193, 76, 122, 61, 137, 194, 107, 152, 180, 208, 46, 166, 167, 195, 92, 181, 138, 209, 123, 153, 224, 196, 77, 168, 210, 182, 240, 108, 197, 62, 154, 225, 183, 169, 211, 47, 139, 93, 184, 226, 212, 241, 198, 170, 124, 155, 199, 78, 213, 185, 109, 227, 200, 63, 228, 242, 140, 214, 171, 186, 156, 229, 243, 125, 94, 201, 244, 215, 216, 230, 141, 187, 202, 79, 172, 110, 157, 245, 217, 231, 95, 246, 232, 126, 203, 247, 233, 173, 218, 142, 111, 158, 188, 248, 127, 234, 219, 249, 189, 204, 143, 174, 159, 250, 235, 205, 220, 175, 190, 251, 221, 191, 206, 236, 207, 237, 252, 222, 253, 223, 238, 239, 254, 255]; +pub(crate) const DEFAULT_SCAN_32X32: [i16; 1024] = [0, 32, 1, 64, 33, 2, 96, 65, 34, 128, 3, 97, 66, 160, 129, 35, 98, 4, 67, 130, 161, 192, 36, 99, 224, 5, 162, 193, 68, 131, 37, 100, 225, 194, 256, 163, 69, 132, 6, 226, 257, 288, 195, 101, 164, 38, 258, 7, 227, 289, 133, 320, 70, 196, 165, 290, 259, 228, 39, 321, 102, 352, 8, 197, 71, 134, 322, 291, 260, 353, 384, 229, 166, 103, 40, 354, 323, 292, 135, 385, 198, 261, 72, 9, 416, 167, 386, 355, 230, 324, 104, 293, 41, 417, 199, 136, 262, 387, 448, 325, 356, 10, 73, 418, 231, 168, 449, 294, 388, 105, 419, 263, 42, 200, 357, 450, 137, 480, 74, 326, 232, 11, 389, 169, 295, 420, 106, 451, 481, 358, 264, 327, 201, 43, 138, 512, 482, 390, 296, 233, 170, 421, 75, 452, 359, 12, 513, 265, 483, 328, 107, 202, 514, 544, 422, 391, 453, 139, 44, 234, 484, 297, 360, 171, 76, 515, 545, 266, 329, 454, 13, 423, 203, 108, 546, 485, 576, 298, 235, 140, 361, 330, 172, 547, 45, 455, 267, 577, 486, 77, 204, 362, 608, 14, 299, 578, 109, 236, 487, 609, 331, 141, 579, 46, 15, 173, 610, 363, 78, 205, 16, 110, 237, 611, 142, 47, 174, 79, 206, 17, 111, 238, 48, 143, 80, 175, 112, 207, 49, 18, 239, 81, 113, 19, 50, 82, 114, 51, 83, 115, 640, 516, 392, 268, 144, 20, 672, 641, 548, 517, 424, 393, 300, 269, 176, 145, 52, 21, 704, 673, 642, 580, 549, 518, 456, 425, 394, 332, 301, 270, 208, 177, 146, 84, 53, 22, 736, 705, 674, 643, 612, 581, 550, 519, 488, 457, 426, 395, 364, 333, 302, 271, 240, 209, 178, 147, 116, 85, 54, 23, 737, 706, 675, 613, 582, 551, 489, 458, 427, 365, 334, 303, 241, 210, 179, 117, 86, 55, 738, 707, 614, 583, 490, 459, 366, 335, 242, 211, 118, 87, 739, 615, 491, 367, 243, 119, 768, 644, 520, 396, 272, 148, 24, 800, 769, 676, 645, 552, 521, 428, 397, 304, 273, 180, 149, 56, 25, 832, 801, 770, 708, 677, 646, 584, 553, 522, 460, 429, 398, 336, 305, 274, 212, 181, 150, 88, 57, 26, 864, 833, 802, 771, 740, 709, 678, 647, 616, 585, 554, 523, 492, 461, 430, 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 865, 834, 803, 741, 710, 679, 617, 586, 555, 493, 462, 431, 369, 338, 307, 245, 214, 183, 121, 90, 59, 866, 835, 742, 711, 618, 587, 494, 463, 370, 339, 246, 215, 122, 91, 867, 743, 619, 495, 371, 247, 123, 896, 772, 648, 524, 400, 276, 152, 28, 928, 897, 804, 773, 680, 649, 556, 525, 432, 401, 308, 277, 184, 153, 60, 29, 960, 929, 898, 836, 805, 774, 712, 681, 650, 588, 557, 526, 464, 433, 402, 340, 309, 278, 216, 185, 154, 92, 61, 30, 992, 961, 930, 899, 868, 837, 806, 775, 744, 713, 682, 651, 620, 589, 558, 527, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31, 993, 962, 931, 869, 838, 807, 745, 714, 683, 621, 590, 559, 497, 466, 435, 373, 342, 311, 249, 218, 187, 125, 94, 63, 994, 963, 870, 839, 746, 715, 622, 591, 498, 467, 374, 343, 250, 219, 126, 95, 995, 871, 747, 623, 499, 375, 251, 127, 900, 776, 652, 528, 404, 280, 156, 932, 901, 808, 777, 684, 653, 560, 529, 436, 405, 312, 281, 188, 157, 964, 933, 902, 840, 809, 778, 716, 685, 654, 592, 561, 530, 468, 437, 406, 344, 313, 282, 220, 189, 158, 996, 965, 934, 903, 872, 841, 810, 779, 748, 717, 686, 655, 624, 593, 562, 531, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 997, 966, 935, 873, 842, 811, 749, 718, 687, 625, 594, 563, 501, 470, 439, 377, 346, 315, 253, 222, 191, 998, 967, 874, 843, 750, 719, 626, 595, 502, 471, 378, 347, 254, 223, 999, 875, 751, 627, 503, 379, 255, 904, 780, 656, 532, 408, 284, 936, 905, 812, 781, 688, 657, 564, 533, 440, 409, 316, 285, 968, 937, 906, 844, 813, 782, 720, 689, 658, 596, 565, 534, 472, 441, 410, 348, 317, 286, 1000, 969, 938, 907, 876, 845, 814, 783, 752, 721, 690, 659, 628, 597, 566, 535, 504, 473, 442, 411, 380, 349, 318, 287, 1001, 970, 939, 877, 846, 815, 753, 722, 691, 629, 598, 567, 505, 474, 443, 381, 350, 319, 1002, 971, 878, 847, 754, 723, 630, 599, 506, 475, 382, 351, 1003, 879, 755, 631, 507, 383, 908, 784, 660, 536, 412, 940, 909, 816, 785, 692, 661, 568, 537, 444, 413, 972, 941, 910, 848, 817, 786, 724, 693, 662, 600, 569, 538, 476, 445, 414, 1004, 973, 942, 911, 880, 849, 818, 787, 756, 725, 694, 663, 632, 601, 570, 539, 508, 477, 446, 415, 1005, 974, 943, 881, 850, 819, 757, 726, 695, 633, 602, 571, 509, 478, 447, 1006, 975, 882, 851, 758, 727, 634, 603, 510, 479, 1007, 883, 759, 635, 511, 912, 788, 664, 540, 944, 913, 820, 789, 696, 665, 572, 541, 976, 945, 914, 852, 821, 790, 728, 697, 666, 604, 573, 542, 1008, 977, 946, 915, 884, 853, 822, 791, 760, 729, 698, 667, 636, 605, 574, 543, 1009, 978, 947, 885, 854, 823, 761, 730, 699, 637, 606, 575, 1010, 979, 886, 855, 762, 731, 638, 607, 1011, 887, 763, 639, 916, 792, 668, 948, 917, 824, 793, 700, 669, 980, 949, 918, 856, 825, 794, 732, 701, 670, 1012, 981, 950, 919, 888, 857, 826, 795, 764, 733, 702, 671, 1013, 982, 951, 889, 858, 827, 765, 734, 703, 1014, 983, 890, 859, 766, 735, 1015, 891, 767, 920, 796, 952, 921, 828, 797, 984, 953, 922, 860, 829, 798, 1016, 985, 954, 923, 892, 861, 830, 799, 1017, 986, 955, 893, 862, 831, 1018, 987, 894, 863, 1019, 895, 924, 956, 925, 988, 957, 926, 1020, 989, 958, 927, 1021, 990, 959, 1022, 991, 1023]; +pub(crate) const DEFAULT_SCAN_4X4_NEIGHBORS: [i16; 34] = [0, 0, 0, 0, 0, 0, 1, 4, 4, 4, 1, 1, 8, 8, 5, 8, 2, 2, 2, 5, 9, 12, 6, 9, 3, 6, 10, 13, 7, 10, 11, 14, 0, 0]; +pub(crate) const COL_SCAN_4X4_NEIGHBORS: [i16; 34] = [0, 0, 0, 0, 4, 4, 0, 0, 8, 8, 1, 1, 5, 5, 1, 1, 9, 9, 2, 2, 6, 6, 2, 2, 3, 3, 10, 10, 7, 7, 11, 11, 0, 0]; +pub(crate) const ROW_SCAN_4X4_NEIGHBORS: [i16; 34] = [0, 0, 0, 0, 0, 0, 1, 1, 4, 4, 2, 2, 5, 5, 4, 4, 8, 8, 6, 6, 8, 8, 9, 9, 12, 12, 10, 10, 13, 13, 14, 14, 0, 0]; +pub(crate) const DEFAULT_SCAN_8X8_NEIGHBORS: [i16; 130] = [0, 0, 0, 0, 0, 0, 8, 8, 1, 8, 1, 1, 9, 16, 16, 16, 2, 9, 2, 2, 10, 17, 17, 24, 24, 24, 3, 10, 3, 3, 18, 25, 25, 32, 11, 18, 32, 32, 4, 11, 26, 33, 19, 26, 4, 4, 33, 40, 12, 19, 40, 40, 5, 12, 27, 34, 34, 41, 20, 27, 13, 20, 5, 5, 41, 48, 48, 48, 28, 35, 35, 42, 21, 28, 6, 6, 6, 13, 42, 49, 49, 56, 36, 43, 14, 21, 29, 36, 7, 14, 43, 50, 50, 57, 22, 29, 37, 44, 15, 22, 44, 51, 51, 58, 30, 37, 23, 30, 52, 59, 45, 52, 38, 45, 31, 38, 53, 60, 46, 53, 39, 46, 54, 61, 47, 54, 55, 62, 0, 0]; +pub(crate) const COL_SCAN_8X8_NEIGHBORS: [i16; 130] = [0, 0, 0, 0, 8, 8, 0, 0, 16, 16, 1, 1, 24, 24, 9, 9, 1, 1, 32, 32, 17, 17, 2, 2, 25, 25, 10, 10, 40, 40, 2, 2, 18, 18, 33, 33, 3, 3, 48, 48, 11, 11, 26, 26, 3, 3, 41, 41, 19, 19, 34, 34, 4, 4, 27, 27, 12, 12, 49, 49, 42, 42, 20, 20, 4, 4, 35, 35, 5, 5, 28, 28, 50, 50, 43, 43, 13, 13, 36, 36, 5, 5, 21, 21, 51, 51, 29, 29, 6, 6, 44, 44, 14, 14, 6, 6, 37, 37, 52, 52, 22, 22, 7, 7, 30, 30, 45, 45, 15, 15, 38, 38, 23, 23, 53, 53, 31, 31, 46, 46, 39, 39, 54, 54, 47, 47, 55, 55, 0, 0]; +pub(crate) const ROW_SCAN_8X8_NEIGHBORS: [i16; 130] = [0, 0, 0, 0, 1, 1, 0, 0, 8, 8, 2, 2, 8, 8, 9, 9, 3, 3, 16, 16, 10, 10, 16, 16, 4, 4, 17, 17, 24, 24, 11, 11, 18, 18, 25, 25, 24, 24, 5, 5, 12, 12, 19, 19, 32, 32, 26, 26, 6, 6, 33, 33, 32, 32, 20, 20, 27, 27, 40, 40, 13, 13, 34, 34, 40, 40, 41, 41, 28, 28, 35, 35, 48, 48, 21, 21, 42, 42, 14, 14, 48, 48, 36, 36, 49, 49, 43, 43, 29, 29, 56, 56, 22, 22, 50, 50, 57, 57, 44, 44, 37, 37, 51, 51, 30, 30, 58, 58, 52, 52, 45, 45, 59, 59, 38, 38, 60, 60, 46, 46, 53, 53, 54, 54, 61, 61, 62, 62, 0, 0]; +pub(crate) const DEFAULT_SCAN_16X16_NEIGHBORS: [i16; 514] = [0, 0, 0, 0, 0, 0, 16, 16, 1, 16, 1, 1, 32, 32, 17, 32, 2, 17, 2, 2, 48, 48, 18, 33, 33, 48, 3, 18, 49, 64, 64, 64, 34, 49, 3, 3, 19, 34, 50, 65, 4, 19, 65, 80, 80, 80, 35, 50, 4, 4, 20, 35, 66, 81, 81, 96, 51, 66, 96, 96, 5, 20, 36, 51, 82, 97, 21, 36, 67, 82, 97, 112, 5, 5, 52, 67, 112, 112, 37, 52, 6, 21, 83, 98, 98, 113, 68, 83, 6, 6, 113, 128, 22, 37, 53, 68, 84, 99, 99, 114, 128, 128, 114, 129, 69, 84, 38, 53, 7, 22, 7, 7, 129, 144, 23, 38, 54, 69, 100, 115, 85, 100, 115, 130, 144, 144, 130, 145, 39, 54, 70, 85, 8, 23, 55, 70, 116, 131, 101, 116, 145, 160, 24, 39, 8, 8, 86, 101, 131, 146, 160, 160, 146, 161, 71, 86, 40, 55, 9, 24, 117, 132, 102, 117, 161, 176, 132, 147, 56, 71, 87, 102, 25, 40, 147, 162, 9, 9, 176, 176, 162, 177, 72, 87, 41, 56, 118, 133, 133, 148, 103, 118, 10, 25, 148, 163, 57, 72, 88, 103, 177, 192, 26, 41, 163, 178, 192, 192, 10, 10, 119, 134, 73, 88, 149, 164, 104, 119, 134, 149, 42, 57, 178, 193, 164, 179, 11, 26, 58, 73, 193, 208, 89, 104, 135, 150, 120, 135, 27, 42, 74, 89, 208, 208, 150, 165, 179, 194, 165, 180, 105, 120, 194, 209, 43, 58, 11, 11, 136, 151, 90, 105, 151, 166, 180, 195, 59, 74, 121, 136, 209, 224, 195, 210, 224, 224, 166, 181, 106, 121, 75, 90, 12, 27, 181, 196, 12, 12, 210, 225, 152, 167, 167, 182, 137, 152, 28, 43, 196, 211, 122, 137, 91, 106, 225, 240, 44, 59, 13, 28, 107, 122, 182, 197, 168, 183, 211, 226, 153, 168, 226, 241, 60, 75, 197, 212, 138, 153, 29, 44, 76, 91, 13, 13, 183, 198, 123, 138, 45, 60, 212, 227, 198, 213, 154, 169, 169, 184, 227, 242, 92, 107, 61, 76, 139, 154, 14, 29, 14, 14, 184, 199, 213, 228, 108, 123, 199, 214, 228, 243, 77, 92, 30, 45, 170, 185, 155, 170, 185, 200, 93, 108, 124, 139, 214, 229, 46, 61, 200, 215, 229, 244, 15, 30, 109, 124, 62, 77, 140, 155, 215, 230, 31, 46, 171, 186, 186, 201, 201, 216, 78, 93, 230, 245, 125, 140, 47, 62, 216, 231, 156, 171, 94, 109, 231, 246, 141, 156, 63, 78, 202, 217, 187, 202, 110, 125, 217, 232, 172, 187, 232, 247, 79, 94, 157, 172, 126, 141, 203, 218, 95, 110, 233, 248, 218, 233, 142, 157, 111, 126, 173, 188, 188, 203, 234, 249, 219, 234, 127, 142, 158, 173, 204, 219, 189, 204, 143, 158, 235, 250, 174, 189, 205, 220, 159, 174, 220, 235, 221, 236, 175, 190, 190, 205, 236, 251, 206, 221, 237, 252, 191, 206, 222, 237, 207, 222, 238, 253, 223, 238, 239, 254, 0, 0]; +pub(crate) const COL_SCAN_16X16_NEIGHBORS: [i16; 514] = [0, 0, 0, 0, 16, 16, 32, 32, 0, 0, 48, 48, 1, 1, 64, 64, 17, 17, 80, 80, 33, 33, 1, 1, 49, 49, 96, 96, 2, 2, 65, 65, 18, 18, 112, 112, 34, 34, 81, 81, 2, 2, 50, 50, 128, 128, 3, 3, 97, 97, 19, 19, 66, 66, 144, 144, 82, 82, 35, 35, 113, 113, 3, 3, 51, 51, 160, 160, 4, 4, 98, 98, 129, 129, 67, 67, 20, 20, 83, 83, 114, 114, 36, 36, 176, 176, 4, 4, 145, 145, 52, 52, 99, 99, 5, 5, 130, 130, 68, 68, 192, 192, 161, 161, 21, 21, 115, 115, 84, 84, 37, 37, 146, 146, 208, 208, 53, 53, 5, 5, 100, 100, 177, 177, 131, 131, 69, 69, 6, 6, 224, 224, 116, 116, 22, 22, 162, 162, 85, 85, 147, 147, 38, 38, 193, 193, 101, 101, 54, 54, 6, 6, 132, 132, 178, 178, 70, 70, 163, 163, 209, 209, 7, 7, 117, 117, 23, 23, 148, 148, 7, 7, 86, 86, 194, 194, 225, 225, 39, 39, 179, 179, 102, 102, 133, 133, 55, 55, 164, 164, 8, 8, 71, 71, 210, 210, 118, 118, 149, 149, 195, 195, 24, 24, 87, 87, 40, 40, 56, 56, 134, 134, 180, 180, 226, 226, 103, 103, 8, 8, 165, 165, 211, 211, 72, 72, 150, 150, 9, 9, 119, 119, 25, 25, 88, 88, 196, 196, 41, 41, 135, 135, 181, 181, 104, 104, 57, 57, 227, 227, 166, 166, 120, 120, 151, 151, 197, 197, 73, 73, 9, 9, 212, 212, 89, 89, 136, 136, 182, 182, 10, 10, 26, 26, 105, 105, 167, 167, 228, 228, 152, 152, 42, 42, 121, 121, 213, 213, 58, 58, 198, 198, 74, 74, 137, 137, 183, 183, 168, 168, 10, 10, 90, 90, 229, 229, 11, 11, 106, 106, 214, 214, 153, 153, 27, 27, 199, 199, 43, 43, 184, 184, 122, 122, 169, 169, 230, 230, 59, 59, 11, 11, 75, 75, 138, 138, 200, 200, 215, 215, 91, 91, 12, 12, 28, 28, 185, 185, 107, 107, 154, 154, 44, 44, 231, 231, 216, 216, 60, 60, 123, 123, 12, 12, 76, 76, 201, 201, 170, 170, 232, 232, 139, 139, 92, 92, 13, 13, 108, 108, 29, 29, 186, 186, 217, 217, 155, 155, 45, 45, 13, 13, 61, 61, 124, 124, 14, 14, 233, 233, 77, 77, 14, 14, 171, 171, 140, 140, 202, 202, 30, 30, 93, 93, 109, 109, 46, 46, 156, 156, 62, 62, 187, 187, 15, 15, 125, 125, 218, 218, 78, 78, 31, 31, 172, 172, 47, 47, 141, 141, 94, 94, 234, 234, 203, 203, 63, 63, 110, 110, 188, 188, 157, 157, 126, 126, 79, 79, 173, 173, 95, 95, 219, 219, 142, 142, 204, 204, 235, 235, 111, 111, 158, 158, 127, 127, 189, 189, 220, 220, 143, 143, 174, 174, 205, 205, 236, 236, 159, 159, 190, 190, 221, 221, 175, 175, 237, 237, 206, 206, 222, 222, 191, 191, 238, 238, 207, 207, 223, 223, 239, 239, 0, 0]; +pub(crate) const ROW_SCAN_16X16_NEIGHBORS: [i16; 514] = [0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 16, 16, 3, 3, 17, 17, 16, 16, 4, 4, 32, 32, 18, 18, 5, 5, 33, 33, 32, 32, 19, 19, 48, 48, 6, 6, 34, 34, 20, 20, 49, 49, 48, 48, 7, 7, 35, 35, 64, 64, 21, 21, 50, 50, 36, 36, 64, 64, 8, 8, 65, 65, 51, 51, 22, 22, 37, 37, 80, 80, 66, 66, 9, 9, 52, 52, 23, 23, 81, 81, 67, 67, 80, 80, 38, 38, 10, 10, 53, 53, 82, 82, 96, 96, 68, 68, 24, 24, 97, 97, 83, 83, 39, 39, 96, 96, 54, 54, 11, 11, 69, 69, 98, 98, 112, 112, 84, 84, 25, 25, 40, 40, 55, 55, 113, 113, 99, 99, 12, 12, 70, 70, 112, 112, 85, 85, 26, 26, 114, 114, 100, 100, 128, 128, 41, 41, 56, 56, 71, 71, 115, 115, 13, 13, 86, 86, 129, 129, 101, 101, 128, 128, 72, 72, 130, 130, 116, 116, 27, 27, 57, 57, 14, 14, 87, 87, 42, 42, 144, 144, 102, 102, 131, 131, 145, 145, 117, 117, 73, 73, 144, 144, 88, 88, 132, 132, 103, 103, 28, 28, 58, 58, 146, 146, 118, 118, 43, 43, 160, 160, 147, 147, 89, 89, 104, 104, 133, 133, 161, 161, 119, 119, 160, 160, 74, 74, 134, 134, 148, 148, 29, 29, 59, 59, 162, 162, 176, 176, 44, 44, 120, 120, 90, 90, 105, 105, 163, 163, 177, 177, 149, 149, 176, 176, 135, 135, 164, 164, 178, 178, 30, 30, 150, 150, 192, 192, 75, 75, 121, 121, 60, 60, 136, 136, 193, 193, 106, 106, 151, 151, 179, 179, 192, 192, 45, 45, 165, 165, 166, 166, 194, 194, 91, 91, 180, 180, 137, 137, 208, 208, 122, 122, 152, 152, 208, 208, 195, 195, 76, 76, 167, 167, 209, 209, 181, 181, 224, 224, 107, 107, 196, 196, 61, 61, 153, 153, 224, 224, 182, 182, 168, 168, 210, 210, 46, 46, 138, 138, 92, 92, 183, 183, 225, 225, 211, 211, 240, 240, 197, 197, 169, 169, 123, 123, 154, 154, 198, 198, 77, 77, 212, 212, 184, 184, 108, 108, 226, 226, 199, 199, 62, 62, 227, 227, 241, 241, 139, 139, 213, 213, 170, 170, 185, 185, 155, 155, 228, 228, 242, 242, 124, 124, 93, 93, 200, 200, 243, 243, 214, 214, 215, 215, 229, 229, 140, 140, 186, 186, 201, 201, 78, 78, 171, 171, 109, 109, 156, 156, 244, 244, 216, 216, 230, 230, 94, 94, 245, 245, 231, 231, 125, 125, 202, 202, 246, 246, 232, 232, 172, 172, 217, 217, 141, 141, 110, 110, 157, 157, 187, 187, 247, 247, 126, 126, 233, 233, 218, 218, 248, 248, 188, 188, 203, 203, 142, 142, 173, 173, 158, 158, 249, 249, 234, 234, 204, 204, 219, 219, 174, 174, 189, 189, 250, 250, 220, 220, 190, 190, 205, 205, 235, 235, 206, 206, 236, 236, 251, 251, 221, 221, 252, 252, 222, 222, 237, 237, 238, 238, 253, 253, 254, 254, 0, 0]; +pub(crate) const DEFAULT_SCAN_32X32_NEIGHBORS: [i16; 2050] = [0, 0, 0, 0, 0, 0, 32, 32, 1, 32, 1, 1, 64, 64, 33, 64, 2, 33, 96, 96, 2, 2, 65, 96, 34, 65, 128, 128, 97, 128, 3, 34, 66, 97, 3, 3, 35, 66, 98, 129, 129, 160, 160, 160, 4, 35, 67, 98, 192, 192, 4, 4, 130, 161, 161, 192, 36, 67, 99, 130, 5, 36, 68, 99, 193, 224, 162, 193, 224, 224, 131, 162, 37, 68, 100, 131, 5, 5, 194, 225, 225, 256, 256, 256, 163, 194, 69, 100, 132, 163, 6, 37, 226, 257, 6, 6, 195, 226, 257, 288, 101, 132, 288, 288, 38, 69, 164, 195, 133, 164, 258, 289, 227, 258, 196, 227, 7, 38, 289, 320, 70, 101, 320, 320, 7, 7, 165, 196, 39, 70, 102, 133, 290, 321, 259, 290, 228, 259, 321, 352, 352, 352, 197, 228, 134, 165, 71, 102, 8, 39, 322, 353, 291, 322, 260, 291, 103, 134, 353, 384, 166, 197, 229, 260, 40, 71, 8, 8, 384, 384, 135, 166, 354, 385, 323, 354, 198, 229, 292, 323, 72, 103, 261, 292, 9, 40, 385, 416, 167, 198, 104, 135, 230, 261, 355, 386, 416, 416, 293, 324, 324, 355, 9, 9, 41, 72, 386, 417, 199, 230, 136, 167, 417, 448, 262, 293, 356, 387, 73, 104, 387, 418, 231, 262, 10, 41, 168, 199, 325, 356, 418, 449, 105, 136, 448, 448, 42, 73, 294, 325, 200, 231, 10, 10, 357, 388, 137, 168, 263, 294, 388, 419, 74, 105, 419, 450, 449, 480, 326, 357, 232, 263, 295, 326, 169, 200, 11, 42, 106, 137, 480, 480, 450, 481, 358, 389, 264, 295, 201, 232, 138, 169, 389, 420, 43, 74, 420, 451, 327, 358, 11, 11, 481, 512, 233, 264, 451, 482, 296, 327, 75, 106, 170, 201, 482, 513, 512, 512, 390, 421, 359, 390, 421, 452, 107, 138, 12, 43, 202, 233, 452, 483, 265, 296, 328, 359, 139, 170, 44, 75, 483, 514, 513, 544, 234, 265, 297, 328, 422, 453, 12, 12, 391, 422, 171, 202, 76, 107, 514, 545, 453, 484, 544, 544, 266, 297, 203, 234, 108, 139, 329, 360, 298, 329, 140, 171, 515, 546, 13, 44, 423, 454, 235, 266, 545, 576, 454, 485, 45, 76, 172, 203, 330, 361, 576, 576, 13, 13, 267, 298, 546, 577, 77, 108, 204, 235, 455, 486, 577, 608, 299, 330, 109, 140, 547, 578, 14, 45, 14, 14, 141, 172, 578, 609, 331, 362, 46, 77, 173, 204, 15, 15, 78, 109, 205, 236, 579, 610, 110, 141, 15, 46, 142, 173, 47, 78, 174, 205, 16, 16, 79, 110, 206, 237, 16, 47, 111, 142, 48, 79, 143, 174, 80, 111, 175, 206, 17, 48, 17, 17, 207, 238, 49, 80, 81, 112, 18, 18, 18, 49, 50, 81, 82, 113, 19, 50, 51, 82, 83, 114, 608, 608, 484, 515, 360, 391, 236, 267, 112, 143, 19, 19, 640, 640, 609, 640, 516, 547, 485, 516, 392, 423, 361, 392, 268, 299, 237, 268, 144, 175, 113, 144, 20, 51, 20, 20, 672, 672, 641, 672, 610, 641, 548, 579, 517, 548, 486, 517, 424, 455, 393, 424, 362, 393, 300, 331, 269, 300, 238, 269, 176, 207, 145, 176, 114, 145, 52, 83, 21, 52, 21, 21, 704, 704, 673, 704, 642, 673, 611, 642, 580, 611, 549, 580, 518, 549, 487, 518, 456, 487, 425, 456, 394, 425, 363, 394, 332, 363, 301, 332, 270, 301, 239, 270, 208, 239, 177, 208, 146, 177, 115, 146, 84, 115, 53, 84, 22, 53, 22, 22, 705, 736, 674, 705, 643, 674, 581, 612, 550, 581, 519, 550, 457, 488, 426, 457, 395, 426, 333, 364, 302, 333, 271, 302, 209, 240, 178, 209, 147, 178, 85, 116, 54, 85, 23, 54, 706, 737, 675, 706, 582, 613, 551, 582, 458, 489, 427, 458, 334, 365, 303, 334, 210, 241, 179, 210, 86, 117, 55, 86, 707, 738, 583, 614, 459, 490, 335, 366, 211, 242, 87, 118, 736, 736, 612, 643, 488, 519, 364, 395, 240, 271, 116, 147, 23, 23, 768, 768, 737, 768, 644, 675, 613, 644, 520, 551, 489, 520, 396, 427, 365, 396, 272, 303, 241, 272, 148, 179, 117, 148, 24, 55, 24, 24, 800, 800, 769, 800, 738, 769, 676, 707, 645, 676, 614, 645, 552, 583, 521, 552, 490, 521, 428, 459, 397, 428, 366, 397, 304, 335, 273, 304, 242, 273, 180, 211, 149, 180, 118, 149, 56, 87, 25, 56, 25, 25, 832, 832, 801, 832, 770, 801, 739, 770, 708, 739, 677, 708, 646, 677, 615, 646, 584, 615, 553, 584, 522, 553, 491, 522, 460, 491, 429, 460, 398, 429, 367, 398, 336, 367, 305, 336, 274, 305, 243, 274, 212, 243, 181, 212, 150, 181, 119, 150, 88, 119, 57, 88, 26, 57, 26, 26, 833, 864, 802, 833, 771, 802, 709, 740, 678, 709, 647, 678, 585, 616, 554, 585, 523, 554, 461, 492, 430, 461, 399, 430, 337, 368, 306, 337, 275, 306, 213, 244, 182, 213, 151, 182, 89, 120, 58, 89, 27, 58, 834, 865, 803, 834, 710, 741, 679, 710, 586, 617, 555, 586, 462, 493, 431, 462, 338, 369, 307, 338, 214, 245, 183, 214, 90, 121, 59, 90, 835, 866, 711, 742, 587, 618, 463, 494, 339, 370, 215, 246, 91, 122, 864, 864, 740, 771, 616, 647, 492, 523, 368, 399, 244, 275, 120, 151, 27, 27, 896, 896, 865, 896, 772, 803, 741, 772, 648, 679, 617, 648, 524, 555, 493, 524, 400, 431, 369, 400, 276, 307, 245, 276, 152, 183, 121, 152, 28, 59, 28, 28, 928, 928, 897, 928, 866, 897, 804, 835, 773, 804, 742, 773, 680, 711, 649, 680, 618, 649, 556, 587, 525, 556, 494, 525, 432, 463, 401, 432, 370, 401, 308, 339, 277, 308, 246, 277, 184, 215, 153, 184, 122, 153, 60, 91, 29, 60, 29, 29, 960, 960, 929, 960, 898, 929, 867, 898, 836, 867, 805, 836, 774, 805, 743, 774, 712, 743, 681, 712, 650, 681, 619, 650, 588, 619, 557, 588, 526, 557, 495, 526, 464, 495, 433, 464, 402, 433, 371, 402, 340, 371, 309, 340, 278, 309, 247, 278, 216, 247, 185, 216, 154, 185, 123, 154, 92, 123, 61, 92, 30, 61, 30, 30, 961, 992, 930, 961, 899, 930, 837, 868, 806, 837, 775, 806, 713, 744, 682, 713, 651, 682, 589, 620, 558, 589, 527, 558, 465, 496, 434, 465, 403, 434, 341, 372, 310, 341, 279, 310, 217, 248, 186, 217, 155, 186, 93, 124, 62, 93, 31, 62, 962, 993, 931, 962, 838, 869, 807, 838, 714, 745, 683, 714, 590, 621, 559, 590, 466, 497, 435, 466, 342, 373, 311, 342, 218, 249, 187, 218, 94, 125, 63, 94, 963, 994, 839, 870, 715, 746, 591, 622, 467, 498, 343, 374, 219, 250, 95, 126, 868, 899, 744, 775, 620, 651, 496, 527, 372, 403, 248, 279, 124, 155, 900, 931, 869, 900, 776, 807, 745, 776, 652, 683, 621, 652, 528, 559, 497, 528, 404, 435, 373, 404, 280, 311, 249, 280, 156, 187, 125, 156, 932, 963, 901, 932, 870, 901, 808, 839, 777, 808, 746, 777, 684, 715, 653, 684, 622, 653, 560, 591, 529, 560, 498, 529, 436, 467, 405, 436, 374, 405, 312, 343, 281, 312, 250, 281, 188, 219, 157, 188, 126, 157, 964, 995, 933, 964, 902, 933, 871, 902, 840, 871, 809, 840, 778, 809, 747, 778, 716, 747, 685, 716, 654, 685, 623, 654, 592, 623, 561, 592, 530, 561, 499, 530, 468, 499, 437, 468, 406, 437, 375, 406, 344, 375, 313, 344, 282, 313, 251, 282, 220, 251, 189, 220, 158, 189, 127, 158, 965, 996, 934, 965, 903, 934, 841, 872, 810, 841, 779, 810, 717, 748, 686, 717, 655, 686, 593, 624, 562, 593, 531, 562, 469, 500, 438, 469, 407, 438, 345, 376, 314, 345, 283, 314, 221, 252, 190, 221, 159, 190, 966, 997, 935, 966, 842, 873, 811, 842, 718, 749, 687, 718, 594, 625, 563, 594, 470, 501, 439, 470, 346, 377, 315, 346, 222, 253, 191, 222, 967, 998, 843, 874, 719, 750, 595, 626, 471, 502, 347, 378, 223, 254, 872, 903, 748, 779, 624, 655, 500, 531, 376, 407, 252, 283, 904, 935, 873, 904, 780, 811, 749, 780, 656, 687, 625, 656, 532, 563, 501, 532, 408, 439, 377, 408, 284, 315, 253, 284, 936, 967, 905, 936, 874, 905, 812, 843, 781, 812, 750, 781, 688, 719, 657, 688, 626, 657, 564, 595, 533, 564, 502, 533, 440, 471, 409, 440, 378, 409, 316, 347, 285, 316, 254, 285, 968, 999, 937, 968, 906, 937, 875, 906, 844, 875, 813, 844, 782, 813, 751, 782, 720, 751, 689, 720, 658, 689, 627, 658, 596, 627, 565, 596, 534, 565, 503, 534, 472, 503, 441, 472, 410, 441, 379, 410, 348, 379, 317, 348, 286, 317, 255, 286, 969, 1000, 938, 969, 907, 938, 845, 876, 814, 845, 783, 814, 721, 752, 690, 721, 659, 690, 597, 628, 566, 597, 535, 566, 473, 504, 442, 473, 411, 442, 349, 380, 318, 349, 287, 318, 970, 1001, 939, 970, 846, 877, 815, 846, 722, 753, 691, 722, 598, 629, 567, 598, 474, 505, 443, 474, 350, 381, 319, 350, 971, 1002, 847, 878, 723, 754, 599, 630, 475, 506, 351, 382, 876, 907, 752, 783, 628, 659, 504, 535, 380, 411, 908, 939, 877, 908, 784, 815, 753, 784, 660, 691, 629, 660, 536, 567, 505, 536, 412, 443, 381, 412, 940, 971, 909, 940, 878, 909, 816, 847, 785, 816, 754, 785, 692, 723, 661, 692, 630, 661, 568, 599, 537, 568, 506, 537, 444, 475, 413, 444, 382, 413, 972, 1003, 941, 972, 910, 941, 879, 910, 848, 879, 817, 848, 786, 817, 755, 786, 724, 755, 693, 724, 662, 693, 631, 662, 600, 631, 569, 600, 538, 569, 507, 538, 476, 507, 445, 476, 414, 445, 383, 414, 973, 1004, 942, 973, 911, 942, 849, 880, 818, 849, 787, 818, 725, 756, 694, 725, 663, 694, 601, 632, 570, 601, 539, 570, 477, 508, 446, 477, 415, 446, 974, 1005, 943, 974, 850, 881, 819, 850, 726, 757, 695, 726, 602, 633, 571, 602, 478, 509, 447, 478, 975, 1006, 851, 882, 727, 758, 603, 634, 479, 510, 880, 911, 756, 787, 632, 663, 508, 539, 912, 943, 881, 912, 788, 819, 757, 788, 664, 695, 633, 664, 540, 571, 509, 540, 944, 975, 913, 944, 882, 913, 820, 851, 789, 820, 758, 789, 696, 727, 665, 696, 634, 665, 572, 603, 541, 572, 510, 541, 976, 1007, 945, 976, 914, 945, 883, 914, 852, 883, 821, 852, 790, 821, 759, 790, 728, 759, 697, 728, 666, 697, 635, 666, 604, 635, 573, 604, 542, 573, 511, 542, 977, 1008, 946, 977, 915, 946, 853, 884, 822, 853, 791, 822, 729, 760, 698, 729, 667, 698, 605, 636, 574, 605, 543, 574, 978, 1009, 947, 978, 854, 885, 823, 854, 730, 761, 699, 730, 606, 637, 575, 606, 979, 1010, 855, 886, 731, 762, 607, 638, 884, 915, 760, 791, 636, 667, 916, 947, 885, 916, 792, 823, 761, 792, 668, 699, 637, 668, 948, 979, 917, 948, 886, 917, 824, 855, 793, 824, 762, 793, 700, 731, 669, 700, 638, 669, 980, 1011, 949, 980, 918, 949, 887, 918, 856, 887, 825, 856, 794, 825, 763, 794, 732, 763, 701, 732, 670, 701, 639, 670, 981, 1012, 950, 981, 919, 950, 857, 888, 826, 857, 795, 826, 733, 764, 702, 733, 671, 702, 982, 1013, 951, 982, 858, 889, 827, 858, 734, 765, 703, 734, 983, 1014, 859, 890, 735, 766, 888, 919, 764, 795, 920, 951, 889, 920, 796, 827, 765, 796, 952, 983, 921, 952, 890, 921, 828, 859, 797, 828, 766, 797, 984, 1015, 953, 984, 922, 953, 891, 922, 860, 891, 829, 860, 798, 829, 767, 798, 985, 1016, 954, 985, 923, 954, 861, 892, 830, 861, 799, 830, 986, 1017, 955, 986, 862, 893, 831, 862, 987, 1018, 863, 894, 892, 923, 924, 955, 893, 924, 956, 987, 925, 956, 894, 925, 988, 1019, 957, 988, 926, 957, 895, 926, 989, 1020, 958, 989, 927, 958, 990, 1021, 959, 990, 991, 1022, 0, 0]; +pub(crate) const KF_Y_MODE_PROB: [u8; 900] = [137, 30, 42, 148, 151, 207, 70, 52, 91, 92, 45, 102, 136, 116, 180, 74, 90, 100, 73, 32, 19, 187, 222, 215, 46, 34, 100, 91, 30, 32, 116, 121, 186, 93, 86, 94, 72, 35, 36, 149, 68, 206, 68, 63, 105, 73, 31, 28, 138, 57, 124, 55, 122, 151, 67, 23, 21, 140, 126, 197, 40, 37, 171, 86, 27, 28, 128, 154, 212, 45, 43, 53, 74, 32, 27, 107, 86, 160, 63, 134, 102, 59, 67, 44, 140, 161, 202, 78, 67, 119, 63, 36, 126, 146, 123, 158, 60, 90, 96, 43, 46, 168, 134, 107, 128, 69, 142, 92, 44, 29, 68, 159, 201, 177, 50, 57, 77, 58, 38, 76, 114, 97, 172, 78, 133, 92, 46, 41, 76, 140, 63, 184, 69, 112, 57, 38, 32, 85, 140, 46, 112, 54, 151, 133, 39, 27, 61, 131, 110, 175, 44, 75, 136, 52, 30, 74, 113, 130, 175, 51, 64, 58, 47, 35, 80, 100, 74, 143, 64, 163, 74, 36, 61, 116, 114, 128, 162, 80, 125, 82, 82, 26, 26, 171, 208, 204, 44, 32, 105, 55, 44, 68, 166, 179, 192, 57, 57, 108, 42, 26, 11, 199, 241, 228, 23, 15, 85, 68, 42, 19, 131, 160, 199, 55, 52, 83, 58, 50, 25, 139, 115, 232, 39, 52, 118, 50, 35, 33, 153, 104, 162, 64, 59, 131, 44, 24, 16, 150, 177, 202, 33, 19, 156, 55, 27, 12, 153, 203, 218, 26, 27, 49, 53, 49, 21, 110, 116, 168, 59, 80, 76, 38, 72, 19, 168, 203, 212, 50, 50, 107, 103, 26, 36, 129, 132, 201, 83, 80, 93, 59, 38, 83, 112, 103, 162, 98, 136, 90, 62, 30, 23, 158, 200, 207, 59, 57, 50, 67, 30, 29, 84, 86, 191, 102, 91, 59, 60, 32, 33, 112, 71, 220, 64, 89, 104, 53, 26, 34, 130, 56, 149, 84, 120, 103, 53, 21, 23, 133, 109, 210, 56, 77, 172, 77, 19, 29, 112, 142, 228, 55, 66, 36, 61, 29, 29, 93, 97, 165, 83, 175, 162, 47, 47, 43, 114, 137, 181, 100, 99, 95, 69, 23, 29, 128, 83, 199, 46, 44, 101, 53, 40, 55, 139, 69, 183, 61, 80, 110, 40, 29, 19, 161, 180, 207, 43, 24, 91, 60, 34, 19, 105, 61, 198, 53, 64, 89, 52, 31, 22, 158, 40, 209, 58, 62, 89, 44, 31, 29, 147, 46, 158, 56, 102, 198, 35, 19, 12, 135, 87, 209, 41, 45, 167, 55, 25, 21, 118, 95, 215, 38, 39, 66, 51, 38, 25, 113, 58, 164, 70, 93, 97, 47, 54, 34, 146, 108, 203, 72, 103, 151, 64, 19, 37, 156, 66, 138, 49, 95, 133, 46, 27, 80, 150, 55, 124, 55, 121, 135, 36, 23, 27, 165, 149, 166, 54, 64, 118, 53, 21, 36, 131, 63, 163, 60, 109, 81, 40, 26, 35, 154, 40, 185, 51, 97, 123, 35, 19, 34, 179, 19, 97, 48, 129, 124, 36, 20, 26, 136, 62, 164, 33, 77, 154, 45, 18, 32, 130, 90, 157, 40, 79, 91, 45, 26, 28, 129, 45, 129, 49, 147, 123, 38, 44, 51, 136, 74, 162, 57, 97, 121, 75, 17, 22, 136, 138, 185, 32, 34, 166, 56, 39, 58, 133, 117, 173, 48, 53, 187, 35, 21, 12, 161, 212, 207, 20, 23, 145, 56, 29, 19, 117, 109, 181, 55, 68, 112, 47, 29, 17, 153, 64, 220, 59, 51, 114, 46, 16, 24, 136, 76, 147, 41, 64, 172, 34, 17, 11, 108, 152, 187, 13, 15, 209, 51, 24, 14, 115, 133, 209, 32, 26, 104, 55, 30, 18, 122, 79, 179, 44, 88, 116, 37, 49, 25, 129, 168, 164, 41, 54, 148, 82, 22, 32, 127, 143, 213, 39, 41, 70, 62, 44, 61, 123, 105, 189, 48, 57, 64, 47, 25, 17, 175, 222, 220, 24, 30, 86, 68, 36, 17, 106, 102, 206, 59, 74, 74, 57, 39, 23, 151, 68, 216, 55, 63, 58, 49, 30, 35, 141, 70, 168, 82, 40, 115, 51, 25, 15, 136, 129, 202, 38, 35, 139, 68, 26, 16, 111, 141, 215, 29, 28, 28, 59, 39, 19, 114, 75, 180, 77, 104, 42, 40, 61, 26, 126, 152, 206, 61, 59, 93, 78, 23, 39, 111, 117, 170, 74, 124, 94, 48, 34, 86, 101, 92, 146, 78, 179, 134, 47, 22, 24, 138, 187, 178, 68, 69, 59, 56, 25, 33, 105, 112, 187, 95, 177, 129, 48, 31, 27, 114, 63, 183, 82, 116, 56, 43, 28, 37, 121, 63, 123, 61, 192, 169, 42, 17, 24, 109, 97, 177, 56, 76, 122, 58, 18, 28, 105, 139, 182, 70, 92, 63, 46, 23, 32, 74, 86, 150, 67, 183, 88, 36, 38, 48, 92, 122, 165, 88, 137, 91, 65, 70, 60, 155, 159, 199, 61, 60, 81, 44, 78, 115, 132, 119, 173, 71, 112, 93, 39, 38, 21, 184, 227, 206, 42, 32, 64, 58, 47, 36, 124, 137, 193, 80, 82, 78, 49, 50, 35, 144, 95, 205, 63, 78, 59, 41, 53, 52, 148, 71, 142, 65, 128, 51, 40, 36, 28, 143, 143, 202, 40, 55, 137, 52, 34, 29, 129, 183, 227, 42, 35, 43, 42, 44, 44, 104, 105, 164, 64, 130, 80, 43, 81, 53, 140, 169, 204, 68, 84, 72]; +pub(crate) const DEFAULT_IF_UV_PROBS: [u8; 90] = [120, 7, 76, 176, 208, 126, 28, 54, 103, 48, 12, 154, 155, 139, 90, 34, 117, 119, 67, 6, 25, 204, 243, 158, 13, 21, 96, 97, 5, 44, 131, 176, 139, 48, 68, 97, 83, 5, 42, 156, 111, 152, 26, 49, 152, 80, 5, 58, 178, 74, 83, 33, 62, 145, 86, 5, 32, 154, 192, 168, 14, 22, 163, 85, 5, 32, 156, 216, 148, 19, 29, 73, 77, 7, 64, 116, 132, 122, 37, 126, 120, 101, 21, 107, 181, 192, 103, 19, 67, 125]; +pub(crate) const DEFAULT_PARTITION_PROBS: [u8; 48] = [199, 122, 141, 147, 63, 159, 148, 133, 118, 121, 104, 114, 174, 73, 87, 92, 41, 83, 82, 99, 50, 53, 39, 39, 177, 58, 59, 68, 26, 63, 52, 79, 25, 17, 14, 12, 222, 34, 30, 72, 16, 44, 58, 32, 12, 10, 7, 6]; +pub(crate) const DEFAULT_SKIP_PROBS: [u8; 3] = [192, 128, 64]; +pub(crate) const MODE_TO_TXTYPE_LOOKUP: [u8; 10] = [0, 1, 2, 0, 3, 1, 2, 2, 1, 3]; +pub(crate) const B_WIDTH_LOG2_LOOKUP: [i8; 13] = [0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4]; +pub(crate) const B_HEIGHT_LOG2_LOOKUP: [i8; 13] = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4]; +pub(crate) const NUM_8X8_BLOCKS_WIDE_LOOKUP: [u8; 13] = [1, 1, 1, 1, 1, 2, 2, 2, 4, 4, 4, 8, 8]; +pub(crate) const NUM_8X8_BLOCKS_HIGH_LOOKUP: [u8; 13] = [1, 1, 1, 1, 2, 1, 2, 4, 2, 4, 8, 4, 8]; +pub(crate) const NUM_4X4_BLOCKS_WIDE_LOOKUP: [u8; 13] = [1, 1, 2, 2, 2, 4, 4, 4, 8, 8, 8, 16, 16]; +pub(crate) const NUM_4X4_BLOCKS_HIGH_LOOKUP: [u8; 13] = [1, 2, 1, 2, 4, 2, 4, 8, 4, 8, 16, 8, 16]; +pub(crate) const SIZE_GROUP_LOOKUP: [u8; 13] = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3]; +pub(crate) const MAX_TXSIZE_LOOKUP: [u8; 13] = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3]; +pub(crate) const SS_SIZE_LOOKUP: [u8; 52] = [0, 255, 255, 255, 1, 0, 255, 255, 2, 255, 0, 255, 3, 2, 1, 0, 4, 3, 255, 1, 5, 255, 3, 2, 6, 5, 4, 3, 7, 6, 255, 4, 8, 255, 6, 5, 9, 8, 7, 6, 10, 9, 255, 7, 11, 255, 9, 8, 12, 11, 10, 9]; +pub(crate) const SUBSIZE_LOOKUP: [u8; 52] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 255, 255, 255, 2, 255, 255, 5, 255, 255, 8, 255, 255, 11, 255, 255, 255, 1, 255, 255, 4, 255, 255, 7, 255, 255, 10, 255, 255, 255, 0, 255, 255, 3, 255, 255, 6, 255, 255, 9]; +pub(crate) const DEFAULT_COEF_PROBS_4X4: [[[[[u8; 3]; 6]; 6]; 2]; 2] = [[[[[195, 29, 183], [84, 49, 136], [8, 42, 71], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[31, 107, 169], [35, 99, 159], [17, 82, 140], [8, 66, 114], [2, 44, 76], [1, 19, 32]], [[40, 132, 201], [29, 114, 187], [13, 91, 157], [7, 75, 127], [3, 58, 95], [1, 28, 47]], [[69, 142, 221], [42, 122, 201], [15, 91, 159], [6, 67, 121], [1, 42, 77], [1, 17, 31]], [[102, 148, 228], [67, 117, 204], [17, 82, 154], [6, 59, 114], [2, 39, 75], [1, 15, 29]], [[156, 57, 233], [119, 57, 212], [58, 48, 163], [29, 40, 124], [12, 30, 81], [3, 12, 31]]], [[[191, 107, 226], [124, 117, 204], [25, 99, 155], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[29, 148, 210], [37, 126, 194], [8, 93, 157], [2, 68, 118], [1, 39, 69], [1, 17, 33]], [[41, 151, 213], [27, 123, 193], [3, 82, 144], [1, 58, 105], [1, 32, 60], [1, 13, 26]], [[59, 159, 220], [23, 126, 198], [4, 88, 151], [1, 66, 114], [1, 38, 71], [1, 18, 34]], [[114, 136, 232], [51, 114, 207], [11, 83, 155], [3, 56, 105], [1, 33, 65], [1, 17, 34]], [[149, 65, 234], [121, 57, 215], [61, 49, 166], [28, 36, 114], [12, 25, 76], [3, 16, 42]]]], [[[[214, 49, 220], [132, 63, 188], [42, 65, 137], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[85, 137, 221], [104, 131, 216], [49, 111, 192], [21, 87, 155], [2, 49, 87], [1, 16, 28]], [[89, 163, 230], [90, 137, 220], [29, 100, 183], [10, 70, 135], [2, 42, 81], [1, 17, 33]], [[108, 167, 237], [55, 133, 222], [15, 97, 179], [4, 72, 135], [1, 45, 85], [1, 19, 38]], [[124, 146, 240], [66, 124, 224], [17, 88, 175], [4, 58, 122], [1, 36, 75], [1, 18, 37]], [[141, 79, 241], [126, 70, 227], [66, 58, 182], [30, 44, 136], [12, 34, 96], [2, 20, 47]]], [[[229, 99, 249], [143, 111, 235], [46, 109, 192], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[82, 158, 236], [94, 146, 224], [25, 117, 191], [9, 87, 149], [3, 56, 99], [1, 33, 57]], [[83, 167, 237], [68, 145, 222], [10, 103, 177], [2, 72, 131], [1, 41, 79], [1, 20, 39]], [[99, 167, 239], [47, 141, 224], [10, 104, 178], [2, 73, 133], [1, 44, 85], [1, 22, 47]], [[127, 145, 243], [71, 129, 228], [17, 93, 177], [3, 61, 124], [1, 41, 84], [1, 21, 52]], [[157, 78, 244], [140, 72, 231], [69, 58, 184], [31, 44, 137], [14, 38, 105], [8, 23, 61]]]]]; +pub(crate) const DEFAULT_COEF_PROBS_8X8: [[[[[u8; 3]; 6]; 6]; 2]; 2] = [[[[[125, 34, 187], [52, 41, 133], [6, 31, 56], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[37, 109, 153], [51, 102, 147], [23, 87, 128], [8, 67, 101], [1, 41, 63], [1, 19, 29]], [[31, 154, 185], [17, 127, 175], [6, 96, 145], [2, 73, 114], [1, 51, 82], [1, 28, 45]], [[23, 163, 200], [10, 131, 185], [2, 93, 148], [1, 67, 111], [1, 41, 69], [1, 14, 24]], [[29, 176, 217], [12, 145, 201], [3, 101, 156], [1, 69, 111], [1, 39, 63], [1, 14, 23]], [[57, 192, 233], [25, 154, 215], [6, 109, 167], [3, 78, 118], [1, 48, 69], [1, 21, 29]]], [[[202, 105, 245], [108, 106, 216], [18, 90, 144], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[33, 172, 219], [64, 149, 206], [14, 117, 177], [5, 90, 141], [2, 61, 95], [1, 37, 57]], [[33, 179, 220], [11, 140, 198], [1, 89, 148], [1, 60, 104], [1, 33, 57], [1, 12, 21]], [[30, 181, 221], [8, 141, 198], [1, 87, 145], [1, 58, 100], [1, 31, 55], [1, 12, 20]], [[32, 186, 224], [7, 142, 198], [1, 86, 143], [1, 58, 100], [1, 31, 55], [1, 12, 22]], [[57, 192, 227], [20, 143, 204], [3, 96, 154], [1, 68, 112], [1, 42, 69], [1, 19, 32]]]], [[[[212, 35, 215], [113, 47, 169], [29, 48, 105], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[74, 129, 203], [106, 120, 203], [49, 107, 178], [19, 84, 144], [4, 50, 84], [1, 15, 25]], [[71, 172, 217], [44, 141, 209], [15, 102, 173], [6, 76, 133], [2, 51, 89], [1, 24, 42]], [[64, 185, 231], [31, 148, 216], [8, 103, 175], [3, 74, 131], [1, 46, 81], [1, 18, 30]], [[65, 196, 235], [25, 157, 221], [5, 105, 174], [1, 67, 120], [1, 38, 69], [1, 15, 30]], [[65, 204, 238], [30, 156, 224], [7, 107, 177], [2, 70, 124], [1, 42, 73], [1, 18, 34]]], [[[225, 86, 251], [144, 104, 235], [42, 99, 181], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[85, 175, 239], [112, 165, 229], [29, 136, 200], [12, 103, 162], [6, 77, 123], [2, 53, 84]], [[75, 183, 239], [30, 155, 221], [3, 106, 171], [1, 74, 128], [1, 44, 76], [1, 17, 28]], [[73, 185, 240], [27, 159, 222], [2, 107, 172], [1, 75, 127], [1, 42, 73], [1, 17, 29]], [[62, 190, 238], [21, 159, 222], [2, 107, 172], [1, 72, 122], [1, 40, 71], [1, 18, 32]], [[61, 199, 240], [27, 161, 226], [4, 113, 180], [1, 76, 129], [1, 46, 80], [1, 23, 41]]]]]; +pub(crate) const DEFAULT_COEF_PROBS_16X16: [[[[[u8; 3]; 6]; 6]; 2]; 2] = [[[[[7, 27, 153], [5, 30, 95], [1, 16, 30], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[50, 75, 127], [57, 75, 124], [27, 67, 108], [10, 54, 86], [1, 33, 52], [1, 12, 18]], [[43, 125, 151], [26, 108, 148], [7, 83, 122], [2, 59, 89], [1, 38, 60], [1, 17, 27]], [[23, 144, 163], [13, 112, 154], [2, 75, 117], [1, 50, 81], [1, 31, 51], [1, 14, 23]], [[18, 162, 185], [6, 123, 171], [1, 78, 125], [1, 51, 86], [1, 31, 54], [1, 14, 23]], [[15, 199, 227], [3, 150, 204], [1, 91, 146], [1, 55, 95], [1, 30, 53], [1, 11, 20]]], [[[19, 55, 240], [19, 59, 196], [3, 52, 105], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[41, 166, 207], [104, 153, 199], [31, 123, 181], [14, 101, 152], [5, 72, 106], [1, 36, 52]], [[35, 176, 211], [12, 131, 190], [2, 88, 144], [1, 60, 101], [1, 36, 60], [1, 16, 28]], [[28, 183, 213], [8, 134, 191], [1, 86, 142], [1, 56, 96], [1, 30, 53], [1, 12, 20]], [[20, 190, 215], [4, 135, 192], [1, 84, 139], [1, 53, 91], [1, 28, 49], [1, 11, 20]], [[13, 196, 216], [2, 137, 192], [1, 86, 143], [1, 57, 99], [1, 32, 56], [1, 13, 24]]]], [[[[211, 29, 217], [96, 47, 156], [22, 43, 87], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[78, 120, 193], [111, 116, 186], [46, 102, 164], [15, 80, 128], [2, 49, 76], [1, 18, 28]], [[71, 161, 203], [42, 132, 192], [10, 98, 150], [3, 69, 109], [1, 44, 70], [1, 18, 29]], [[57, 186, 211], [30, 140, 196], [4, 93, 146], [1, 62, 102], [1, 38, 65], [1, 16, 27]], [[47, 199, 217], [14, 145, 196], [1, 88, 142], [1, 57, 98], [1, 36, 62], [1, 15, 26]], [[26, 219, 229], [5, 155, 207], [1, 94, 151], [1, 60, 104], [1, 36, 62], [1, 16, 28]]], [[[233, 29, 248], [146, 47, 220], [43, 52, 140], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[100, 163, 232], [179, 161, 222], [63, 142, 204], [37, 113, 174], [26, 89, 137], [18, 68, 97]], [[85, 181, 230], [32, 146, 209], [7, 100, 164], [3, 71, 121], [1, 45, 77], [1, 18, 30]], [[65, 187, 230], [20, 148, 207], [2, 97, 159], [1, 68, 116], [1, 40, 70], [1, 14, 29]], [[40, 194, 227], [8, 147, 204], [1, 94, 155], [1, 65, 112], [1, 39, 66], [1, 14, 26]], [[16, 208, 228], [3, 151, 207], [1, 98, 160], [1, 67, 117], [1, 41, 74], [1, 17, 31]]]]]; +pub(crate) const DEFAULT_COEF_PROBS_32X32: [[[[[u8; 3]; 6]; 6]; 2]; 2] = [[[[[17, 38, 140], [7, 34, 80], [1, 17, 29], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[37, 75, 128], [41, 76, 128], [26, 66, 116], [12, 52, 94], [2, 32, 55], [1, 10, 16]], [[50, 127, 154], [37, 109, 152], [16, 82, 121], [5, 59, 85], [1, 35, 54], [1, 13, 20]], [[40, 142, 167], [17, 110, 157], [2, 71, 112], [1, 44, 72], [1, 27, 45], [1, 11, 17]], [[30, 175, 188], [9, 124, 169], [1, 74, 116], [1, 48, 78], [1, 30, 49], [1, 11, 18]], [[10, 222, 223], [2, 150, 194], [1, 83, 128], [1, 48, 79], [1, 27, 45], [1, 11, 17]]], [[[36, 41, 235], [29, 36, 193], [10, 27, 111], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[85, 165, 222], [177, 162, 215], [110, 135, 195], [57, 113, 168], [23, 83, 120], [10, 49, 61]], [[85, 190, 223], [36, 139, 200], [5, 90, 146], [1, 60, 103], [1, 38, 65], [1, 18, 30]], [[72, 202, 223], [23, 141, 199], [2, 86, 140], [1, 56, 97], [1, 36, 61], [1, 16, 27]], [[55, 218, 225], [13, 145, 200], [1, 86, 141], [1, 57, 99], [1, 35, 61], [1, 13, 22]], [[15, 235, 212], [1, 132, 184], [1, 84, 139], [1, 57, 97], [1, 34, 56], [1, 14, 23]]]], [[[[181, 21, 201], [61, 37, 123], [10, 38, 71], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[47, 106, 172], [95, 104, 173], [42, 93, 159], [18, 77, 131], [4, 50, 81], [1, 17, 23]], [[62, 147, 199], [44, 130, 189], [28, 102, 154], [18, 75, 115], [2, 44, 65], [1, 12, 19]], [[55, 153, 210], [24, 130, 194], [3, 93, 146], [1, 61, 97], [1, 31, 50], [1, 10, 16]], [[49, 186, 223], [17, 148, 204], [1, 96, 142], [1, 53, 83], [1, 26, 44], [1, 11, 17]], [[13, 217, 212], [2, 136, 180], [1, 78, 124], [1, 50, 83], [1, 29, 49], [1, 14, 23]]], [[[197, 13, 247], [82, 17, 222], [25, 17, 162], [0, 0, 0], [0, 0, 0], [0, 0, 0]], [[126, 186, 247], [234, 191, 243], [176, 177, 234], [104, 158, 220], [66, 128, 186], [55, 90, 137]], [[111, 197, 242], [46, 158, 219], [9, 104, 171], [2, 65, 125], [1, 44, 80], [1, 17, 91]], [[104, 208, 245], [39, 168, 224], [3, 109, 162], [1, 79, 124], [1, 50, 102], [1, 43, 102]], [[84, 220, 246], [31, 177, 231], [2, 115, 180], [1, 79, 134], [1, 55, 77], [1, 60, 79]], [[43, 243, 240], [8, 180, 217], [1, 115, 166], [1, 84, 121], [1, 51, 67], [1, 16, 6]]]]]; +pub(crate) const TX_P8X8_PROB: [u8; 2] = [100, 66]; +pub(crate) const TX_P16X16_PROB: [u8; 4] = [20, 152, 15, 101]; +pub(crate) const TX_P32X32_PROB: [u8; 6] = [3, 136, 37, 5, 52, 13]; +pub(crate) const KF_UV_MODE_PROB: [u8; 90] = [144,11,54,157,195,130,46,58,108,118,15,123,148,131,101,44,93,131,113,12,23,188,226,142,26,32,125,120,11,50,123,163,135,64,77,103,113,9,36,155,111,157,32,44,161,116,9,55,176,76,96,37,61,149,115,9,28,141,161,167,21,25,193,120,12,32,145,195,142,32,38,86,116,12,64,120,140,125,49,115,121,102,19,66,162,182,122,35,59,128]; diff --git a/crates/ec-vp9/src/tables/mod.rs b/crates/ec-vp9/src/tables/mod.rs new file mode 100644 index 00000000..b0bd9594 --- /dev/null +++ b/crates/ec-vp9/src/tables/mod.rs @@ -0,0 +1,140 @@ +//! Handwritten trees and constants around the generated bulk tables, +//! plus the block/transform-size enums shared by every module. + +mod gen_tables; + +pub(crate) use gen_tables::*; + +use crate::Result; +use ec_core::Error; + +pub(crate) const DIFF_UPDATE_PROB: u8 = 252; +pub(crate) const ALLOW_32X32: u8 = 3; + +// spec 5.3 (PREDICTION_MODE) +pub(crate) const DC_PRED: u8 = 0; +pub(crate) const TM_PRED: u8 = 9; +pub(crate) const INTRA_MODES: usize = 10; + +// spec 5.2 (TX_SIZE) +pub(crate) const TX_4X4: usize = 0; +pub(crate) const TX_8X8: usize = 1; +pub(crate) const TX_16X16: usize = 2; +pub(crate) const TX_32X32: usize = 3; + +// spec 5.4 (TX_TYPE) +pub(crate) const DCT_DCT: usize = 0; +pub(crate) const ADST_DCT: usize = 1; +pub(crate) const DCT_ADST: usize = 2; +pub(crate) const ADST_ADST: usize = 3; + +pub(crate) const BLOCK_INVALID: u8 = 255; + +// spec 5.3 (TX_MODE) +pub(crate) const TX_MODE_SELECT: u8 = 4; +/// decodeframe.c `tx_mode_to_biggest_tx_size`. +pub(crate) const TX_MODE_TO_BIGGEST_TX_SIZE: [usize; 5] = + [TX_4X4, TX_8X8, TX_16X16, TX_32X32, TX_32X32]; + +/// spec 6.3.5 `partition_tree`. +pub(crate) const PARTITION_TREE: [i8; 6] = [-0, 2, -1, 4, -2, -3]; +/// spec 6.3.4 y mode tree (8.2 `read_intra_mode`). +pub(crate) const INTRA_MODE_TREE: [i8; 18] = [ + -0, 2, -9, 4, -1, 6, 8, 12, -2, 10, -5, -6, -3, 14, -7, 16, -8, -4, +]; +/// spec 6.3.4 uv mode tree. +pub(crate) const UV_MODE_TREE: [i8; 18] = [ + -0, 2, -1, 4, -2, 6, -3, 8, -4, 10, -5, 12, -6, 14, -7, 16, -8, -9, +]; +/// spec 6.2 segment id tree. +pub(crate) const SEGMENT_TREE: [i8; 14] = + [-0, 2, -1, 4, -2, 6, -3, 8, -4, 10, -5, 12, -6, -7]; + +/// blockd.h `get_y_mode`. +#[inline] +pub(crate) fn get_y_mode(sb_type: usize, bmi: [u8; 4], mode: u8, block: usize) -> u8 { + if sb_type < 3 { bmi[block] } else { mode } +} + +/// vp9_blockd.c `vp9_above_block_mode` (keyframes: neighbours are intra). +pub(crate) fn above_block_mode( + cur_bmi: &[u8; 4], + above: Option<(usize, [u8; 4], u8)>, + b: usize, +) -> u8 { + if b == 0 || b == 1 { + match above { + Some((sb_type, bmi, mode)) => get_y_mode(sb_type, bmi, mode, b + 2), + None => DC_PRED, + } + } else { + cur_bmi[b - 2] + } +} + +/// vp9_blockd.c `vp9_left_block_mode`. +pub(crate) fn left_block_mode( + cur_bmi: &[u8; 4], + left: Option<(usize, [u8; 4], u8)>, + b: usize, +) -> u8 { + if b == 0 || b == 2 { + match left { + Some((sb_type, bmi, mode)) => get_y_mode(sb_type, bmi, mode, b + 1), + None => DC_PRED, + } + } else { + cur_bmi[b - 1] + } +} + +/// blockd.h `get_y_mode_probs` reduced to the keyframe table. +#[inline] +pub(crate) fn kf_y_mode_probs(above: u8, left: u8) -> [u8; 9] { + let base = above as usize * INTRA_MODES + left as usize; + let mut out = [0u8; 9]; + out.copy_from_slice(&KF_Y_MODE_PROB[base * 9..base * 9 + 9]); + out +} + +/// `vp9_kf_uv_mode_prob` reshaped per y mode (9 branch probs). +pub(crate) fn kf_uv_probs(mode: u8) -> [u8; 9] { + let base = mode as usize * 9; + let mut out = [0u8; 9]; + out.copy_from_slice(&KF_UV_MODE_PROB[base..base + 9]); + out +} + +/// common_data.c `uv_txsize_lookup` for 4:2:0. +pub(crate) fn uv_txsize_lookup(bsize: usize, tx_size: usize) -> usize { + let uv = SS_SIZE_LOOKUP[bsize * 4 + 3]; + if uv == BLOCK_INVALID { + TX_4X4 + } else { + tx_size.min(MAX_TXSIZE_LOOKUP[uv as usize] as usize) + } +} + +/// common_data.c `ss_size_lookup[bsize][1][1]`. +#[inline] +pub(crate) fn ss_size(bsize: usize) -> usize { + SS_SIZE_LOOKUP[bsize * 4 + 3] as usize +} + +/// blockd.h `get_uv_tx_size` for 4:2:0. +#[inline] +pub(crate) fn get_uv_tx_size(mi_tx_size: usize, sb_type: usize) -> usize { + if sb_type < 3 { + TX_4X4 + } else { + mi_tx_size.min(MAX_TXSIZE_LOOKUP[ss_size(sb_type)] as usize) + } +} + +pub(crate) fn corrupt(what: impl Into) -> Error { + Error::corrupt(format!("vp9: {}", what.into())) +} + +pub(crate) fn ensure(cond: bool, what: &str) -> Result<()> { + if cond { Ok(()) } else { Err(corrupt(what)) } +} diff --git a/crates/ec-vp9/src/tokens.rs b/crates/ec-vp9/src/tokens.rs new file mode 100644 index 00000000..b45578c1 --- /dev/null +++ b/crates/ec-vp9/src/tokens.rs @@ -0,0 +1,155 @@ +//! Coefficient token decoding (spec 8.5.2 `decode_coefs` / libvpx +//! `vp9_detokenize.c`, ported verbatim including its context bookkeeping). + +use crate::bool::BoolDecoder; +use crate::tables::*; + +/// One plane's entropy contexts: a has-coefficient flag per 4x4 column +/// above the current superblock row and per 4x4 row to the left. +pub(crate) struct PlaneContexts { + pub above: Vec, + pub left: [u8; 32], +} + +impl PlaneContexts { + pub(crate) fn new(above_len: usize) -> Self { + Self { above: vec![0; above_len], left: [0; 32] } + } +} + +/// `get_coef_context` (vp9_scan.h). +#[inline] +fn get_coef_context(nb: &[i16], token_cache: &[u8; 1024], c: usize) -> usize { + ((1 + token_cache[nb[2 * c] as usize] + token_cache[nb[2 * c + 1] as usize]) >> 1) as usize +} + +#[inline] +fn band_at(tx_size: usize, c: usize) -> usize { + if tx_size == TX_4X4 { COEFBAND_TRANS_4X4[c] as usize } else { COEFBAND_TRANS_8X8PLUS[c] as usize } +} + +#[inline] +fn read_coeff(r: &mut BoolDecoder, probs: &[u8], n: usize) -> i32 { + let mut val = 0i32; + for i in 0..n { + val = (val << 1) + r.read_bool(probs[i]) as i32; + } + val +} + +/// One decoded transform block: dequantized coefficients + eob. +pub(crate) struct CoeffBlock { + pub coeffs: Box<[i32]>, + pub eob: usize, +} + +/// `decode_coefs`, verbatim port. `dq` is `[dc, ac]`; plane 0 is luma, +/// chroma is 1; the ref axis is fixed at 0 (intra). +pub(crate) fn decode_coefs( + r: &mut BoolDecoder, + plane_type: usize, + tx_size: usize, + dequant: &[i16; 2], + mut ctx: usize, + scan: &[i16], + nb: &[i16], + probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2], +) -> CoeffBlock { + let max_eob = 16 << (tx_size << 1); + let mut coef = CoeffBlock { coeffs: vec![0i32; max_eob].into_boxed_slice(), eob: 0 }; + let mut token_cache = [0u8; 1024]; + let mut c = 0usize; + let dq_shift = usize::from(tx_size == TX_32X32); + let mut dqv = dequant[0] as i32; + let mut band = band_at(tx_size, c); + let mut prob: &[u8; 3] = &probs4d[plane_type][0][band][ctx]; + if std::env::var_os("EC_VP9_DBG").is_some() && plane_type == 0 && ctx == 0 && band == 0 { + eprintln!("DBG coefs tx={tx_size} dq={dequant:?} ctx={ctx} band={band} prob={prob:?}"); + } + + while c < max_eob { + if !r.read_bool(prob[0]) { + break; + } + while !r.read_bool(prob[1]) { + dqv = dequant[1] as i32; + token_cache[scan[c] as usize] = 0; + c += 1; + if c >= max_eob { + return coef; // zero tokens to the end (no eob token) + } + ctx = get_coef_context(nb, &token_cache, c); + band = band_at(tx_size, c); + prob = &probs4d[plane_type][0][band][ctx]; + } + let mut v: i32; + if r.read_bool(prob[2]) { + let base = prob[2] as usize - 1; + let p = &PARETO8_FULL[base * 8..base * 8 + 8]; + if r.read_bool(p[0]) { + if r.read_bool(p[3]) { + token_cache[scan[c] as usize] = 5; + if r.read_bool(p[5]) { + if r.read_bool(p[7]) { + v = 67 + read_coeff(r, &CAT6_PROB, 14); + } else { + v = 35 + read_coeff(r, &CAT5_PROB, 5); + } + } else if r.read_bool(p[6]) { + v = 19 + read_coeff(r, &CAT4_PROB, 4); + } else { + v = 11 + read_coeff(r, &CAT3_PROB, 3); + } + } else { + token_cache[scan[c] as usize] = 4; + if r.read_bool(p[4]) { + v = 7 + read_coeff(r, &CAT2_PROB, 2); + } else { + v = 5 + read_coeff(r, &CAT1_PROB, 1); + } + } + v = (v * dqv) >> dq_shift; + } else if r.read_bool(p[1]) { + token_cache[scan[c] as usize] = 3; + v = ((3 + r.read_bool(p[2]) as i32) * dqv) >> dq_shift; + } else { + token_cache[scan[c] as usize] = 2; + v = (2 * dqv) >> dq_shift; + } + } else { + token_cache[scan[c] as usize] = 1; + v = dqv >> dq_shift; + } + let sign = r.read_bool(128); + let pos = scan[c] as usize; + coef.coeffs[pos] = if sign { -v } else { v }; + c += 1; + if c < max_eob { + ctx = get_coef_context(nb, &token_cache, c); + band = band_at(tx_size, c); + prob = &probs4d[plane_type][0][band][ctx]; + } + dqv = dequant[1] as i32; + } + coef.eob = c; + coef +} + +/// Scan + neighbors per tx size and tx type (vp9_scan_orders). +pub(crate) fn scan_for(tx_size: usize, tx_type: usize) -> (&'static [i16], &'static [i16]) { + match (tx_size, tx_type) { + (TX_4X4, DCT_DCT) => (&DEFAULT_SCAN_4X4, &DEFAULT_SCAN_4X4_NEIGHBORS), + (TX_4X4, ADST_DCT) => (&ROW_SCAN_4X4, &ROW_SCAN_4X4_NEIGHBORS), + (TX_4X4, DCT_ADST) => (&COL_SCAN_4X4, &COL_SCAN_4X4_NEIGHBORS), + (TX_4X4, _) => (&DEFAULT_SCAN_4X4, &DEFAULT_SCAN_4X4_NEIGHBORS), + (TX_8X8, DCT_DCT) => (&DEFAULT_SCAN_8X8, &DEFAULT_SCAN_8X8_NEIGHBORS), + (TX_8X8, ADST_DCT) => (&ROW_SCAN_8X8, &ROW_SCAN_8X8_NEIGHBORS), + (TX_8X8, DCT_ADST) => (&COL_SCAN_8X8, &COL_SCAN_8X8_NEIGHBORS), + (TX_8X8, _) => (&DEFAULT_SCAN_8X8, &DEFAULT_SCAN_8X8_NEIGHBORS), + (TX_16X16, DCT_DCT) => (&DEFAULT_SCAN_16X16, &DEFAULT_SCAN_16X16_NEIGHBORS), + (TX_16X16, ADST_DCT) => (&ROW_SCAN_16X16, &ROW_SCAN_16X16_NEIGHBORS), + (TX_16X16, DCT_ADST) => (&COL_SCAN_16X16, &COL_SCAN_16X16_NEIGHBORS), + (TX_16X16, _) => (&DEFAULT_SCAN_16X16, &DEFAULT_SCAN_16X16_NEIGHBORS), + (_, _) => (&DEFAULT_SCAN_32X32, &DEFAULT_SCAN_32X32_NEIGHBORS), + } +} diff --git a/crates/ec-vp9/src/transform.rs b/crates/ec-vp9/src/transform.rs new file mode 100644 index 00000000..2c2433a1 --- /dev/null +++ b/crates/ec-vp9/src/transform.rs @@ -0,0 +1,670 @@ +//! Integer inverse transforms (spec 8.5.3; the libvpx `inv_txfm.c` +//! butterflies, rounding and shifts transcribed exactly). Release-build +//! `WRAPLOW` is an identity, so intermediates stay `i32`; only the final +//! add clamps. + +use crate::tables::*; + +#[inline] +fn dcrs(x: i64) -> i32 { + ((x + (1 << 13)) >> 14) as i32 +} + +const C1: i64 = 16364; +const C2: i64 = 16305; +const C3: i64 = 16207; +const C4: i64 = 16069; +const C5: i64 = 15893; +const C6: i64 = 15679; +const C7: i64 = 15426; +const C8: i64 = 15137; +const C9: i64 = 14811; +const C10: i64 = 14449; +const C11: i64 = 14053; +const C12: i64 = 13623; +const C13: i64 = 13160; +const C14: i64 = 12665; +const C15: i64 = 12140; +const C16: i64 = 11585; +const C17: i64 = 11003; +const C18: i64 = 10394; +const C19: i64 = 9760; +const C20: i64 = 9102; +const C21: i64 = 8423; +const C22: i64 = 7723; +const C23: i64 = 7005; +const C24: i64 = 6270; +const C25: i64 = 5520; +const C26: i64 = 4756; +const C27: i64 = 3981; +const C28: i64 = 3196; +const C29: i64 = 2404; +const C30: i64 = 1606; +const C31: i64 = 804; +const S1: i64 = 5283; +const S2: i64 = 9929; +const S3: i64 = 13377; +const S4: i64 = 15212; + +/// `clip_pixel_add`. +#[inline] +pub(crate) fn clip_add(d: u8, v: i32) -> u8 { + (d as i32 + v).clamp(0, 255) as u8 +} + +/// vpx_iwht4x4_16_add_c (lossless). +pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) { + let mut output = [0i32; 16]; + for i in 0..4 { + let ip = &input[i * 4..i * 4 + 4]; + let mut a1 = ip[0] >> 2; + let mut c1 = ip[1] >> 2; + let mut d1 = ip[2] >> 2; + let mut b1 = ip[3] >> 2; + a1 += c1; + d1 -= b1; + let e1 = (a1 - d1) >> 1; + b1 = e1 - b1; + c1 = e1 - c1; + a1 -= b1; + d1 += c1; + output[i * 4..i * 4 + 4].copy_from_slice(&[a1, b1, c1, d1]); + } + for i in 0..4 { + let a0 = output[i]; + let c0 = output[4 + i]; + let d0 = output[8 + i]; + let b0 = output[12 + i]; + let a2 = a0 + c0; + let d2 = d0 - b0; + let e1 = (a2 - d2) >> 1; + let b1 = e1 - b0; + let c1 = e1 - c0; + let a1 = a2 - b1; + let d1 = d2 + c1; + dest[i] = clip_add(dest[i], a1); + dest[stride + i] = clip_add(dest[stride + i], b1); + dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1); + dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1); + } +} + +pub(crate) fn idct4(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut step = [0i32; 4]; + let t1 = (g(input[0]) + g(input[2])) * C16; + let t2 = (g(input[0]) - g(input[2])) * C16; + step[0] = dcrs(t1); + step[1] = dcrs(t2); + let t1 = g(input[1]) * C24 - g(input[3]) * C8; + let t2 = g(input[1]) * C8 + g(input[3]) * C24; + step[2] = dcrs(t1); + step[3] = dcrs(t2); + output[0] = step[0] + step[3]; + output[1] = step[1] + step[2]; + output[2] = step[1] - step[2]; + output[3] = step[0] - step[3]; +} + +pub(crate) fn idct8(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut step1 = [0i32; 8]; + let mut step2 = [0i32; 8]; + step1[0] = input[0]; + step1[1] = input[2]; + step1[2] = input[4]; + step1[3] = input[6]; + step1[4] = dcrs(g(input[1]) * C28 - g(input[7]) * C4); + step1[7] = dcrs(g(input[1]) * C4 + g(input[7]) * C28); + step1[5] = dcrs(g(input[5]) * C12 - g(input[3]) * C20); + step1[6] = dcrs(g(input[5]) * C20 + g(input[3]) * C12); + step2[0] = dcrs((g(step1[0]) + g(step1[2])) * C16); + step2[1] = dcrs((g(step1[0]) - g(step1[2])) * C16); + step2[2] = dcrs(g(step1[1]) * C24 - g(step1[3]) * C8); + step2[3] = dcrs(g(step1[1]) * C8 + g(step1[3]) * C24); + step2[4] = step1[4] + step1[5]; + step2[5] = step1[4] - step1[5]; + step2[6] = -step1[6] + step1[7]; + step2[7] = step1[6] + step1[7]; + step1[0] = step2[0] + step2[3]; + step1[1] = step2[1] + step2[2]; + step1[2] = step2[1] - step2[2]; + step1[3] = step2[0] - step2[3]; + step1[4] = step2[4]; + step1[5] = dcrs((g(step2[6]) - g(step2[5])) * C16); + step1[6] = dcrs((g(step2[5]) + g(step2[6])) * C16); + step1[7] = step2[7]; + output[0] = step1[0] + step1[7]; + output[1] = step1[1] + step1[6]; + output[2] = step1[2] + step1[5]; + output[3] = step1[3] + step1[4]; + output[4] = step1[3] - step1[4]; + output[5] = step1[2] - step1[5]; + output[6] = step1[1] - step1[6]; + output[7] = step1[0] - step1[7]; +} + +pub(crate) fn idct16(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut step1 = [0i32; 16]; + let mut step2 = [0i32; 16]; + const ORD: [usize; 16] = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30]; + for i in 0..16 { + step1[i] = input[ORD[i] / 2]; + } + step2[8] = dcrs(g(step1[8]) * C30 - g(step1[15]) * C2); + step2[15] = dcrs(g(step1[8]) * C2 + g(step1[15]) * C30); + step2[9] = dcrs(g(step1[9]) * C14 - g(step1[14]) * C18); + step2[14] = dcrs(g(step1[9]) * C18 + g(step1[14]) * C14); + step2[10] = dcrs(g(step1[10]) * C22 - g(step1[13]) * C10); + step2[13] = dcrs(g(step1[10]) * C10 + g(step1[13]) * C22); + step2[11] = dcrs(g(step1[11]) * C6 - g(step1[12]) * C26); + step2[12] = dcrs(g(step1[11]) * C26 + g(step1[12]) * C6); + step2[0..8].copy_from_slice(&step1[0..8]); + step1[4] = dcrs(g(step2[4]) * C28 - g(step2[7]) * C4); + step1[7] = dcrs(g(step2[4]) * C4 + g(step2[7]) * C28); + step1[5] = dcrs(g(step2[5]) * C12 - g(step2[6]) * C20); + step1[6] = dcrs(g(step2[5]) * C20 + g(step2[6]) * C12); + step1[0..4].copy_from_slice(&step2[0..4]); + step1[8] = step2[8] + step2[9]; + step1[9] = step2[8] - step2[9]; + step1[10] = -step2[10] + step2[11]; + step1[11] = step2[10] + step2[11]; + step1[12] = step2[12] + step2[13]; + step1[13] = step2[12] - step2[13]; + step1[14] = -step2[14] + step2[15]; + step1[15] = step2[14] + step2[15]; + step2[0] = dcrs((g(step1[0]) + g(step1[1])) * C16); + step2[1] = dcrs((g(step1[0]) - g(step1[1])) * C16); + step2[2] = dcrs(g(step1[2]) * C24 - g(step1[3]) * C8); + step2[3] = dcrs(g(step1[2]) * C8 + g(step1[3]) * C24); + step2[4] = step1[4] + step1[5]; + step2[5] = step1[4] - step1[5]; + step2[6] = -step1[6] + step1[7]; + step2[7] = step1[6] + step1[7]; + step2[8] = step1[8]; + step2[15] = step1[15]; + step2[9] = dcrs(-g(step1[9]) * C8 + g(step1[14]) * C24); + step2[14] = dcrs(g(step1[9]) * C24 + g(step1[14]) * C8); + step2[10] = dcrs(-g(step1[10]) * C24 - g(step1[13]) * C8); + step2[13] = dcrs(-g(step1[10]) * C8 + g(step1[13]) * C24); + step2[11] = step1[11]; + step2[12] = step1[12]; + step1[0] = step2[0] + step2[3]; + step1[1] = step2[1] + step2[2]; + step1[2] = step2[1] - step2[2]; + step1[3] = step2[0] - step2[3]; + step1[4] = step2[4]; + step1[5] = dcrs((g(step2[6]) - g(step2[5])) * C16); + step1[6] = dcrs((g(step2[5]) + g(step2[6])) * C16); + step1[7] = step2[7]; + step1[8] = step2[8] + step2[11]; + step1[9] = step2[9] + step2[10]; + step1[10] = step2[9] - step2[10]; + step1[11] = step2[8] - step2[11]; + step1[12] = -step2[12] + step2[15]; + step1[13] = -step2[13] + step2[14]; + step1[14] = step2[13] + step2[14]; + step1[15] = step2[12] + step2[15]; + step2[0] = step1[0] + step1[7]; + step2[1] = step1[1] + step1[6]; + step2[2] = step1[2] + step1[5]; + step2[3] = step1[3] + step1[4]; + step2[4] = step1[3] - step1[4]; + step2[5] = step1[2] - step1[5]; + step2[6] = step1[1] - step1[6]; + step2[7] = step1[0] - step1[7]; + step2[8] = step1[8]; + step2[9] = step1[9]; + step2[10] = dcrs((-g(step1[10]) + g(step1[13])) * C16); + step2[13] = dcrs((g(step1[10]) + g(step1[13])) * C16); + step2[11] = dcrs((-g(step1[11]) + g(step1[12])) * C16); + step2[12] = dcrs((g(step1[11]) + g(step1[12])) * C16); + step2[14] = step1[14]; + step2[15] = step1[15]; + for i in 0..8 { + output[i] = step2[i] + step2[15 - i]; + output[15 - i] = step2[i] - step2[15 - i]; + } +} + +pub(crate) fn idct32(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut step1 = [0i32; 32]; + let mut step2 = [0i32; 32]; + for i in 0..16 { + step1[i] = input[[0usize, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30][i]]; + } + step1[16] = dcrs(g(input[1]) * C31 - g(input[31]) * C1); + step1[31] = dcrs(g(input[1]) * C1 + g(input[31]) * C31); + step1[17] = dcrs(g(input[17]) * C15 - g(input[15]) * C17); + step1[30] = dcrs(g(input[17]) * C17 + g(input[15]) * C15); + step1[18] = dcrs(g(input[9]) * C23 - g(input[23]) * C9); + step1[29] = dcrs(g(input[9]) * C9 + g(input[23]) * C23); + step1[19] = dcrs(g(input[25]) * C7 - g(input[7]) * C25); + step1[28] = dcrs(g(input[25]) * C25 + g(input[7]) * C7); + step1[20] = dcrs(g(input[5]) * C27 - g(input[27]) * C5); + step1[27] = dcrs(g(input[5]) * C5 + g(input[27]) * C27); + step1[21] = dcrs(g(input[21]) * C11 - g(input[11]) * C21); + step1[26] = dcrs(g(input[21]) * C21 + g(input[11]) * C11); + step1[22] = dcrs(g(input[13]) * C19 - g(input[19]) * C13); + step1[25] = dcrs(g(input[13]) * C13 + g(input[19]) * C19); + step1[23] = dcrs(g(input[29]) * C3 - g(input[3]) * C29); + step1[24] = dcrs(g(input[29]) * C29 + g(input[3]) * C3); + step2[0..8].copy_from_slice(&step1[0..8]); + step2[8] = dcrs(g(step1[8]) * C30 - g(step1[15]) * C2); + step2[15] = dcrs(g(step1[8]) * C2 + g(step1[15]) * C30); + step2[9] = dcrs(g(step1[9]) * C14 - g(step1[14]) * C18); + step2[14] = dcrs(g(step1[9]) * C18 + g(step1[14]) * C14); + step2[10] = dcrs(g(step1[10]) * C22 - g(step1[13]) * C10); + step2[13] = dcrs(g(step1[10]) * C10 + g(step1[13]) * C22); + step2[11] = dcrs(g(step1[11]) * C6 - g(step1[12]) * C26); + step2[12] = dcrs(g(step1[11]) * C26 + g(step1[12]) * C6); + step2[16] = step1[16] + step1[17]; + step2[17] = step1[16] - step1[17]; + step2[18] = -step1[18] + step1[19]; + step2[19] = step1[18] + step1[19]; + step2[20] = step1[20] + step1[21]; + step2[21] = step1[20] - step1[21]; + step2[22] = -step1[22] + step1[23]; + step2[23] = step1[22] + step1[23]; + step2[24] = step1[24] + step1[25]; + step2[25] = step1[24] - step1[25]; + step2[26] = -step1[26] + step1[27]; + step2[27] = step1[26] + step1[27]; + step2[28] = step1[28] + step1[29]; + step2[29] = step1[28] - step1[29]; + step2[30] = -step1[30] + step1[31]; + step2[31] = step1[30] + step1[31]; + step1[0..4].copy_from_slice(&step2[0..4]); + step1[4] = dcrs(g(step2[4]) * C28 - g(step2[7]) * C4); + step1[7] = dcrs(g(step2[4]) * C4 + g(step2[7]) * C28); + step1[5] = dcrs(g(step2[5]) * C12 - g(step2[6]) * C20); + step1[6] = dcrs(g(step2[5]) * C20 + g(step2[6]) * C12); + step1[8] = step2[8] + step2[9]; + step1[9] = step2[8] - step2[9]; + step1[10] = -step2[10] + step2[11]; + step1[11] = step2[10] + step2[11]; + step1[12] = step2[12] + step2[13]; + step1[13] = step2[12] - step2[13]; + step1[14] = -step2[14] + step2[15]; + step1[15] = step2[14] + step2[15]; + step1[16] = step2[16]; + step1[31] = step2[31]; + step1[17] = dcrs(-g(step2[17]) * C4 + g(step2[30]) * C28); + step1[30] = dcrs(g(step2[17]) * C28 + g(step2[30]) * C4); + step1[18] = dcrs(-g(step2[18]) * C28 - g(step2[29]) * C4); + step1[29] = dcrs(-g(step2[18]) * C4 + g(step2[29]) * C28); + step1[19] = step2[19]; + step1[20] = step2[20]; + step1[21] = dcrs(-g(step2[21]) * C20 + g(step2[26]) * C12); + step1[26] = dcrs(g(step2[21]) * C12 + g(step2[26]) * C20); + step1[22] = dcrs(-g(step2[22]) * C12 - g(step2[25]) * C20); + step1[25] = dcrs(-g(step2[22]) * C20 + g(step2[25]) * C12); + step1[23] = step2[23]; + step1[24] = step2[24]; + step1[27] = step2[27]; + step1[28] = step2[28]; + step2[0] = dcrs((g(step1[0]) + g(step1[1])) * C16); + step2[1] = dcrs((g(step1[0]) - g(step1[1])) * C16); + step2[2] = dcrs(g(step1[2]) * C24 - g(step1[3]) * C8); + step2[3] = dcrs(g(step1[2]) * C8 + g(step1[3]) * C24); + step2[4] = step1[4] + step1[5]; + step2[5] = step1[4] - step1[5]; + step2[6] = -step1[6] + step1[7]; + step2[7] = step1[6] + step1[7]; + step2[8] = step1[8]; + step2[15] = step1[15]; + step2[9] = dcrs(-g(step1[9]) * C8 + g(step1[14]) * C24); + step2[14] = dcrs(g(step1[9]) * C24 + g(step1[14]) * C8); + step2[10] = dcrs(-g(step1[10]) * C24 - g(step1[13]) * C8); + step2[13] = dcrs(-g(step1[10]) * C8 + g(step1[13]) * C24); + step2[11] = step1[11]; + step2[12] = step1[12]; + step2[16] = step1[16] + step1[19]; + step2[17] = step1[17] + step1[18]; + step2[18] = step1[17] - step1[18]; + step2[19] = step1[16] - step1[19]; + step2[20] = -step1[20] + step1[23]; + step2[21] = -step1[21] + step1[22]; + step2[22] = step1[21] + step1[22]; + step2[23] = step1[20] + step1[23]; + step2[24] = step1[24] + step1[27]; + step2[25] = step1[25] + step1[26]; + step2[26] = step1[25] - step1[26]; + step2[27] = step1[24] - step1[27]; + step2[28] = -step1[28] + step1[31]; + step2[29] = -step1[29] + step1[30]; + step2[30] = step1[29] + step1[30]; + step2[31] = step1[28] + step1[31]; + step1[0] = step2[0] + step2[3]; + step1[1] = step2[1] + step2[2]; + step1[2] = step2[1] - step2[2]; + step1[3] = step2[0] - step2[3]; + step1[4] = step2[4]; + step1[5] = dcrs((g(step2[6]) - g(step2[5])) * C16); + step1[6] = dcrs((g(step2[5]) + g(step2[6])) * C16); + step1[7] = step2[7]; + step1[8] = step2[8] + step2[11]; + step1[9] = step2[9] + step2[10]; + step1[10] = step2[9] - step2[10]; + step1[11] = step2[8] - step2[11]; + step1[12] = -step2[12] + step2[15]; + step1[13] = -step2[13] + step2[14]; + step1[14] = step2[13] + step2[14]; + step1[15] = step2[12] + step2[15]; + step1[16] = step2[16]; + step1[17] = step2[17]; + step1[18] = dcrs(-g(step2[18]) * C8 + g(step2[29]) * C24); + step1[29] = dcrs(g(step2[18]) * C24 + g(step2[29]) * C8); + step1[19] = dcrs(-g(step2[19]) * C8 + g(step2[28]) * C24); + step1[28] = dcrs(g(step2[19]) * C24 + g(step2[28]) * C8); + step1[20] = dcrs(-g(step2[20]) * C24 - g(step2[27]) * C8); + step1[27] = dcrs(-g(step2[20]) * C8 + g(step2[27]) * C24); + step1[21] = dcrs(-g(step2[21]) * C24 - g(step2[26]) * C8); + step1[26] = dcrs(-g(step2[21]) * C8 + g(step2[26]) * C24); + step1[22] = step2[22]; + step1[23] = step2[23]; + step1[24] = step2[24]; + step1[25] = step2[25]; + step1[30] = step2[30]; + step1[31] = step2[31]; + step2[0] = step1[0] + step1[7]; + step2[1] = step1[1] + step1[6]; + step2[2] = step1[2] + step1[5]; + step2[3] = step1[3] + step1[4]; + step2[4] = step1[3] - step1[4]; + step2[5] = step1[2] - step1[5]; + step2[6] = step1[1] - step1[6]; + step2[7] = step1[0] - step1[7]; + step2[8] = step1[8]; + step2[9] = step1[9]; + step2[10] = dcrs((-g(step1[10]) + g(step1[13])) * C16); + step2[13] = dcrs((g(step1[10]) + g(step1[13])) * C16); + step2[11] = dcrs((-g(step1[11]) + g(step1[12])) * C16); + step2[12] = dcrs((g(step1[11]) + g(step1[12])) * C16); + step2[14] = step1[14]; + step2[15] = step1[15]; + step2[16] = step1[16] + step1[23]; + step2[17] = step1[17] + step1[22]; + step2[18] = step1[18] + step1[21]; + step2[19] = step1[19] + step1[20]; + step2[20] = step1[19] - step1[20]; + step2[21] = step1[18] - step1[21]; + step2[22] = step1[17] - step1[22]; + step2[23] = step1[16] - step1[23]; + step2[24] = -step1[24] + step1[31]; + step2[25] = -step1[25] + step1[30]; + step2[26] = -step1[26] + step1[29]; + step2[27] = -step1[27] + step1[28]; + step2[28] = step1[27] + step1[28]; + step2[29] = step1[26] + step1[29]; + step2[30] = step1[25] + step1[30]; + step2[31] = step1[24] + step1[31]; + step1[0] = step2[0] + step2[15]; + step1[1] = step2[1] + step2[14]; + step1[2] = step2[2] + step2[13]; + step1[3] = step2[3] + step2[12]; + step1[4] = step2[4] + step2[11]; + step1[5] = step2[5] + step2[10]; + step1[6] = step2[6] + step2[9]; + step1[7] = step2[7] + step2[8]; + step1[8] = step2[7] - step2[8]; + step1[9] = step2[6] - step2[9]; + step1[10] = step2[5] - step2[10]; + step1[11] = step2[4] - step2[11]; + step1[12] = step2[3] - step2[12]; + step1[13] = step2[2] - step2[13]; + step1[14] = step2[1] - step2[14]; + step1[15] = step2[0] - step2[15]; + step1[16..32].copy_from_slice(&step2[16..32]); + for i in 0..16 { + output[i] = step1[i] + step1[31 - i]; + output[31 - i] = step1[i] - step1[31 - i]; + } +} + +pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) { + let (x0, x1, x2, x3) = (input[0] as i64, input[1] as i64, input[2] as i64, input[3] as i64); + if x0 | x1 | x2 | x3 == 0 { + output[..4].fill(0); + return; + } + let s0 = S1 * x0 + S4 * x2 + S2 * x3; + let s1 = S2 * x0 - S1 * x2 - S4 * x3; + let s3 = S3 * x1; + let s7 = (x0 - x2 + x3) as i32 as i64; + let s2 = S3 * s7; + output[0] = dcrs(s0 + s3); + output[1] = dcrs(s1 + s3); + output[2] = dcrs(s2); + output[3] = dcrs(s0 + s1 - s3); +} + +pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut x0 = g(input[7]); + let mut x1 = g(input[0]); + let mut x2 = g(input[5]); + let mut x3 = g(input[2]); + let mut x4 = g(input[3]); + let mut x5 = g(input[4]); + let mut x6 = g(input[1]); + let mut x7 = g(input[6]); + if x0 | x1 | x2 | x3 | x4 | x5 | x6 | x7 == 0 { + output[..8].fill(0); + return; + } + let s0 = C2 * x0 + C30 * x1; + let s1 = C30 * x0 - C2 * x1; + let s2 = C10 * x2 + C22 * x3; + let s3 = C22 * x2 - C10 * x3; + let s4 = C18 * x4 + C14 * x5; + let s5 = C14 * x4 - C18 * x5; + let s6 = C26 * x6 + C6 * x7; + let s7 = C6 * x6 - C26 * x7; + x0 = dcrs(s0 + s4) as i64; + x1 = dcrs(s1 + s5) as i64; + x2 = dcrs(s2 + s6) as i64; + x3 = dcrs(s3 + s7) as i64; + x4 = dcrs(s0 - s4) as i64; + x5 = dcrs(s1 - s5) as i64; + x6 = dcrs(s2 - s6) as i64; + x7 = dcrs(s3 - s7) as i64; + let (t0, t1, t2, t3) = (x0, x1, x2, x3); + let s4 = C8 * x4 + C24 * x5; + let s5 = C24 * x4 - C8 * x5; + let s6 = -C24 * x6 + C8 * x7; + let s7 = C8 * x6 + C24 * x7; + x0 = (t0 + t2) as i32 as i64; + x1 = (t1 + t3) as i32 as i64; + x2 = (t0 - t2) as i32 as i64; + x3 = (t1 - t3) as i32 as i64; + x4 = dcrs(s4 + s6) as i64; + x5 = dcrs(s5 + s7) as i64; + x6 = dcrs(s4 - s6) as i64; + x7 = dcrs(s5 - s7) as i64; + let s2 = C16 * (x2 + x3); + let s3 = C16 * (x2 - x3); + let s6 = C16 * (x6 + x7); + let s7 = C16 * (x6 - x7); + x2 = dcrs(s2) as i64; + x3 = dcrs(s3) as i64; + x6 = dcrs(s6) as i64; + x7 = dcrs(s7) as i64; + output[0] = x0 as i32; + output[1] = -x4 as i32; + output[2] = x6 as i32; + output[3] = -x2 as i32; + output[4] = x3 as i32; + output[5] = -x7 as i32; + output[6] = x5 as i32; + output[7] = -x1 as i32; +} + +pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) { + let g = |v: i32| v as i64; + let mut x = [ + g(input[15]), g(input[0]), g(input[13]), g(input[2]), + g(input[11]), g(input[4]), g(input[9]), g(input[6]), + g(input[7]), g(input[8]), g(input[5]), g(input[10]), + g(input[3]), g(input[12]), g(input[1]), g(input[14]), + ]; + if x.iter().all(|&v| v == 0) { + output[..16].fill(0); + return; + } + let mut s = [0i64; 16]; + s[0] = x[0] * C1 + x[1] * C31; + s[1] = x[0] * C31 - x[1] * C1; + s[2] = x[2] * C5 + x[3] * C27; + s[3] = x[2] * C27 - x[3] * C5; + s[4] = x[4] * C9 + x[5] * C23; + s[5] = x[4] * C23 - x[5] * C9; + s[6] = x[6] * C13 + x[7] * C19; + s[7] = x[6] * C19 - x[7] * C13; + s[8] = x[8] * C17 + x[9] * C15; + s[9] = x[8] * C15 - x[9] * C17; + s[10] = x[10] * C21 + x[11] * C11; + s[11] = x[10] * C11 - x[11] * C21; + s[12] = x[12] * C25 + x[13] * C7; + s[13] = x[12] * C7 - x[13] * C25; + s[14] = x[14] * C29 + x[15] * C3; + s[15] = x[14] * C3 - x[15] * C29; + for i in 0..8 { + x[i] = dcrs(s[i] + s[i + 8]) as i64; + x[i + 8] = dcrs(s[i] - s[i + 8]) as i64; + } + s[0..8].copy_from_slice(&x[0..8]); + s[8] = x[8] * C4 + x[9] * C28; + s[9] = x[8] * C28 - x[9] * C4; + s[10] = x[10] * C20 + x[11] * C12; + s[11] = x[10] * C12 - x[11] * C20; + s[12] = -x[12] * C28 + x[13] * C4; + s[13] = x[12] * C4 + x[13] * C28; + s[14] = -x[14] * C12 + x[15] * C20; + s[15] = x[14] * C20 + x[15] * C12; + for i in 0..4 { + x[i] = (s[i] + s[i + 4]) as i32 as i64; + x[i + 4] = (s[i] - s[i + 4]) as i32 as i64; + } + for i in 0..4 { + x[8 + i] = dcrs(s[8 + i] + s[12 + i]) as i64; + x[12 + i] = dcrs(s[8 + i] - s[12 + i]) as i64; + } + s[0..4].copy_from_slice(&x[0..4]); + s[8..12].copy_from_slice(&x[8..12]); + s[4] = x[4] * C8 + x[5] * C24; + s[5] = x[4] * C24 - x[5] * C8; + s[6] = -x[6] * C24 + x[7] * C8; + s[7] = x[6] * C8 + x[7] * C24; + s[12] = x[12] * C8 + x[13] * C24; + s[13] = x[12] * C24 - x[13] * C8; + s[14] = -x[14] * C24 + x[15] * C8; + s[15] = x[14] * C8 + x[15] * C24; + x[0] = (s[0] + s[2]) as i32 as i64; + x[1] = (s[1] + s[3]) as i32 as i64; + x[2] = (s[0] - s[2]) as i32 as i64; + x[3] = (s[1] - s[3]) as i32 as i64; + x[4] = dcrs(s[4] + s[6]) as i64; + x[5] = dcrs(s[5] + s[7]) as i64; + x[6] = dcrs(s[4] - s[6]) as i64; + x[7] = dcrs(s[5] - s[7]) as i64; + x[8] = (s[8] + s[10]) as i32 as i64; + x[9] = (s[9] + s[11]) as i32 as i64; + x[10] = (s[8] - s[10]) as i32 as i64; + x[11] = (s[9] - s[11]) as i32 as i64; + x[12] = dcrs(s[12] + s[14]) as i64; + x[13] = dcrs(s[13] + s[15]) as i64; + x[14] = dcrs(s[12] - s[14]) as i64; + x[15] = dcrs(s[13] - s[15]) as i64; + for (i, j) in [(2usize, 3usize), (6, 7), (10, 11), (14, 15)] { + let a = C16 * (x[i] + x[j]); + let b = C16 * (x[i] - x[j]); + x[i] = dcrs(a) as i64; + x[j] = dcrs(b) as i64; + } + let o = [ + x[0], -x[8], x[12], -x[4], x[6], x[14], x[10], x[2], + x[3], x[11], x[15], x[7], x[5], x[13], x[9], -x[1], + ]; + for (i, &v) in o.iter().enumerate() { + output[i] = v as i32; + } +} + +/// One 2D transform pass: `rows` then `cols` then add with the block's +/// rounding shift (vpx_idct4x4_16_add_c and friends; vp9_iht* for the +/// ADST combinations). +pub(crate) fn inverse_transform_add( + tx_size: usize, + tx_type: usize, + coeffs: &[i32], + dest: &mut [u8], + off: usize, + stride: usize, + lossless: bool, +) { + if lossless { + iwht4x4_add(coeffs, &mut dest[off..], stride); + return; + } + if tx_size == TX_32X32 { + let mut out = [0i32; 1024]; + for i in 0..32 { + idct32(&coeffs[i * 32..], &mut out[i * 32..]); + } + let mut temp_in = [0i32; 32]; + let mut temp_out = [0i32; 32]; + for i in 0..32 { + for (j, ti) in temp_in.iter_mut().enumerate() { + *ti = out[j * 32 + i]; + } + idct32(&temp_in, &mut temp_out); + for j in 0..32 { + let d = &mut dest[off + j * stride + i]; + *d = clip_add(*d, (temp_out[j] + 32) >> 6); + } + } + return; + } + let (n, shift) = match tx_size { + TX_4X4 => (4usize, 4u32), + TX_8X8 => (8, 5), + _ => (16, 6), + }; + // ADST_DCT codes ADST vertical (= cols pass); DCT_ADST horizontal. + let adst_cols = matches!(tx_type, ADST_DCT | ADST_ADST); + let adst_rows = matches!(tx_type, DCT_ADST | ADST_ADST); + let (row_fn, col_fn): (fn(&[i32], &mut [i32]), fn(&[i32], &mut [i32])) = match tx_size { + TX_4X4 => ( + if adst_rows { iadst4 } else { idct4 }, + if adst_cols { iadst4 } else { idct4 }, + ), + TX_8X8 => ( + if adst_rows { iadst8 } else { idct8 }, + if adst_cols { iadst8 } else { idct8 }, + ), + _ => ( + if adst_rows { iadst16 } else { idct16 }, + if adst_cols { iadst16 } else { idct16 }, + ), + }; + let mut out = vec![0i32; n * n]; + for i in 0..n { + row_fn(&coeffs[i * n..], &mut out[i * n..]); + } + let mut temp_in = vec![0i32; n]; + let mut temp_out = vec![0i32; n]; + for i in 0..n { + for j in 0..n { + temp_in[j] = out[j * n + i]; + } + col_fn(&temp_in, &mut temp_out); + for j in 0..n { + let d = &mut dest[off + j * stride + i]; + *d = clip_add(*d, (temp_out[j] + (1 << (shift - 1))) >> shift); + } + } +} + diff --git a/crates/ec-vp9/tests/dump_probe.rs b/crates/ec-vp9/tests/dump_probe.rs new file mode 100644 index 00000000..fbcece6b --- /dev/null +++ b/crates/ec-vp9/tests/dump_probe.rs @@ -0,0 +1,31 @@ +mod ivf; +use ec_vp9::decode::Decoder; +#[test] +fn diff_stats() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bytes = std::fs::read(dir.join("fixtures/vp9/key-320.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut d = Decoder::new(); + let pic = d.decode(&frames[0].data).unwrap().unwrap(); + let refout = std::process::Command::new("ffmpeg") + .args(["-v","error","-i",dir.join("fixtures/vp9/key-320.ivf").to_str().unwrap(), + "-frames:v","1","-f","rawvideo","-pix_fmt","yuv420p","-"]) + .output().unwrap().stdout; + let w = 320usize; + let mut sb_match = [[0usize; 5]; 4]; + let mut sb_total = [[0usize; 5]; 4]; + let mut first: Option<(usize, usize)> = None; + for y in 0..240 { + for x in 0..320 { + let a = pic.y[y * pic.stride + x]; + let b = refout[y * w + x]; + let (sy, sx) = (y / 64, x / 64); + sb_total[sy][sx] += 1; + if a == b { sb_match[sy][sx] += 1; } else if first.is_none() { first = Some((x, y)); } + } + } + println!("first diff at {:?}", first); + for (i, row) in sb_match.iter().enumerate() { + println!("sb row {i}: {:?}", row.iter().zip(sb_total[i].iter()).map(|(m, t)| format!("{}/{}", m, t)).collect::>()); + } +} diff --git a/crates/ec-vp9/tests/ivf.rs b/crates/ec-vp9/tests/ivf.rs new file mode 100644 index 00000000..42ee5b9e --- /dev/null +++ b/crates/ec-vp9/tests/ivf.rs @@ -0,0 +1,60 @@ +//! Minimal IVF demuxing for the ec-vp9 test fixtures (the DKIF +//! container; only what the witnesses need). + +/// One IVF frame: (pts, payload). +pub struct IvfFrame { + /// Presentation timestamp from the IVF frame header. + #[allow(dead_code)] + pub pts: u64, + /// The compressed VP9 payload (possibly a superframe chunk). + #[allow(dead_code)] + pub data: Vec, +} + +/// The frame chunk's VP9 uncompressed-header `show_frame` bit lives +/// behind the marker/profile bits; the witnesses only need a presence +/// census, so this walks enough of the header to find it (spec 6.2). +#[allow(dead_code)] +pub fn show_frame(data: &[u8]) -> bool { + // Bit layout: 2 marker, 2 profile, 1 show_existing, 1 frame_type, + // 1 show_frame (bit 7 of byte 0, LSB-first). + (data[0] >> 7) & 1 == 1 +} + +/// Parse an IVF file into (fourcc, width, height, frames). +pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { + assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); + let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); + let width = u16::from_le_bytes([bytes[12], bytes[13]]); + let height = u16::from_le_bytes([bytes[14], bytes[15]]); + let mut pos = hdr_len; + let mut frames = Vec::new(); + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes([ + bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3], + ]) as usize; + let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap()); + pos += 12; + if pos + sz > bytes.len() { + break; + } + frames.push(IvfFrame { + pts, + data: bytes[pos..pos + sz].to_vec(), + }); + pos += sz; + } + (fourcc, width, height, frames) +} + +/// Root of the workspace checkout this test runs in (crates/ec-vp9/../..). +pub fn fixture_dir() -> Option { + let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/bitstreams"); + if bitstreams.is_dir() { + Some(bitstreams) + } else { + None + } +} diff --git a/crates/ec-vp9/tests/keyframe_exact.rs b/crates/ec-vp9/tests/keyframe_exact.rs new file mode 100644 index 00000000..3069ede4 --- /dev/null +++ b/crates/ec-vp9/tests/keyframe_exact.rs @@ -0,0 +1,137 @@ +//! M1 witness: key-frame decode is byte-exact against ffmpeg's libvpx +//! (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt yuv420p -`), plus +//! the lane's named refusals. + +mod ivf; + +use ec_vp9::decode::Decoder; + +/// Generate the small all-keyframe fixture with libvpx if it is absent +/// (2 keyframes of 320x240 testsrc2, realtime cpu-used 4). +fn ensure_fixture(path: &std::path::Path) { + if path.exists() { + return; + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + let st = std::process::Command::new("ffmpeg") + .args([ + "-y", + "-f", "lavfi", + "-i", "testsrc2=size=320x240:rate=30:duration=1", + "-pix_fmt", "yuv420p", + "-c:v", "libvpx-vp9", + "-g", "1", + "-cpu-used", "4", + "-deadline", "realtime", + "-frames:v", "2", + ]) + .arg(path) + .output() + .expect("ffmpeg with libvpx-vp9 must be on PATH for the witnesses"); + assert!(st.status.success(), "fixture generation failed: {st:?}"); +} + +/// ffmpeg's decoded rawvideo byte stream for the same file. +fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg must be on PATH for the witnesses"); + assert!(out.status.success(), "ffmpeg failed on {path:?}"); + out.stdout +} + +/// Decode every frame of an IVF with our decoder and compare each SHOWN +/// frame's planes against ffmpeg's byte stream. +fn compare(path: &std::path::Path) { + let bytes = std::fs::read(path).unwrap(); + let (_fourcc, _w, _h, frames) = ivf::parse_ivf(&bytes); + let reference = ffmpeg_raw_yuv(path); + + let mut decoder = Decoder::new(); + let mut ref_pos = 0usize; + let mut shown = 0usize; + for frame in &frames { + let pic = decoder.decode(&frame.data).expect("decode must succeed"); + if let Some(pic) = pic { + let (w, h) = (pic.width as usize, pic.height as usize); + assert_eq!(w, 320, "fixture width"); + assert_eq!(h, 240, "fixture height"); + let uv = (w / 2) * (h / 2); + let fr = &reference[ref_pos..ref_pos + w * h + 2 * uv]; + ref_pos += w * h + 2 * uv; + let want_y = &fr[..w * h]; + let want_u = &fr[w * h..w * h + uv]; + let want_v = &fr[w * h + uv..]; + assert_eq!(pic.y.len(), want_y.len()); + assert_eq!(pic.u.len(), want_u.len()); + assert_eq!(pic.v.len(), want_v.len()); + for (i, (&a, &b)) in pic.y.iter().zip(want_y).enumerate() { + assert_eq!(a, b, "Y plane mismatch at pixel ({}, {}) frame {shown}", i % w, i / w); + } + for (i, (&a, &b)) in pic.u.iter().zip(want_u).enumerate() { + assert_eq!(a, b, "U plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); + } + for (i, (&a, &b)) in pic.v.iter().zip(want_v).enumerate() { + assert_eq!(a, b, "V plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); + } + shown += 1; + } + } + assert_eq!(shown, 2, "both keyframes are shown"); +} + +#[test] +fn keyframes_match_ffmpeg() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vp9"); + let path = dir.join("key-320.ivf"); + ensure_fixture(&path); + compare(&path); +} + +#[test] +fn inter_is_named_unsupported() { + let Some(dir) = ivf::fixture_dir() else { return }; + // The altref clip contains hidden (inter) frames. + let path = dir.join("vp9-superframe-altref.ivf"); + let bytes = std::fs::read(&path).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let mut saw_inter = false; + let mut saw_named = false; + for frame in &frames { + match decoder.decode(&frame.data) { + Ok(_) => {} + Err(e) => { + saw_inter = true; + let msg = format!("{e}"); + if msg.contains("vp9 inter") { + saw_named = true; + } + break; + } + } + } + assert!(saw_inter, "the altref fixture must contain a refused frame"); + assert!(saw_named, "the refusal must name 'vp9 inter'"); +} + +#[test] +fn profile1_444_is_named_unsupported() { + let Some(dir) = ivf::fixture_dir() else { return }; + let path = dir.join("vp9-profile1-444.ivf"); + let bytes = std::fs::read(&path).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let err = decoder + .decode(&frames[0].data) + .expect_err("profile 1 4:4:4 must be refused"); + assert!( + format!("{err}").contains("vp9 profile 1"), + "the refusal must name the profile: {err}" + ); +} diff --git a/lanes/vp9kf.charter.md b/lanes/vp9kf.charter.md new file mode 100644 index 00000000..4ab9ff2e --- /dev/null +++ b/lanes/vp9kf.charter.md @@ -0,0 +1,43 @@ +# lane-vp9-kf — first VP9 software-decode lane: crate `ec-vp9` + +## Charter (keep-rule) + +A shown profile-0 8-bit 4:2:0 **KEYFRAME**'s Y/U/V planes are **byte-exact** against +`ffmpeg -v error -i -frames:v 1 -f rawvideo -pix_fmt yuv420p -`. +Close PSNR is a fail. libvpx quirks ported verbatim, including dead guards. + +## Scope + +- New crate `crates/ec-vp9` in worktree `/home/user/Documents/Code/Rust/edith_codecs-vp9`, + branch `lane-vp9-kf`, base `29f35b77`. Workspace `Cargo.toml` lists crates via the + `members = ["crates/*"]` glob exactly like `ec-vp8` — nothing to add there. +- Deps: `ec-core` + `ec-vp9-syntax` only (uncompressed header, superframe split, dc_q/ac_q). + libvpx/ffmpeg are test oracles, never runtime code. `deny(unsafe_code)`. + +## Modules + +`bool` (range coder, spec 8.3), `header` (thin wrap of `Vp9Parser` + compressed header), +`decode` (Decoder::new / decode -> Option, superframe split first), `stream` (IVF +DKIF/VP90), `modes` (partition + intra mode info), `intra` (predictors), `transform` +(DCT/ADST/WHT), `tokens` (coefficient decoding), `loopfilter`, `tables`. **No `mc.rs` +this lane.** + +## Refusals (named, via `Error::unsupported`) + +- VP9 inter frames — `vp9 inter` +- profile != 0 — `vp9 profile N` (pinned: `fixtures/bitstreams/vp9-profile1-444.ivf`) +- subsampling != 4:2:0 — `vp9 4:2:2` / `vp9 4:4:4` +- `show_existing_frame`: return the buffered reference plane, never pretend to decode. + +## Out of scope + +inter/MC, profile 1/3 pixels, 10-bit, edith seat, HEVC, any edit to `ec-vp8`, `ec-hw`, +`edith`, or `ec-vp9-syntax`. + +## Verify (scoped only) + +``` +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo check -p ec-vp9 +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --lib +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --test keyframe_exact -- --nocapture +``` diff --git a/lanes/vp9kf.report.md b/lanes/vp9kf.report.md new file mode 100644 index 00000000..0e8ab143 --- /dev/null +++ b/lanes/vp9kf.report.md @@ -0,0 +1,81 @@ +# lane-vp9-kf report — first VP9 software-decode lane (`ec-vp9`) + +Status: **HANDOFF — decode pipeline complete end-to-end, byte-exactness not yet achieved.** +Charter file: `lanes/vp9kf.charter.md`. Branch `lane-vp9-kf` (base 29f35b77). NOT merged, NOT pushed. + +## What works (verified by running code) + +- Crate `crates/ec-vp9` compiles (`cargo check -p ec-vp9` clean of errors; a handful of + unused-variable warnings remain). `deny(unsafe_code)`, deps = `ec-core` + `ec-vp9-syntax` only. +- `bool.rs` — VP9 range coder (spec 8.3.2) with carry-propagating reference-encoder + roundtrip tests: **7/7 lib tests pass**. +- Full keyframe pipeline runs end-to-end on `fixtures/vp9/key-320.ivf` + (320x240, 2 keyframes, generated with the charter's ffmpeg command): superframe split → + `Vp9Parser` uncompressed header → compressed header (tx_mode, tx/coef/skip diff-updates + with `inv_remap_prob`/`decode_term_subexp` verbatim from libvpx v1.15.0) → tiles + (4-byte size prefixes) → partition recursion → intra mode info → tokens → + intra prediction → transforms → residual add → loop filter → cropped `Picture`. +- `profile1_444_is_named_unsupported` PASSES (refuses `vp9 profile 1` via + `fixtures/bitstreams/vp9-profile1-444.ivf`). +- Constant tables (`src/tables/gen_tables.rs`) extracted mechanically from libvpx v1.15.0 + (coefficient probs incl. band-0 padding, pareto8 model, scans + neighbors, kf/uv mode + probs, partition/tx/skip probs, common_data lookups, subsize/ss_size lookups). + +## What fails + +- `keyframes_match_ffmpeg` — our reconstruction diverges from + `ffmpeg -v error -i -frames:v 1 -f rawvideo -pix_fmt yuv420p -` at pixel (0,0) + (ours 133 vs 72); ~90% of pixels are the plane-fill value, i.e. the entropy decode or + reconstruction is systematically wrong from the first transform block. +- `inter_is_named_unsupported` — refused frames do error, but the panic-vs-Error path was + being reworked when the budget ran out; needs a re-run after the entropy fix. + +## HANDOFF — where to look next (in order of suspicion) + +1. **Entropy desync AT THE UV-MODE READ of the first block** (latest probe): a Python + replica of the bool decode over the same tile bytes agrees with our Rust through + partition(0)/skip(0)/y-mode(2=H), but the uv-mode read diverges (replica: 7=D207 vs + Rust: 4=D135). Check `kf_uv_probs`/`KF_UV_MODE_PROB` row indexing (y*9) and the + `UV_MODE_TREE` leaf mapping (DC,V,H,D45,D135,D117,D153,D207,D63,TM order) against the + replica in the lane transcript. The first tx block then EOBs immediately (eob bit 0), + i.e. the correct (0,0) is pure prediction (129 for H at the frame corner) + later + blocks' overlap; our residual decode never even starts. +2. **Entropy desync at/inside the first transform block.** Evidence: first-block probs + verified correct (`8x8 band0 ctx0 = [125,34,187]`), compressed header consumed 82 bytes + with 0 overreads, defaults untouched by updates — so the divergence starts inside token + reading or right after it. Dump the first 64x64's full read sequence with `EC_VP9_TRACE=1` + and hand-check against the spec 8.5.2 token flow. +2. **Verify the "no partition symbol at 4x4 level" decision** (`decode.rs`, + `if n4 == 1 { 0 }`): our stream traced 3 extra NONE reads then SPLIT(=subsize 255) + before the removal, strongly indicating the spec behavior (partition only >= 8x8) — but + double-check `has_rows/has_cols` edge handling at 4x4 against `read_partition` in + `~/.cache/vp9-ref/vp9_decodeframe.c:1195`. +3. **Sub-8x8 chroma gating**: implemented as "chroma tokens/prediction once per 8x8, on the + TL sub-block" (`decode.rs`, `sub && plane != 0` gate). Verify against libvpx + (`predict_and_reconstruct_intra_block` runs chroma per sub-block; the real gating lives in + `read_intra_frame_mode_info`/`n4_w` semantics — confirm). +4. **Dequant**: `dq=[38,44]` for q=130 — sanity-check `dc_q(8,130)` against the spec 8.6.1 + table (the syntax crate's `dc_q`/`ac_q` are trusted, but the wiring + `segment_dequant(seg)[luma_dc|luma_ac]` should be printed once per frame). +5. **Loop filter edge rules** (`loopfilter.rs`): per-edge re-derivation of libvpx's + `build_masks` semantics (documented in the module head); the 32x32/64x64 border + promotions and the z-(0,0)-slot chroma rule for 8x8 regions need one careful re-read + against `vp9_loopfilter.c:652-790` once pixels match pre-filter. +6. Debug traces still present: `EC_VP9_DBG` eprintlns in `header.rs`, `tokens.rs`, + `loopfilter.rs` — remove when done. `tests/dump_probe.rs` is a scratch harness; delete. + +## Verification commands + +``` +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo check -p ec-vp9 +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --lib +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --test keyframe_exact -- --nocapture +``` + +## Provenance notes + +- libvpx v1.15.0 reference sources cached at `~/.cache/vp9-ref/` (test oracle; never linked). +- Table extractor: brace-matching + macro-resolving Python over the C initializers + (comments stripped, all arrays flattened, ragged band-0 padded). +- No edits to `ec-vp8`, `ec-hw`, `edith`, or `ec-vp9-syntax`. Workspace `Cargo.toml` untouched + (members glob covers the new crate, same as `ec-vp8`).