| 1 | |
| 2 | |
| 3 | |
| 4 | use crate::huffman_tables::*; |
| 5 | use ec_core::bitio::{BitReader, BitWriter}; |
| 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 | pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> { |
| 180 | let max = u32::from(table.dim) - 1; |
| 181 | let escape = u32::from(table.linbits) > 0; |
| 182 | let (ix, iy) = (x.min(max), y.min(max)); |
| 183 | if (x > max && !escape) || (y > max && !escape) { |
| 184 | return None; |
| 185 | } |
| 186 | if escape && (x > max + (1 << table.linbits) - 1 || y > max + (1 << table.linbits) - 1) { |
| 187 | return None; |
| 188 | } |
| 189 | let (len, _) = table.codes[(ix * u32::from(table.dim) + iy) as usize]; |
| 190 | if len == 0 && !(x == 0 && y == 0) { |
| 191 | return None; |
| 192 | } |
| 193 | let mut bits = u32::from(len); |
| 194 | for value in [x, y] { |
| 195 | if value >= max && escape { |
| 196 | bits += u32::from(table.linbits); |
| 197 | } |
| 198 | if value != 0 { |
| 199 | bits += 1; |
| 200 | } |
| 201 | } |
| 202 | Some(bits) |
| 203 | } |
| 204 | |
| 205 | |
| 206 | pub(crate) fn write_pair(writer: &mut BitWriter, table: Table, x: i32, y: i32) { |
| 207 | let max = u32::from(table.dim) - 1; |
| 208 | let escape = table.linbits > 0; |
| 209 | let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs()); |
| 210 | let (ix, iy) = (ax.min(max), ay.min(max)); |
| 211 | let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize]; |
| 212 | writer.write_bits(u32::from(code), u32::from(len)); |
| 213 | for (value, abs) in [(x, ax), (y, ay)] { |
| 214 | if abs >= max && escape { |
| 215 | writer.write_bits(abs - max, u32::from(table.linbits)); |
| 216 | } |
| 217 | if abs != 0 { |
| 218 | writer.write_bit(value < 0); |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | |
| 224 | pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 { |
| 225 | let index = quad |
| 226 | .iter() |
| 227 | .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); |
| 228 | let (len, _) = count1_table(select)[index]; |
| 229 | u32::from(len) + quad.iter().filter(|v| **v != 0).count() as u32 |
| 230 | } |
| 231 | |
| 232 | |
| 233 | pub(crate) fn write_quad(writer: &mut BitWriter, select: bool, quad: [i32; 4]) { |
| 234 | let index = quad |
| 235 | .iter() |
| 236 | .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); |
| 237 | let (len, code) = count1_table(select)[index]; |
| 238 | writer.write_bits(u32::from(code), u32::from(len)); |
| 239 | for value in quad { |
| 240 | if value != 0 { |
| 241 | writer.write_bit(value < 0); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | #[cfg(test)] |
| 247 | mod tests { |
| 248 | use super::*; |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | #[test] |
| 254 | fn tables_are_complete_prefix_codes() { |
| 255 | let mut seen = 0; |
| 256 | for select in 0..32 { |
| 257 | let Ok(table) = big_table(select) else { |
| 258 | continue; |
| 259 | }; |
| 260 | if table.codes.is_empty() { |
| 261 | continue; |
| 262 | } |
| 263 | seen += 1; |
| 264 | assert_eq!( |
| 265 | table.codes.len(), |
| 266 | usize::from(table.dim) * usize::from(table.dim) |
| 267 | ); |
| 268 | let kraft: f64 = table |
| 269 | .codes |
| 270 | .iter() |
| 271 | .map(|(len, _)| 2f64.powi(-i32::from(*len))) |
| 272 | .sum(); |
| 273 | assert!( |
| 274 | (kraft - 1.0).abs() < 1e-12, |
| 275 | "table {select}: Kraft sum {kraft}" |
| 276 | ); |
| 277 | let tree = build_tree(table.codes); |
| 278 | assert_eq!( |
| 279 | tree.iter().flatten().filter(|n| **n < 0).count(), |
| 280 | table.codes.len() |
| 281 | ); |
| 282 | } |
| 283 | assert_eq!(seen, 29, "tables 0..31 minus the four unassigned slots"); |
| 284 | for select in [false, true] { |
| 285 | let codes = count1_table(select); |
| 286 | let kraft: f64 = codes |
| 287 | .iter() |
| 288 | .map(|(len, _)| 2f64.powi(-i32::from(*len))) |
| 289 | .sum(); |
| 290 | assert!((kraft - 1.0).abs() < 1e-12); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn pairs_round_trip_through_every_table() { |
| 296 | for select in (1..32).filter(|s| big_table(*s).is_ok()) { |
| 297 | let table = big_table(select).unwrap(); |
| 298 | if table.codes.is_empty() { |
| 299 | continue; |
| 300 | } |
| 301 | let max = u32::from(table.dim) - 1; |
| 302 | let mut writer = BitWriter::new(); |
| 303 | let mut wanted = Vec::new(); |
| 304 | for x in 0..=max { |
| 305 | for y in 0..=max { |
| 306 | let (sx, sy) = (x as i32, -(y as i32)); |
| 307 | write_pair(&mut writer, table, sx, sy); |
| 308 | wanted.push([sx as f32, sy as f32]); |
| 309 | } |
| 310 | } |
| 311 | let bytes = writer.into_bytes(); |
| 312 | let mut reader = BitReader::new(&bytes); |
| 313 | for want in wanted { |
| 314 | let mut got = [0.0f32; 2]; |
| 315 | decode_pair(&mut reader, select, table, &mut got).unwrap(); |
| 316 | assert_eq!(got, want, "table {select}"); |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn quads_round_trip() { |
| 323 | for select in [false, true] { |
| 324 | let mut writer = BitWriter::new(); |
| 325 | let mut wanted = Vec::new(); |
| 326 | for index in 0..16 { |
| 327 | let quad = [ |
| 328 | (index >> 3) & 1, |
| 329 | -((index >> 2) & 1), |
| 330 | (index >> 1) & 1, |
| 331 | -(index & 1), |
| 332 | ]; |
| 333 | write_quad(&mut writer, select, quad); |
| 334 | wanted.push(quad.map(|v| v as f32)); |
| 335 | } |
| 336 | let bytes = writer.into_bytes(); |
| 337 | let mut reader = BitReader::new(&bytes); |
| 338 | for want in wanted { |
| 339 | let mut got = [0.0f32; 4]; |
| 340 | decode_quad(&mut reader, select, &mut got).unwrap(); |
| 341 | assert_eq!(got, want); |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | } |