Merge branch 'lane-av1dec' (r1): software AV1 key-frame decoder core
Browse files at this commit4 changed files +887 -79
- crates/ec-av1/src/decode.rs +773 -0
- crates/ec-av1/src/encode.rs +20 -0
- crates/ec-av1/src/lib.rs +1 -0
- crates/ec-av1/src/msac.rs +93 -79
crates/ec-av1/src/decode.rsadded+773 -0
| @@ -0,0 +1,773 @@ | ||
| 1 | +//! Software decoder for this crate's own key-frame tile payloads (spec 5.11), | |
| 2 | +//! the reader half of [`crate::tile`]'s writer. | |
| 3 | +//! | |
| 4 | +//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is | |
| 5 | +//! touching its partition search), so nothing here imports its private | |
| 6 | +//! helpers: the handful of `pub(crate)` items it already exposes | |
| 7 | +//! ([`crate::tile::block_grid`], [`crate::tile::has_half`], | |
| 8 | +//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused, | |
| 9 | +//! and everything else (the partition/coefficient context arithmetic, the | |
| 10 | +//! scan table) is a from-spec reimplementation kept in step with the writer by | |
| 11 | +//! the gate tests below rather than by sharing code with it. | |
| 12 | +//! | |
| 13 | +//! # Scope (round 1) | |
| 14 | +//! Key frames only, and only the shapes the encoder actually still needs to | |
| 15 | +//! prove itself against: every coded block is `DC_PRED` (this crate's mode | |
| 16 | +//! search names other intra modes, but a decoder for those needs the | |
| 17 | +//! directional-prediction edge-reach plumbing [`crate::intra::predict`] | |
| 18 | +//! already carries; wiring it up is round 2), never skipped, and every | |
| 19 | +//! superblock is a whole number of 64x64 units (a frame whose true edge falls | |
| 20 | +//! inside one, forcing the gathered-CDF partial-superblock path, is round 2 | |
| 21 | +//! too). Anything outside that refuses with [`Error::unsupported`] rather than | |
| 22 | +//! silently miscoding. | |
| 23 | + | |
| 24 | +use ec_core::{Error, Result}; | |
| 25 | + | |
| 26 | +use crate::cdf; | |
| 27 | +use crate::cdf_state::{Cdfs, TxbSet, TxbTables}; | |
| 28 | +use crate::encode::Picture; | |
| 29 | +use crate::msac::SymbolDecoder; | |
| 30 | +use crate::tile::{INTRA_MODE_CTX, block_grid, has_half}; | |
| 31 | +use crate::transform::dequant_and_inverse; | |
| 32 | + | |
| 33 | +const PARTITION_NONE: usize = 0; | |
| 34 | +const PARTITION_SPLIT: usize = 3; | |
| 35 | +const SB_MI: u32 = 16; | |
| 36 | +const BLOCK_MI: u32 = 8; | |
| 37 | +const SUB_MI: u32 = 4; | |
| 38 | +const SB: usize = 64; | |
| 39 | +const BLOCK: usize = 32; | |
| 40 | +const SUB: usize = 16; | |
| 41 | +const TX32: usize = 32; | |
| 42 | +const TX16: usize = 16; | |
| 43 | +const TX8: usize = 8; | |
| 44 | +const DC_PRED: usize = 0; | |
| 45 | +const NUM_BASE_LEVELS: i32 = 2; | |
| 46 | +const COEFF_BASE_RANGE: i32 = 12; | |
| 47 | +const BR_STEP: i32 = 3; | |
| 48 | +const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE; | |
| 49 | + | |
| 50 | +fn unsupported(what: impl Into<String>) -> Error { | |
| 51 | + Error::unsupported("AV1 tile", what.into()) | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs | |
| 55 | +/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the | |
| 56 | +/// same rule. | |
| 57 | +fn q_ctx_of(base_q_idx: u8) -> usize { | |
| 58 | + match base_q_idx { | |
| 59 | + 0..=20 => 0, | |
| 60 | + 21..=60 => 1, | |
| 61 | + 61..=120 => 2, | |
| 62 | + _ => 3, | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk | |
| 67 | +/// [`crate::tile`]'s writer generates its scan tables with. | |
| 68 | +fn default_scan(side: usize) -> Vec<u16> { | |
| 69 | + let mut scan = Vec::with_capacity(side * side); | |
| 70 | + for d in 0..(2 * side - 1) { | |
| 71 | + let lo = d.saturating_sub(side - 1); | |
| 72 | + let hi = d.min(side - 1); | |
| 73 | + let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16); | |
| 74 | + if d % 2 == 0 { | |
| 75 | + scan.extend(diagonal.rev()); | |
| 76 | + } else { | |
| 77 | + scan.extend(diagonal); | |
| 78 | + } | |
| 79 | + } | |
| 80 | + scan | |
| 81 | +} | |
| 82 | + | |
| 83 | +fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize { | |
| 84 | + match scan_idx { | |
| 85 | + 0 => 0, | |
| 86 | + i if i <= area / 8 => 1, | |
| 87 | + i if i <= area / 4 => 2, | |
| 88 | + _ => 3, | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 { | |
| 93 | + if row >= side || col >= side { | |
| 94 | + 0 | |
| 95 | + } else { | |
| 96 | + grid[row * side + col] | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 100 | +fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { | |
| 101 | + if row == 0 && col == 0 { | |
| 102 | + return 0; | |
| 103 | + } | |
| 104 | + let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] | |
| 105 | + .iter() | |
| 106 | + .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3)) | |
| 107 | + .sum(); | |
| 108 | + let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize; | |
| 109 | + (((mag + 1) >> 1).min(4) as usize) + offset | |
| 110 | +} | |
| 111 | + | |
| 112 | +fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { | |
| 113 | + let mag: i32 = [(1, 0), (0, 1), (1, 1)] | |
| 114 | + .iter() | |
| 115 | + .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs()) | |
| 116 | + .sum(); | |
| 117 | + let mag = (((mag + 1) >> 1).min(6)) as usize; | |
| 118 | + if row == 0 && col == 0 { | |
| 119 | + mag | |
| 120 | + } else if row < 2 && col < 2 { | |
| 121 | + mag + 7 | |
| 122 | + } else { | |
| 123 | + mag + 14 | |
| 124 | + } | |
| 125 | +} | |
| 126 | + | |
| 127 | +fn dc_vote(dc: Option<bool>) -> i32 { | |
| 128 | + match dc { | |
| 129 | + None => 0, | |
| 130 | + Some(true) => -1, | |
| 131 | + Some(false) => 1, | |
| 132 | + } | |
| 133 | +} | |
| 134 | + | |
| 135 | +fn dc_sign_ctx(vote: i32) -> usize { | |
| 136 | + match vote.signum() { | |
| 137 | + 0 => 0, | |
| 138 | + -1 => 1, | |
| 139 | + _ => 2, | |
| 140 | + } | |
| 141 | +} | |
| 142 | + | |
| 143 | +/// The remainder of a level the base and base-range syntax could not reach | |
| 144 | +/// (spec 5.11.40): its bit length in unary, then that many of its own bits, | |
| 145 | +/// most significant first — the exact inverse of [`crate::tile::write_golomb`]. | |
| 146 | +fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> { | |
| 147 | + let mut length = 1u32; | |
| 148 | + while dec.literal(1) == 0 { | |
| 149 | + length += 1; | |
| 150 | + if length > 20 { | |
| 151 | + return Err(unsupported("a Golomb tail longer than this decoder reads")); | |
| 152 | + } | |
| 153 | + } | |
| 154 | + let mut x = 1u32; | |
| 155 | + for _ in 1..length { | |
| 156 | + x = (x << 1) | dec.literal(1); | |
| 157 | + } | |
| 158 | + Ok(x - 1) | |
| 159 | +} | |
| 160 | + | |
| 161 | +/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of | |
| 162 | +/// [`crate::tile`]'s `write_eob`. | |
| 163 | +fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables) -> usize { | |
| 164 | + const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513]; | |
| 165 | + const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
| 166 | + | |
| 167 | + let group = dec.symbol(coding.eob_pt) + 1; | |
| 168 | + let bits = OFFSET_BITS[group]; | |
| 169 | + let mut offset = 0u32; | |
| 170 | + if bits > 0 { | |
| 171 | + let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32; | |
| 172 | + offset = top << (bits - 1); | |
| 173 | + if bits > 1 { | |
| 174 | + offset |= dec.literal(bits - 1); | |
| 175 | + } | |
| 176 | + } | |
| 177 | + GROUP_START[group] + offset as usize | |
| 178 | +} | |
| 179 | + | |
| 180 | +/// One transform block's levels, the inverse of [`crate::tile`]'s | |
| 181 | +/// `write_coeffs`, returned as a `side * side` grid in raster order. | |
| 182 | +/// | |
| 183 | +/// # Errors | |
| 184 | +/// Returns an error if the transform codes a type other than `DCT_DCT` — this | |
| 185 | +/// decoder reads only the intra key-frame path the encoder still writes, | |
| 186 | +/// which never selects another type. | |
| 187 | +fn read_coeffs( | |
| 188 | + dec: &mut SymbolDecoder, | |
| 189 | + coding: &mut TxbTables, | |
| 190 | + scan: &[u16], | |
| 191 | + skip_ctx: usize, | |
| 192 | + sign_ctx: usize, | |
| 193 | +) -> Result<Vec<i32>> { | |
| 194 | + let side = coding.side; | |
| 195 | + let mut grid = vec![0i32; side * side]; | |
| 196 | + let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1; | |
| 197 | + if all_zero { | |
| 198 | + return Ok(grid); | |
| 199 | + } | |
| 200 | + if let Some(tx_type) = coding.tx_type.as_deref_mut() { | |
| 201 | + let t = dec.symbol(tx_type); | |
| 202 | + if t != 1 { | |
| 203 | + return Err(unsupported( | |
| 204 | + "a transform type other than DCT_DCT (round 2: inter/other intra tx sets)", | |
| 205 | + )); | |
| 206 | + } | |
| 207 | + } | |
| 208 | + | |
| 209 | + let eob = read_eob(dec, coding); | |
| 210 | + let mut levels = vec![0i32; side * side]; | |
| 211 | + for scan_idx in (0..eob).rev() { | |
| 212 | + let pos = scan[scan_idx] as usize; | |
| 213 | + let (row, col) = (pos / side, pos % side); | |
| 214 | + let level = if scan_idx == eob - 1 { | |
| 215 | + let ctx = eob_coeff_ctx(scan_idx, side * side); | |
| 216 | + dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1 | |
| 217 | + } else { | |
| 218 | + let ctx = base_ctx(&levels, side, row, col); | |
| 219 | + dec.symbol(&mut coding.base[ctx]) as i32 | |
| 220 | + }; | |
| 221 | + let level = if level > NUM_BASE_LEVELS { | |
| 222 | + let ctx = br_ctx(&levels, side, row, col); | |
| 223 | + let mut level = level; | |
| 224 | + let mut sent = 0; | |
| 225 | + loop { | |
| 226 | + let k = dec.symbol(&mut coding.br[ctx]) as i32; | |
| 227 | + level += k; | |
| 228 | + sent += BR_STEP; | |
| 229 | + if k < BR_STEP || sent >= COEFF_BASE_RANGE { | |
| 230 | + break; | |
| 231 | + } | |
| 232 | + } | |
| 233 | + level | |
| 234 | + } else { | |
| 235 | + level | |
| 236 | + }; | |
| 237 | + levels[pos] = level; | |
| 238 | + } | |
| 239 | + | |
| 240 | + for &pos in &scan[..eob] { | |
| 241 | + let level = levels[pos as usize]; | |
| 242 | + if level == 0 { | |
| 243 | + continue; | |
| 244 | + } | |
| 245 | + let negative = if pos == 0 { | |
| 246 | + dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1 | |
| 247 | + } else { | |
| 248 | + dec.literal(1) == 1 | |
| 249 | + }; | |
| 250 | + let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL { | |
| 251 | + level + read_golomb(dec)? as i32 | |
| 252 | + } else { | |
| 253 | + level | |
| 254 | + }; | |
| 255 | + grid[pos as usize] = if negative { -level } else { level }; | |
| 256 | + } | |
| 257 | + Ok(grid) | |
| 258 | +} | |
| 259 | + | |
| 260 | +/// The neighbour state a block's contexts are read from — the decode-side | |
| 261 | +/// twin of [`crate::tile`]'s private `Neighbours`, keeping only what a | |
| 262 | +/// `DC_PRED`-only decoder needs: per-16x16-cell block size (partition | |
| 263 | +/// context) and per-plane coded/DC-sign state (coefficient contexts). Mode | |
| 264 | +/// tracking is not needed: every block is `DC_PRED`, so the mode context is | |
| 265 | +/// always `[0][0]`. | |
| 266 | +struct Neighbours { | |
| 267 | + above_side: Vec<usize>, | |
| 268 | + left_side: Vec<usize>, | |
| 269 | + above: Vec<[(bool, Option<bool>); 3]>, | |
| 270 | + left: Vec<[(bool, Option<bool>); 3]>, | |
| 271 | +} | |
| 272 | + | |
| 273 | +impl Neighbours { | |
| 274 | + fn new(cols: usize, rows: usize) -> Self { | |
| 275 | + Self { | |
| 276 | + above_side: vec![SB; cols], | |
| 277 | + left_side: vec![SB; rows], | |
| 278 | + above: vec![[(false, None); 3]; cols], | |
| 279 | + left: vec![[(false, None); 3]; rows], | |
| 280 | + } | |
| 281 | + } | |
| 282 | + | |
| 283 | + fn start_row(&mut self) { | |
| 284 | + self.left_side.iter_mut().for_each(|s| *s = SB); | |
| 285 | + self.left.iter_mut().for_each(|l| *l = Default::default()); | |
| 286 | + } | |
| 287 | + | |
| 288 | + fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize { | |
| 289 | + let (r, c) = at; | |
| 290 | + 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side) | |
| 291 | + } | |
| 292 | + | |
| 293 | + /// Whether any transform block above/left of this one (spanning `side_sub` | |
| 294 | + /// `SUB`-sized cells) coded a coefficient, and the gathered DC-sign vote, | |
| 295 | + /// per plane. | |
| 296 | + fn around(&self, at: (usize, usize), side_sub: usize) -> [(bool, bool, i32); 3] { | |
| 297 | + let (r, c) = at; | |
| 298 | + std::array::from_fn(|plane| { | |
| 299 | + let mut above_coded = false; | |
| 300 | + let mut left_coded = false; | |
| 301 | + let mut vote = 0; | |
| 302 | + for cell in 0..side_sub { | |
| 303 | + let (a_coded, a_dc) = self.above[c + cell][plane]; | |
| 304 | + let (l_coded, l_dc) = self.left[r + cell][plane]; | |
| 305 | + above_coded |= a_coded; | |
| 306 | + left_coded |= l_coded; | |
| 307 | + vote += dc_vote(a_dc) + dc_vote(l_dc); | |
| 308 | + } | |
| 309 | + (above_coded, left_coded, vote) | |
| 310 | + }) | |
| 311 | + } | |
| 312 | + | |
| 313 | + fn record(&mut self, at: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) { | |
| 314 | + let (r, c) = at; | |
| 315 | + let states: [(bool, Option<bool>); 3] = std::array::from_fn(|plane| { | |
| 316 | + let grid = &grids[plane]; | |
| 317 | + ( | |
| 318 | + grid.iter().any(|&l| l != 0), | |
| 319 | + (grid[0] != 0).then_some(grid[0] < 0), | |
| 320 | + ) | |
| 321 | + }); | |
| 322 | + for cell in 0..side / SUB { | |
| 323 | + self.above_side[c + cell] = side; | |
| 324 | + self.left_side[r + cell] = side; | |
| 325 | + } | |
| 326 | + for cell in 0..side / SUB { | |
| 327 | + self.above[c + cell] = states; | |
| 328 | + self.left[r + cell] = states; | |
| 329 | + } | |
| 330 | + } | |
| 331 | +} | |
| 332 | + | |
| 333 | +/// Reads one coded block's mode and skip flag, refusing anything but | |
| 334 | +/// `DC_PRED`, unskipped — the only shape this round's decoder reconstructs. | |
| 335 | +fn read_intra_mode(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, cfl: bool) -> Result<()> { | |
| 336 | + if dec.symbol(&mut cdfs.skip[0]) != 0 { | |
| 337 | + return Err(unsupported("a skipped block (round 2)")); | |
| 338 | + } | |
| 339 | + let mode = dec.symbol(&mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]]); | |
| 340 | + if mode != DC_PRED { | |
| 341 | + return Err(unsupported(format!( | |
| 342 | + "intra mode {mode} (round 1 reconstructs DC_PRED only)" | |
| 343 | + ))); | |
| 344 | + } | |
| 345 | + let uv_mode = if cfl { | |
| 346 | + dec.symbol(&mut cdfs.uv_mode_cfl[mode]) | |
| 347 | + } else { | |
| 348 | + dec.symbol(&mut cdfs.uv_mode_no_cfl[mode]) | |
| 349 | + }; | |
| 350 | + if uv_mode != DC_PRED { | |
| 351 | + return Err(unsupported("a chroma-from-luma mode (round 2)")); | |
| 352 | + } | |
| 353 | + Ok(()) | |
| 354 | +} | |
| 355 | + | |
| 356 | +/// One plane's reconstruction buffer, `width * height` samples, and the | |
| 357 | +/// prediction/residual reads and writes into it. | |
| 358 | +struct PlaneBuf { | |
| 359 | + data: Vec<u8>, | |
| 360 | + width: usize, | |
| 361 | +} | |
| 362 | + | |
| 363 | +impl PlaneBuf { | |
| 364 | + fn edges( | |
| 365 | + &self, | |
| 366 | + x: usize, | |
| 367 | + y: usize, | |
| 368 | + side: usize, | |
| 369 | + ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) { | |
| 370 | + let above = (y > 0).then(|| self.data[(y - 1) * self.width + x..][..side].to_vec()); | |
| 371 | + let left = (x > 0).then(|| { | |
| 372 | + (y..y + side) | |
| 373 | + .map(|row| self.data[row * self.width + x - 1]) | |
| 374 | + .collect() | |
| 375 | + }); | |
| 376 | + let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]); | |
| 377 | + (above, left, corner) | |
| 378 | + } | |
| 379 | + | |
| 380 | + /// Predicts (`DC_PRED` only) then adds `residual` (side*side, raster), | |
| 381 | + /// writing the clamped reconstruction back into the plane at `(x, y)`. | |
| 382 | + fn reconstruct(&mut self, x: usize, y: usize, side: usize, residual: &[i32]) { | |
| 383 | + let (above, left, _corner) = self.edges(x, y, side); | |
| 384 | + let dc = match (&above, &left) { | |
| 385 | + (None, None) => 128, | |
| 386 | + (Some(a), None) => { | |
| 387 | + let sum: u32 = a.iter().map(|&s| u32::from(s)).sum(); | |
| 388 | + ((sum + (a.len() as u32 >> 1)) / a.len() as u32) as i32 | |
| 389 | + } | |
| 390 | + (None, Some(l)) => { | |
| 391 | + let sum: u32 = l.iter().map(|&s| u32::from(s)).sum(); | |
| 392 | + ((sum + (l.len() as u32 >> 1)) / l.len() as u32) as i32 | |
| 393 | + } | |
| 394 | + (Some(a), Some(l)) => { | |
| 395 | + let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum(); | |
| 396 | + let count = (a.len() + l.len()) as u32; | |
| 397 | + ((sum + (count >> 1)) / count) as i32 | |
| 398 | + } | |
| 399 | + }; | |
| 400 | + for row in 0..side { | |
| 401 | + for col in 0..side { | |
| 402 | + let sample = (dc + residual[row * side + col]).clamp(0, 255) as u8; | |
| 403 | + self.data[(y + row) * self.width + x + col] = sample; | |
| 404 | + } | |
| 405 | + } | |
| 406 | + } | |
| 407 | +} | |
| 408 | + | |
| 409 | +/// Reads one plane's transform block, reconstructs it into `plane` at | |
| 410 | +/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`. | |
| 411 | +#[allow(clippy::too_many_arguments)] | |
| 412 | +fn read_plane( | |
| 413 | + dec: &mut SymbolDecoder, | |
| 414 | + cdfs: &mut Cdfs, | |
| 415 | + set: TxbSet, | |
| 416 | + scan: &[u16], | |
| 417 | + plane_idx: usize, | |
| 418 | + around: (bool, bool, i32), | |
| 419 | + plane: &mut PlaneBuf, | |
| 420 | + x: usize, | |
| 421 | + y: usize, | |
| 422 | + side: usize, | |
| 423 | + tx_side: usize, | |
| 424 | + base_q_idx: u8, | |
| 425 | +) -> Result<Vec<i32>> { | |
| 426 | + let skip_ctx = if plane_idx == 0 { | |
| 427 | + 0 | |
| 428 | + } else { | |
| 429 | + usize::from(around.0) + usize::from(around.1) | |
| 430 | + }; | |
| 431 | + let mut coding = cdfs.txb(set, DC_PRED); | |
| 432 | + let grid = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?; | |
| 433 | + // A 64x64 luma block's transform covers the whole 64x64 area, but only its | |
| 434 | + // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the | |
| 435 | + // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32` | |
| 436 | + // guard also assumes. | |
| 437 | + let levels = if tx_side == side { | |
| 438 | + grid | |
| 439 | + } else { | |
| 440 | + let mut full = vec![0i32; tx_side * tx_side]; | |
| 441 | + for row in 0..side { | |
| 442 | + full[row * tx_side..][..side].copy_from_slice(&grid[row * side..][..side]); | |
| 443 | + } | |
| 444 | + full | |
| 445 | + }; | |
| 446 | + let residual = dequant_and_inverse(&levels, tx_side, 8, i32::from(base_q_idx)); | |
| 447 | + plane.reconstruct(x, y, tx_side, &residual); | |
| 448 | + Ok(if tx_side == side { | |
| 449 | + residual_grid_placeholder(&levels, tx_side) | |
| 450 | + } else { | |
| 451 | + levels | |
| 452 | + }) | |
| 453 | +} | |
| 454 | + | |
| 455 | +/// `record`'s neighbour state only reads whether *the coded grid* (not the | |
| 456 | +/// residual) has nonzero entries, so the levels this function already built | |
| 457 | +/// are what it wants back; this helper exists only to name that clearly at | |
| 458 | +/// the one call site where `tx_side == side`. | |
| 459 | +fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> { | |
| 460 | + levels.to_vec() | |
| 461 | +} | |
| 462 | + | |
| 463 | +/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its | |
| 464 | +/// three planes, reconstructing them into `y`/`u`/`v` and updating | |
| 465 | +/// `neighbours`. | |
| 466 | +#[allow(clippy::too_many_arguments)] | |
| 467 | +fn decode_block( | |
| 468 | + dec: &mut SymbolDecoder, | |
| 469 | + cdfs: &mut Cdfs, | |
| 470 | + neighbours: &mut Neighbours, | |
| 471 | + at: (usize, usize), | |
| 472 | + side: usize, | |
| 473 | + luma_set: TxbSet, | |
| 474 | + chroma_set: TxbSet, | |
| 475 | + luma_tx: usize, | |
| 476 | + chroma_tx: usize, | |
| 477 | + scans: (&[u16], &[u16]), | |
| 478 | + cfl: bool, | |
| 479 | + y: &mut PlaneBuf, | |
| 480 | + u: &mut PlaneBuf, | |
| 481 | + v: &mut PlaneBuf, | |
| 482 | + base_q_idx: u8, | |
| 483 | +) -> Result<()> { | |
| 484 | + read_intra_mode(dec, cdfs, cfl)?; | |
| 485 | + let (r, c) = at; | |
| 486 | + let around = neighbours.around(at, side / SUB); | |
| 487 | + let (px, py) = (c * SUB, r * SUB); | |
| 488 | + let luma_grid = read_plane( | |
| 489 | + dec, cdfs, luma_set, scans.0, 0, around[0], y, px, py, side, luma_tx, base_q_idx, | |
| 490 | + )?; | |
| 491 | + let (cpx, cpy) = (px / 2, py / 2); | |
| 492 | + let chroma_side = side / 2; | |
| 493 | + let u_grid = read_plane( | |
| 494 | + dec, | |
| 495 | + cdfs, | |
| 496 | + chroma_set, | |
| 497 | + scans.1, | |
| 498 | + 1, | |
| 499 | + around[1], | |
| 500 | + u, | |
| 501 | + cpx, | |
| 502 | + cpy, | |
| 503 | + chroma_side, | |
| 504 | + chroma_tx, | |
| 505 | + base_q_idx, | |
| 506 | + )?; | |
| 507 | + let v_grid = read_plane( | |
| 508 | + dec, | |
| 509 | + cdfs, | |
| 510 | + chroma_set, | |
| 511 | + scans.1, | |
| 512 | + 2, | |
| 513 | + around[2], | |
| 514 | + v, | |
| 515 | + cpx, | |
| 516 | + cpy, | |
| 517 | + chroma_side, | |
| 518 | + chroma_tx, | |
| 519 | + base_q_idx, | |
| 520 | + )?; | |
| 521 | + neighbours.record(at, side, &[luma_grid, u_grid, v_grid]); | |
| 522 | + Ok(()) | |
| 523 | +} | |
| 524 | + | |
| 525 | +/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes, | |
| 526 | +/// returning the picture it reconstructs to. | |
| 527 | +/// | |
| 528 | +/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by | |
| 529 | +/// [`ec_av1_syntax`]. | |
| 530 | +/// | |
| 531 | +/// # Errors | |
| 532 | +/// Returns an error when the frame is not a whole number of 64x64 | |
| 533 | +/// superblocks (round 2: the partial-superblock/gathered-CDF path), when a | |
| 534 | +/// block's partition, mode, skip flag or transform type is anything this | |
| 535 | +/// decoder does not reconstruct (round 2: non-`DC_PRED` intra, inter, tx | |
| 536 | +/// types other than `DCT_DCT`), or when the tile payload runs out of the | |
| 537 | +/// symbols this decode expects (a genuinely foreign stream). | |
| 538 | +pub fn decode_key_frame_tile( | |
| 539 | + data: &[u8], | |
| 540 | + mi_cols: u32, | |
| 541 | + mi_rows: u32, | |
| 542 | + base_q_idx: u8, | |
| 543 | +) -> Result<Picture> { | |
| 544 | + if mi_cols == 0 | |
| 545 | + || mi_rows == 0 | |
| 546 | + || !mi_cols.is_multiple_of(SB_MI) | |
| 547 | + || !mi_rows.is_multiple_of(SB_MI) | |
| 548 | + { | |
| 549 | + return Err(unsupported( | |
| 550 | + "a frame that is not a whole number of 64x64 superblocks (round 2)", | |
| 551 | + )); | |
| 552 | + } | |
| 553 | + let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); | |
| 554 | + let (cols32, rows32) = block_grid(mi_cols, mi_rows); | |
| 555 | + let width = (mi_cols * 4) as usize; | |
| 556 | + let height = (mi_rows * 4) as usize; | |
| 557 | + | |
| 558 | + let mut y = PlaneBuf { | |
| 559 | + data: vec![0u8; width * height], | |
| 560 | + width, | |
| 561 | + }; | |
| 562 | + let mut u = PlaneBuf { | |
| 563 | + data: vec![0u8; width * height / 4], | |
| 564 | + width: width / 2, | |
| 565 | + }; | |
| 566 | + let mut v = PlaneBuf { | |
| 567 | + data: vec![0u8; width * height / 4], | |
| 568 | + width: width / 2, | |
| 569 | + }; | |
| 570 | + | |
| 571 | + let scan32 = default_scan(TX32); | |
| 572 | + let scan16 = default_scan(TX16); | |
| 573 | + let scan8 = default_scan(TX8); | |
| 574 | + | |
| 575 | + let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); | |
| 576 | + let mut dec = SymbolDecoder::new(data); | |
| 577 | + let mut neighbours = Neighbours::new(cols32 as usize * 2, rows32 as usize * 2); | |
| 578 | + | |
| 579 | + for sb_r in 0..sb_rows { | |
| 580 | + neighbours.start_row(); | |
| 581 | + for sb_c in 0..sb_cols { | |
| 582 | + let at = (sb_r as usize * 4, sb_c as usize * 4); | |
| 583 | + let ctx = neighbours.partition_ctx(at, SB); | |
| 584 | + let (has_cols, has_rows) = ( | |
| 585 | + sb_c * SB_MI + SB_MI / 2 < mi_cols, | |
| 586 | + sb_r * SB_MI + SB_MI / 2 < mi_rows, | |
| 587 | + ); | |
| 588 | + if !has_cols || !has_rows { | |
| 589 | + return Err(unsupported( | |
| 590 | + "a superblock half outside the true frame (round 2)", | |
| 591 | + )); | |
| 592 | + } | |
| 593 | + let part = dec.symbol(&mut cdfs.partition_w64[ctx]); | |
| 594 | + match part { | |
| 595 | + PARTITION_NONE => { | |
| 596 | + decode_block( | |
| 597 | + &mut dec, | |
| 598 | + &mut cdfs, | |
| 599 | + &mut neighbours, | |
| 600 | + at, | |
| 601 | + SB, | |
| 602 | + TxbSet::Luma64, | |
| 603 | + TxbSet::Chroma32, | |
| 604 | + TX32, | |
| 605 | + TX32, | |
| 606 | + (&scan32, &scan32), | |
| 607 | + false, | |
| 608 | + &mut y, | |
| 609 | + &mut u, | |
| 610 | + &mut v, | |
| 611 | + base_q_idx, | |
| 612 | + )?; | |
| 613 | + } | |
| 614 | + PARTITION_SPLIT => { | |
| 615 | + for q in 0..4 { | |
| 616 | + let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); | |
| 617 | + if r32 >= rows32 || c32 >= cols32 { | |
| 618 | + continue; | |
| 619 | + } | |
| 620 | + let at32 = (r32 as usize * 2, c32 as usize * 2); | |
| 621 | + let ctx32 = neighbours.partition_ctx(at32, BLOCK); | |
| 622 | + let (has_cols32, has_rows32) = ( | |
| 623 | + has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols), | |
| 624 | + has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows), | |
| 625 | + ); | |
| 626 | + if !has_cols32 || !has_rows32 { | |
| 627 | + return Err(unsupported( | |
| 628 | + "a 32x32 block half outside the true frame (round 2)", | |
| 629 | + )); | |
| 630 | + } | |
| 631 | + let part32 = dec.symbol(&mut cdfs.partition_w32[ctx32]); | |
| 632 | + match part32 { | |
| 633 | + PARTITION_NONE => { | |
| 634 | + decode_block( | |
| 635 | + &mut dec, | |
| 636 | + &mut cdfs, | |
| 637 | + &mut neighbours, | |
| 638 | + at32, | |
| 639 | + BLOCK, | |
| 640 | + TxbSet::Luma32, | |
| 641 | + TxbSet::Chroma16, | |
| 642 | + TX32, | |
| 643 | + TX16, | |
| 644 | + (&scan32, &scan16), | |
| 645 | + true, | |
| 646 | + &mut y, | |
| 647 | + &mut u, | |
| 648 | + &mut v, | |
| 649 | + base_q_idx, | |
| 650 | + )?; | |
| 651 | + } | |
| 652 | + PARTITION_SPLIT => { | |
| 653 | + for sub in 0..4 { | |
| 654 | + let (sr, sc) = | |
| 655 | + (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2); | |
| 656 | + if (sr as u32) * SUB_MI >= mi_rows | |
| 657 | + || (sc as u32) * SUB_MI >= mi_cols | |
| 658 | + { | |
| 659 | + continue; | |
| 660 | + } | |
| 661 | + let (has_cols16, has_rows16) = ( | |
| 662 | + has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), | |
| 663 | + has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), | |
| 664 | + ); | |
| 665 | + if !has_cols16 || !has_rows16 { | |
| 666 | + return Err(unsupported( | |
| 667 | + "a 16x16 block the true frame edge cuts through (round 2)", | |
| 668 | + )); | |
| 669 | + } | |
| 670 | + let at16 = (sr, sc); | |
| 671 | + let ctx16 = neighbours.partition_ctx(at16, SUB); | |
| 672 | + let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); | |
| 673 | + if part16 != PARTITION_NONE { | |
| 674 | + return Err(unsupported( | |
| 675 | + "a partition below 16x16 (this encoder never writes one)", | |
| 676 | + )); | |
| 677 | + } | |
| 678 | + decode_block( | |
| 679 | + &mut dec, | |
| 680 | + &mut cdfs, | |
| 681 | + &mut neighbours, | |
| 682 | + at16, | |
| 683 | + SUB, | |
| 684 | + TxbSet::Luma16, | |
| 685 | + TxbSet::Chroma8, | |
| 686 | + TX16, | |
| 687 | + TX8, | |
| 688 | + (&scan16, &scan8), | |
| 689 | + true, | |
| 690 | + &mut y, | |
| 691 | + &mut u, | |
| 692 | + &mut v, | |
| 693 | + base_q_idx, | |
| 694 | + )?; | |
| 695 | + } | |
| 696 | + } | |
| 697 | + _ => { | |
| 698 | + return Err(unsupported( | |
| 699 | + "a partition type this encoder never writes", | |
| 700 | + )); | |
| 701 | + } | |
| 702 | + } | |
| 703 | + } | |
| 704 | + } | |
| 705 | + _ => { | |
| 706 | + return Err(unsupported("a partition type this encoder never writes")); | |
| 707 | + } | |
| 708 | + } | |
| 709 | + } | |
| 710 | + } | |
| 711 | + | |
| 712 | + Ok(Picture { | |
| 713 | + width, | |
| 714 | + height, | |
| 715 | + y: y.data, | |
| 716 | + u: u.data, | |
| 717 | + v: v.data, | |
| 718 | + }) | |
| 719 | +} | |
| 720 | + | |
| 721 | +#[cfg(test)] | |
| 722 | +mod tests { | |
| 723 | + use super::*; | |
| 724 | + | |
| 725 | + // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/ | |
| 726 | + // `split_dc_key_frame_tile` are not exercised here: they are synthetic | |
| 727 | + // single-purpose writers with their own skip-context rule (keyed to | |
| 728 | + // superblock position, not the neighbour-tracked one every real block | |
| 729 | + // uses), never reached by `encode_key_frame_with_modes` — decoding them | |
| 730 | + // would need a second, throwaway context convention next to the real | |
| 731 | + // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is | |
| 732 | + // this decoder's one target, and the round-trip test below is against | |
| 733 | + // that path with real quantised residual, not a synthetic all-DC frame. | |
| 734 | + | |
| 735 | + #[test] | |
| 736 | + fn a_frame_that_is_not_a_whole_number_of_superblocks_is_refused() { | |
| 737 | + assert!(decode_key_frame_tile(&[0u8; 4], 33, 32, 32).is_err()); | |
| 738 | + } | |
| 739 | + | |
| 740 | + #[test] | |
| 741 | + fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() { | |
| 742 | + use crate::encode::{Encoded, Picture as Pic}; | |
| 743 | + for (w, h) in [(128usize, 128usize), (192, 128)] { | |
| 744 | + let mut source = vec![0u8; w * h]; | |
| 745 | + for row in 0..h { | |
| 746 | + for col in 0..w { | |
| 747 | + source[row * w + col] = ((row * 3 + col * 5) % 251) as u8; | |
| 748 | + } | |
| 749 | + } | |
| 750 | + let picture = Pic { | |
| 751 | + width: w, | |
| 752 | + height: h, | |
| 753 | + y: source, | |
| 754 | + u: vec![128; w * h / 4], | |
| 755 | + v: vec![128; w * h / 4], | |
| 756 | + }; | |
| 757 | + let Encoded { | |
| 758 | + tile, | |
| 759 | + reconstruction, | |
| 760 | + mi_cols, | |
| 761 | + mi_rows, | |
| 762 | + base_q_idx, | |
| 763 | + .. | |
| 764 | + }: Encoded = | |
| 765 | + crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, &[DC_PRED as u8]) | |
| 766 | + .unwrap(); | |
| 767 | + let decoded = decode_key_frame_tile(&tile, mi_cols, mi_rows, base_q_idx).unwrap(); | |
| 768 | + assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch"); | |
| 769 | + assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch"); | |
| 770 | + assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch"); | |
| 771 | + } | |
| 772 | + } | |
| 773 | +} |
crates/ec-av1/src/encode.rsmodified+20 -0
| @@ -259,6 +259,10 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En | ||
| 259 | 259 | modes: encoded.modes.clone(), |
| 260 | 260 | inter_block_share: encoded.inter_block_share, |
| 261 | 261 | reconstruction: cropped, |
| 262 | + tile: encoded.tile.clone(), | |
| 263 | + mi_cols: encoded.mi_cols, | |
| 264 | + mi_rows: encoded.mi_rows, | |
| 265 | + base_q_idx: encoded.base_q_idx, | |
| 262 | 266 | } |
| 263 | 267 | } |
| 264 | 268 | |
| @@ -280,6 +284,14 @@ pub struct Encoded { | ||
| 280 | 284 | /// for a key frame, which has no such choice — so a caller can tell a |
| 281 | 285 | /// frame with no motion worth coding from one that never got the chance. |
| 282 | 286 | pub inter_block_share: f64, |
| 287 | + /// The tile payload alone, undecorated by any OBU framing, and the frame | |
| 288 | + /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`. | |
| 289 | + /// `crate::decode`'s tests are the only reader; a real decoder gets these | |
| 290 | + /// off the wire by parsing `stream`'s OBUs instead. | |
| 291 | + pub(crate) tile: Vec<u8>, | |
| 292 | + pub(crate) mi_cols: u32, | |
| 293 | + pub(crate) mi_rows: u32, | |
| 294 | + pub(crate) base_q_idx: u8, | |
| 283 | 295 | } |
| 284 | 296 | |
| 285 | 297 | /// The sequence and frame headers a picture of this size is coded under: one |
| @@ -1754,6 +1766,10 @@ pub(crate) fn encode_key_frame_inner( | ||
| 1754 | 1766 | u: u.reconstruction, |
| 1755 | 1767 | v: v.reconstruction, |
| 1756 | 1768 | }, |
| 1769 | + tile, | |
| 1770 | + mi_cols: header.mi_cols, | |
| 1771 | + mi_rows: header.mi_rows, | |
| 1772 | + base_q_idx, | |
| 1757 | 1773 | }) |
| 1758 | 1774 | } |
| 1759 | 1775 | |
| @@ -2586,6 +2602,10 @@ pub(crate) fn encode_inter_frame( | ||
| 2586 | 2602 | u: u.reconstruction, |
| 2587 | 2603 | v: v.reconstruction, |
| 2588 | 2604 | }, |
| 2605 | + tile, | |
| 2606 | + mi_cols: header.mi_cols, | |
| 2607 | + mi_rows: header.mi_rows, | |
| 2608 | + base_q_idx, | |
| 2589 | 2609 | }) |
| 2590 | 2610 | } |
| 2591 | 2611 |
crates/ec-av1/src/lib.rsmodified+1 -0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | pub mod bits; |
| 16 | 16 | pub mod cdf; |
| 17 | 17 | mod cdf_state; |
| 18 | +pub mod decode; | |
| 18 | 19 | pub mod encode; |
| 19 | 20 | pub mod encoder; |
| 20 | 21 | pub mod frame; |
crates/ec-av1/src/msac.rsmodified+93 -79
| @@ -235,96 +235,110 @@ fn update_cdf(cdf: &mut [u16], symbol: usize) { | ||
| 235 | 235 | cdf[nsyms] = count + 1 - (count >> 5); |
| 236 | 236 | } |
| 237 | 237 | |
| 238 | -#[cfg(test)] | |
| 239 | -pub(crate) mod tests { | |
| 240 | - use super::*; | |
| 238 | +/// The decoding process of spec 8.2, the exact inverse of [`SymbolEncoder`]: | |
| 239 | +/// reads the symbols a [`SymbolEncoder`] wrote, in the order it wrote them, | |
| 240 | +/// adapting every CDF identically (spec 8.3.2) so the two stay in step. This | |
| 241 | +/// is the reader half of the arithmetic coder a real AV1 decoder's tile | |
| 242 | +/// reader is built on top of. | |
| 243 | +#[derive(Debug)] | |
| 244 | +pub struct SymbolDecoder<'a> { | |
| 245 | + data: &'a [u8], | |
| 246 | + /// Next bit to read, as a bit offset into `data`. | |
| 247 | + bit: usize, | |
| 248 | + value: u32, | |
| 249 | + range: u32, | |
| 250 | + /// Bits left before the decoder starts padding with zeros (spec | |
| 251 | + /// `SymbolMaxBits`), which goes negative at the end of the string. | |
| 252 | + max_bits: i32, | |
| 253 | +} | |
| 241 | 254 | |
| 242 | - /// The decoding process of spec 8.2, written from the specification's | |
| 243 | - /// pseudocode so that the roundtrip tests measure the encoder against the | |
| 244 | - /// decoder AV1 defines rather than against the encoder's own arithmetic. | |
| 245 | - pub(crate) struct SymbolDecoder<'a> { | |
| 246 | - data: &'a [u8], | |
| 247 | - /// Next bit to read, as a bit offset into `data`. | |
| 248 | - bit: usize, | |
| 249 | - value: u32, | |
| 250 | - range: u32, | |
| 251 | - /// Bits left before the decoder starts padding with zeros (spec | |
| 252 | - /// `SymbolMaxBits`), which goes negative at the end of the string. | |
| 253 | - max_bits: i32, | |
| 255 | +impl<'a> SymbolDecoder<'a> { | |
| 256 | + /// `init_symbol` (spec 8.2.2). | |
| 257 | + #[must_use] | |
| 258 | + pub fn new(data: &'a [u8]) -> SymbolDecoder<'a> { | |
| 259 | + let mut d = SymbolDecoder { | |
| 260 | + data, | |
| 261 | + bit: 0, | |
| 262 | + value: 0, | |
| 263 | + range: 1 << 15, | |
| 264 | + max_bits: 8 * data.len() as i32 - 15, | |
| 265 | + }; | |
| 266 | + let num_bits = usize::min(data.len() * 8, 15) as u32; | |
| 267 | + let buf = d.f(num_bits); | |
| 268 | + d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits)); | |
| 269 | + d | |
| 254 | 270 | } |
| 255 | 271 | |
| 256 | - impl<'a> SymbolDecoder<'a> { | |
| 257 | - /// `init_symbol` (spec 8.2.2). | |
| 258 | - pub(crate) fn new(data: &'a [u8]) -> SymbolDecoder<'a> { | |
| 259 | - let mut d = SymbolDecoder { | |
| 260 | - data, | |
| 261 | - bit: 0, | |
| 262 | - value: 0, | |
| 263 | - range: 1 << 15, | |
| 264 | - max_bits: 8 * data.len() as i32 - 15, | |
| 265 | - }; | |
| 266 | - let num_bits = usize::min(data.len() * 8, 15) as u32; | |
| 267 | - let buf = d.f(num_bits); | |
| 268 | - d.value = ((1 << 15) - 1) ^ (buf << (15 - num_bits)); | |
| 269 | - d | |
| 270 | - } | |
| 271 | - | |
| 272 | - /// `f(n)`: the next `n` bits, most significant first, zero past the end. | |
| 273 | - fn f(&mut self, n: u32) -> u32 { | |
| 274 | - let mut v = 0; | |
| 275 | - for _ in 0..n { | |
| 276 | - let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0); | |
| 277 | - v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1); | |
| 278 | - self.bit += 1; | |
| 279 | - } | |
| 280 | - v | |
| 272 | + /// `f(n)`: the next `n` bits, most significant first, zero past the end. | |
| 273 | + fn f(&mut self, n: u32) -> u32 { | |
| 274 | + let mut v = 0; | |
| 275 | + for _ in 0..n { | |
| 276 | + let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0); | |
| 277 | + v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1); | |
| 278 | + self.bit += 1; | |
| 281 | 279 | } |
| 280 | + v | |
| 281 | + } | |
| 282 | 282 | |
| 283 | - /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. | |
| 284 | - pub(crate) fn symbol(&mut self, cdf: &mut [u16]) -> usize { | |
| 285 | - let s = self.symbol_fixed(cdf); | |
| 286 | - update_cdf(cdf, s); | |
| 287 | - s | |
| 288 | - } | |
| 283 | + /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2. | |
| 284 | + pub fn symbol(&mut self, cdf: &mut [u16]) -> usize { | |
| 285 | + let s = self.symbol_fixed(cdf); | |
| 286 | + update_cdf(cdf, s); | |
| 287 | + s | |
| 288 | + } | |
| 289 | 289 | |
| 290 | - fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { | |
| 291 | - let nsyms = cdf.len() - 1; | |
| 292 | - let mut cur = self.range; | |
| 293 | - let mut prev; | |
| 294 | - let mut symbol = 0; | |
| 295 | - loop { | |
| 296 | - prev = cur; | |
| 297 | - let f = u32::from(CDF_TOP - cdf[symbol]); | |
| 298 | - cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) | |
| 299 | - + EC_MIN_PROB * (nsyms - 1 - symbol) as u32; | |
| 300 | - if self.value >= cur { | |
| 301 | - break; | |
| 302 | - } | |
| 303 | - symbol += 1; | |
| 290 | + /// `decode_symbol`, without the adaptation of 8.3.2 — the form the spec | |
| 291 | + /// uses for the literal and equiprobable reads, mirroring | |
| 292 | + /// [`SymbolEncoder::symbol_fixed`]. | |
| 293 | + pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize { | |
| 294 | + let nsyms = cdf.len() - 1; | |
| 295 | + let mut cur = self.range; | |
| 296 | + let mut prev; | |
| 297 | + let mut symbol = 0; | |
| 298 | + loop { | |
| 299 | + prev = cur; | |
| 300 | + let f = u32::from(CDF_TOP - cdf[symbol]); | |
| 301 | + cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT)) | |
| 302 | + + EC_MIN_PROB * (nsyms - 1 - symbol) as u32; | |
| 303 | + if self.value >= cur { | |
| 304 | + break; | |
| 304 | 305 | } |
| 305 | - self.range = prev - cur; | |
| 306 | - self.value -= cur; | |
| 307 | - | |
| 308 | - // Renormalise back into `[2^15, 2^16)`, the same shift the encoder | |
| 309 | - // applied when it narrowed to this symbol. | |
| 310 | - let bits = 16 - (32 - self.range.leading_zeros()); | |
| 311 | - self.range <<= bits; | |
| 312 | - let num_bits = u32::min(bits, self.max_bits.max(0) as u32); | |
| 313 | - let new_data = self.f(num_bits); | |
| 314 | - let padded = new_data << (bits - num_bits); | |
| 315 | - self.value = padded ^ (((self.value + 1) << bits) - 1); | |
| 316 | - self.max_bits -= bits as i32; | |
| 317 | - symbol | |
| 306 | + symbol += 1; | |
| 318 | 307 | } |
| 308 | + self.range = prev - cur; | |
| 309 | + self.value -= cur; | |
| 310 | + | |
| 311 | + // Renormalise back into `[2^15, 2^16)`, the same shift the encoder | |
| 312 | + // applied when it narrowed to this symbol. | |
| 313 | + let bits = 16 - (32 - self.range.leading_zeros()); | |
| 314 | + self.range <<= bits; | |
| 315 | + let num_bits = u32::min(bits, self.max_bits.max(0) as u32); | |
| 316 | + let new_data = self.f(num_bits); | |
| 317 | + let padded = new_data << (bits - num_bits); | |
| 318 | + self.value = padded ^ (((self.value + 1) << bits) - 1); | |
| 319 | + self.max_bits -= bits as i32; | |
| 320 | + symbol | |
| 321 | + } | |
| 319 | 322 | |
| 320 | - pub(crate) fn literal(&mut self, bits: u32) -> u32 { | |
| 321 | - let mut v = 0; | |
| 322 | - for _ in 0..bits { | |
| 323 | - v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32; | |
| 324 | - } | |
| 325 | - v | |
| 323 | + /// Reads `bits` raw bits, most significant first — the `L(n)` descriptor | |
| 324 | + /// of spec 4.10.4. | |
| 325 | + pub fn literal(&mut self, bits: u32) -> u32 { | |
| 326 | + let mut v = 0; | |
| 327 | + for _ in 0..bits { | |
| 328 | + v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32; | |
| 326 | 329 | } |
| 330 | + v | |
| 327 | 331 | } |
| 332 | +} | |
| 333 | + | |
| 334 | +#[cfg(test)] | |
| 335 | +pub(crate) mod tests { | |
| 336 | + use super::*; | |
| 337 | + | |
| 338 | + // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now | |
| 339 | + // lives in the outer module (non-test code decodes with it too), so this | |
| 340 | + // re-export is what keeps those call sites resolving unmodified. | |
| 341 | + pub(crate) use super::SymbolDecoder; | |
| 328 | 342 | |
| 329 | 343 | /// A reproducible symbol stream: xorshift, so a failure names one seed. |
| 330 | 344 | fn rng(state: &mut u64) -> u64 { |