| 1 | |
| 2 | |
| 3 | |
| 4 | use crate::huffman_tables::*; |
| 5 | use ec_core::bitio::BitReader; |
| 6 | use ec_core::error::{Error, Result}; |
| 7 | use std::sync::OnceLock; |
| 8 | |
| 9 | |
| 10 | #[derive(Clone, Copy, Debug)] |
| 11 | pub(crate) struct Table { |
| 12 | |
| 13 | pub codes: &'static [(u8, u16)], |
| 14 | |
| 15 | |
| 16 | pub dim: u16, |
| 17 | |
| 18 | pub linbits: u8, |
| 19 | } |
| 20 | |
| 21 | |
| 22 | |
| 23 | pub(crate) fn big_table(select: usize) -> Result<Table> { |
| 24 | let t = |codes: &'static [(u8, u16)], dim: u16, linbits: u8| Table { |
| 25 | codes, |
| 26 | dim, |
| 27 | linbits, |
| 28 | }; |
| 29 | Ok(match select { |
| 30 | 0 => t(&[], 0, 0), |
| 31 | 1 => t(&T1, 2, 0), |
| 32 | 2 => t(&T2, 3, 0), |
| 33 | 3 => t(&T3, 3, 0), |
| 34 | 5 => t(&T5, 4, 0), |
| 35 | 6 => t(&T6, 4, 0), |
| 36 | 7 => t(&T7, 6, 0), |
| 37 | 8 => t(&T8, 6, 0), |
| 38 | 9 => t(&T9, 6, 0), |
| 39 | 10 => t(&T10, 8, 0), |
| 40 | 11 => t(&T11, 8, 0), |
| 41 | 12 => t(&T12, 8, 0), |
| 42 | 13 => t(&T13, 16, 0), |
| 43 | 15 => t(&T15, 16, 0), |
| 44 | 16..=23 => t(&T16, 16, LINBITS_16[select - 16]), |
| 45 | 24..=31 => t(&T24, 16, LINBITS_24[select - 24]), |
| 46 | _ => { |
| 47 | return Err(Error::corrupt(format!( |
| 48 | "mp3: Huffman table {select} is not assigned" |
| 49 | ))); |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | const LINBITS_16: [u8; 8] = [1, 2, 3, 4, 6, 8, 10, 13]; |
| 55 | const LINBITS_24: [u8; 8] = [4, 5, 6, 7, 8, 9, 11, 13]; |
| 56 | |
| 57 | |
| 58 | pub(crate) fn count1_table(select: bool) -> &'static [(u8, u16)] { |
| 59 | if select { &C1 } else { &C0 } |
| 60 | } |
| 61 | |
| 62 | |
| 63 | |
| 64 | type Tree = Vec<[i32; 2]>; |
| 65 | |
| 66 | fn build_tree(codes: &[(u8, u16)]) -> Tree { |
| 67 | let mut tree: Tree = vec![[0, 0]]; |
| 68 | for (index, &(len, code)) in codes.iter().enumerate() { |
| 69 | let mut node = 0usize; |
| 70 | let code = u32::from(code); |
| 71 | for bit in (0..u32::from(len)).rev() { |
| 72 | let branch = ((code >> bit) & 1) as usize; |
| 73 | if bit == 0 { |
| 74 | tree[node][branch] = -(index as i32 + 1); |
| 75 | } else { |
| 76 | if tree[node][branch] == 0 { |
| 77 | tree.push([0, 0]); |
| 78 | tree[node][branch] = (tree.len() - 1) as i32; |
| 79 | } |
| 80 | node = tree[node][branch] as usize; |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | tree |
| 85 | } |
| 86 | |
| 87 | struct Trees { |
| 88 | big: Vec<Option<Tree>>, |
| 89 | count1: [Tree; 2], |
| 90 | } |
| 91 | |
| 92 | fn trees() -> &'static Trees { |
| 93 | static TREES: OnceLock<Trees> = OnceLock::new(); |
| 94 | TREES.get_or_init(|| { |
| 95 | let mut big = Vec::with_capacity(32); |
| 96 | for select in 0..32 { |
| 97 | big.push(match big_table(select) { |
| 98 | Ok(t) if !t.codes.is_empty() => Some(build_tree(t.codes)), |
| 99 | _ => None, |
| 100 | }); |
| 101 | } |
| 102 | Trees { |
| 103 | big, |
| 104 | count1: [build_tree(&C0), build_tree(&C1)], |
| 105 | } |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | fn walk(tree: &Tree, reader: &mut BitReader<'_>) -> Result<usize> { |
| 110 | let mut node = 0usize; |
| 111 | loop { |
| 112 | let branch = usize::from(reader.read_bit()?); |
| 113 | let next = tree[node][branch]; |
| 114 | if next < 0 { |
| 115 | return Ok((-next - 1) as usize); |
| 116 | } |
| 117 | if next == 0 { |
| 118 | return Err(Error::corrupt("mp3: Huffman code not in table")); |
| 119 | } |
| 120 | node = next as usize; |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | |
| 125 | pub(crate) fn decode_pair( |
| 126 | reader: &mut BitReader<'_>, |
| 127 | select: usize, |
| 128 | table: Table, |
| 129 | out: &mut [f32; 2], |
| 130 | ) -> Result<()> { |
| 131 | let tree = trees().big[select] |
| 132 | .as_ref() |
| 133 | .ok_or_else(|| Error::corrupt(format!("mp3: Huffman table {select} is not assigned")))?; |
| 134 | let index = walk(tree, reader)?; |
| 135 | let values = [ |
| 136 | (index as u16 / table.dim) as u32, |
| 137 | (index as u16 % table.dim) as u32, |
| 138 | ]; |
| 139 | |
| 140 | |
| 141 | |
| 142 | for (slot, mut value) in out.iter_mut().zip(values) { |
| 143 | if table.linbits > 0 && value == u32::from(table.dim) - 1 { |
| 144 | value += reader.read_bits(u32::from(table.linbits))?; |
| 145 | } |
| 146 | *slot = if value == 0 { |
| 147 | 0.0 |
| 148 | } else if reader.read_bit()? { |
| 149 | -(value as f32) |
| 150 | } else { |
| 151 | value as f32 |
| 152 | }; |
| 153 | } |
| 154 | Ok(()) |
| 155 | } |
| 156 | |
| 157 | |
| 158 | pub(crate) fn decode_quad( |
| 159 | reader: &mut BitReader<'_>, |
| 160 | select: bool, |
| 161 | out: &mut [f32; 4], |
| 162 | ) -> Result<()> { |
| 163 | let tree = &trees().count1[usize::from(select)]; |
| 164 | let index = walk(tree, reader)?; |
| 165 | for (slot, shift) in out.iter_mut().zip([3, 2, 1, 0]) { |
| 166 | let value = (index >> shift) & 1; |
| 167 | *slot = if value == 0 { |
| 168 | 0.0 |
| 169 | } else if reader.read_bit()? { |
| 170 | -1.0 |
| 171 | } else { |
| 172 | 1.0 |
| 173 | }; |
| 174 | } |
| 175 | Ok(()) |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | #[derive(Clone, Debug, Default)] |
| 188 | pub(crate) struct BitBuf { |
| 189 | |
| 190 | bytes: Vec<u8>, |
| 191 | |
| 192 | acc: u64, |
| 193 | used: u32, |
| 194 | } |
| 195 | |
| 196 | impl BitBuf { |
| 197 | |
| 198 | pub(crate) fn new() -> BitBuf { |
| 199 | BitBuf::default() |
| 200 | } |
| 201 | |
| 202 | |
| 203 | pub(crate) fn bit_len(&self) -> u32 { |
| 204 | (self.bytes.len() as u32) * 8 + self.used |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | pub(crate) fn push_bits(&mut self, value: u64, n: u32) { |
| 217 | debug_assert!(n <= 64, "push_bits: n = {n} > 64"); |
| 218 | if n == 0 { |
| 219 | return; |
| 220 | } |
| 221 | let mask = if n >= 64 { u64::MAX } else { (1u64 << n) - 1 }; |
| 222 | let value = value & mask; |
| 223 | let free = 64 - self.used; |
| 224 | if n <= free { |
| 225 | self.acc |= value << (free - n); |
| 226 | self.used += n; |
| 227 | } else { |
| 228 | |
| 229 | |
| 230 | |
| 231 | self.acc |= value >> (n - free); |
| 232 | self.used = 64; |
| 233 | while self.used >= 8 { |
| 234 | self.bytes.push((self.acc >> 56) as u8); |
| 235 | self.acc <<= 8; |
| 236 | self.used -= 8; |
| 237 | } |
| 238 | let tail = n - free; |
| 239 | self.acc |= (value & ((1u64 << tail) - 1)) << (64 - tail); |
| 240 | self.used = tail; |
| 241 | } |
| 242 | while self.used >= 8 { |
| 243 | self.bytes.push((self.acc >> 56) as u8); |
| 244 | self.acc <<= 8; |
| 245 | self.used -= 8; |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | |
| 250 | pub(crate) fn push_bit(&mut self, bit: bool) { |
| 251 | if bit { |
| 252 | self.acc |= 1u64 << (63 - self.used); |
| 253 | } |
| 254 | self.used += 1; |
| 255 | if self.used == 8 { |
| 256 | self.bytes.push((self.acc >> 56) as u8); |
| 257 | self.acc = 0; |
| 258 | self.used = 0; |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | |
| 263 | |
| 264 | pub(crate) fn push_bits_from(&mut self, src: &[u8], nbits: u32) { |
| 265 | let mut bit = 0; |
| 266 | while bit < nbits { |
| 267 | let take = (nbits - bit).min(8); |
| 268 | let byte = src[(bit / 8) as usize]; |
| 269 | let off = bit % 8; |
| 270 | let value = u64::from(byte >> (8 - off - take)) & ((1u64 << take) - 1); |
| 271 | self.push_bits(value, take); |
| 272 | bit += take; |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | |
| 277 | pub(crate) fn append(&mut self, other: &BitBuf) { |
| 278 | self.push_bits_from(&other.bytes, (other.bytes.len() as u32) * 8); |
| 279 | if other.used > 0 { |
| 280 | self.push_bits(other.acc >> (64 - other.used), other.used); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | |
| 285 | |
| 286 | pub(crate) fn into_bytes(mut self) -> Vec<u8> { |
| 287 | if self.used > 0 { |
| 288 | self.bytes.push((self.acc >> 56) as u8); |
| 289 | } |
| 290 | self.bytes |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | |
| 295 | pub(crate) fn write_pair(writer: &mut BitBuf, table: Table, x: i32, y: i32) { |
| 296 | let max = u32::from(table.dim) - 1; |
| 297 | let escape = table.linbits > 0; |
| 298 | let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs()); |
| 299 | let (ix, iy) = (ax.min(max), ay.min(max)); |
| 300 | let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize]; |
| 301 | writer.push_bits(u64::from(code), u32::from(len)); |
| 302 | for (value, abs) in [(x, ax), (y, ay)] { |
| 303 | if abs >= max && escape { |
| 304 | writer.push_bits(u64::from(abs - max), u32::from(table.linbits)); |
| 305 | } |
| 306 | if abs != 0 { |
| 307 | writer.push_bit(value < 0); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | |
| 313 | pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 { |
| 314 | let index = quad |
| 315 | .iter() |
| 316 | .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); |
| 317 | let (len, _) = count1_table(select)[index]; |
| 318 | u32::from(len) + quad.iter().filter(|v| **v != 0).count() as u32 |
| 319 | } |
| 320 | |
| 321 | |
| 322 | pub(crate) fn write_quad(writer: &mut BitBuf, select: bool, quad: [i32; 4]) { |
| 323 | let index = quad |
| 324 | .iter() |
| 325 | .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); |
| 326 | let (len, code) = count1_table(select)[index]; |
| 327 | writer.push_bits(u64::from(code), u32::from(len)); |
| 328 | for value in quad { |
| 329 | if value != 0 { |
| 330 | writer.push_bit(value < 0); |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | #[cfg(test)] |
| 336 | mod tests { |
| 337 | use super::*; |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | #[test] |
| 343 | fn tables_are_complete_prefix_codes() { |
| 344 | let mut seen = 0; |
| 345 | for select in 0..32 { |
| 346 | let Ok(table) = big_table(select) else { |
| 347 | continue; |
| 348 | }; |
| 349 | if table.codes.is_empty() { |
| 350 | continue; |
| 351 | } |
| 352 | seen += 1; |
| 353 | assert_eq!( |
| 354 | table.codes.len(), |
| 355 | usize::from(table.dim) * usize::from(table.dim) |
| 356 | ); |
| 357 | let kraft: f64 = table |
| 358 | .codes |
| 359 | .iter() |
| 360 | .map(|(len, _)| 2f64.powi(-i32::from(*len))) |
| 361 | .sum(); |
| 362 | assert!( |
| 363 | (kraft - 1.0).abs() < 1e-12, |
| 364 | "table {select}: Kraft sum {kraft}" |
| 365 | ); |
| 366 | let tree = build_tree(table.codes); |
| 367 | assert_eq!( |
| 368 | tree.iter().flatten().filter(|n| **n < 0).count(), |
| 369 | table.codes.len() |
| 370 | ); |
| 371 | } |
| 372 | assert_eq!(seen, 29, "tables 0..31 minus the four unassigned slots"); |
| 373 | for select in [false, true] { |
| 374 | let codes = count1_table(select); |
| 375 | let kraft: f64 = codes |
| 376 | .iter() |
| 377 | .map(|(len, _)| 2f64.powi(-i32::from(*len))) |
| 378 | .sum(); |
| 379 | assert!((kraft - 1.0).abs() < 1e-12); |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn pairs_round_trip_through_every_table() { |
| 385 | for select in (1..32).filter(|s| big_table(*s).is_ok()) { |
| 386 | let table = big_table(select).unwrap(); |
| 387 | if table.codes.is_empty() { |
| 388 | continue; |
| 389 | } |
| 390 | let max = u32::from(table.dim) - 1; |
| 391 | let mut writer = BitBuf::new(); |
| 392 | let mut wanted = Vec::new(); |
| 393 | for x in 0..=max { |
| 394 | for y in 0..=max { |
| 395 | let (sx, sy) = (x as i32, -(y as i32)); |
| 396 | write_pair(&mut writer, table, sx, sy); |
| 397 | wanted.push([sx as f32, sy as f32]); |
| 398 | } |
| 399 | } |
| 400 | let bytes = writer.into_bytes(); |
| 401 | let mut reader = BitReader::new(&bytes); |
| 402 | for want in wanted { |
| 403 | let mut got = [0.0f32; 2]; |
| 404 | decode_pair(&mut reader, select, table, &mut got).unwrap(); |
| 405 | assert_eq!(got, want, "table {select}"); |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | #[test] |
| 417 | fn bits_survive_the_accumulator_boundary() { |
| 418 | let mut writer = BitBuf::new(); |
| 419 | let mut bits: Vec<bool> = Vec::new(); |
| 420 | let push = |writer: &mut BitBuf, bits: &mut Vec<bool>, value: u64, n: u32| { |
| 421 | for i in (0..n).rev() { |
| 422 | bits.push((value >> i) & 1 == 1); |
| 423 | } |
| 424 | writer.push_bits(value, n); |
| 425 | }; |
| 426 | for &(value, n) in &[ |
| 427 | (0u64, 0u32), |
| 428 | (0b101, 3), |
| 429 | (0xABCD_EF01_2345_6789, 64), |
| 430 | (0b1_0110, 5), |
| 431 | (0x00FF_00FF_00FF_00FF, 60), |
| 432 | (0, 0), |
| 433 | (0xDEAD_BEEF, 32), |
| 434 | (0b111, 3), |
| 435 | (0x5555_5555_5555_5555, 57), |
| 436 | ] { |
| 437 | push(&mut writer, &mut bits, value, n); |
| 438 | } |
| 439 | let mut want = Vec::new(); |
| 440 | let mut byte = 0u8; |
| 441 | for (i, bit) in bits.iter().enumerate() { |
| 442 | byte = (byte << 1) | u8::from(*bit); |
| 443 | if i % 8 == 7 { |
| 444 | want.push(byte); |
| 445 | byte = 0; |
| 446 | } |
| 447 | } |
| 448 | if !bits.len().is_multiple_of(8) { |
| 449 | want.push(byte << (8 - bits.len() % 8)); |
| 450 | } |
| 451 | assert_eq!(writer.into_bytes(), want); |
| 452 | } |
| 453 | |
| 454 | #[test] |
| 455 | fn quads_round_trip() { |
| 456 | for select in [false, true] { |
| 457 | let mut writer = BitBuf::new(); |
| 458 | let mut wanted = Vec::new(); |
| 459 | for index in 0..16 { |
| 460 | let quad = [ |
| 461 | (index >> 3) & 1, |
| 462 | -((index >> 2) & 1), |
| 463 | (index >> 1) & 1, |
| 464 | -(index & 1), |
| 465 | ]; |
| 466 | write_quad(&mut writer, select, quad); |
| 467 | wanted.push(quad.map(|v| v as f32)); |
| 468 | } |
| 469 | let bytes = writer.into_bytes(); |
| 470 | let mut reader = BitReader::new(&bytes); |
| 471 | for want in wanted { |
| 472 | let mut got = [0.0f32; 4]; |
| 473 | decode_quad(&mut reader, select, &mut got).unwrap(); |
| 474 | assert_eq!(got, want); |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | } |