| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use ec_core::{Error, Result}; |
| 14 | |
| 15 | use crate::bits::{Bits, BitsOut}; |
| 16 | |
| 17 | |
| 18 | #[derive(Debug, Clone)] |
| 19 | pub struct Codebook { |
| 20 | |
| 21 | pub dimensions: usize, |
| 22 | |
| 23 | tree: Vec<Node>, |
| 24 | |
| 25 | values: Vec<f32>, |
| 26 | } |
| 27 | |
| 28 | impl Codebook { |
| 29 | |
| 30 | pub fn parse(bits: &mut Bits) -> Result<Codebook> { |
| 31 | if bits.read(24) != 0x0056_4342 { |
| 32 | return Err(Error::corrupt("codebook sync pattern")); |
| 33 | } |
| 34 | let dimensions = bits.read(16) as usize; |
| 35 | let entries = bits.read(24) as usize; |
| 36 | if bits.eop() { |
| 37 | return Err(Error::corrupt("codebook header truncated")); |
| 38 | } |
| 39 | if dimensions == 0 || entries == 0 { |
| 40 | return Err(Error::corrupt("empty codebook")); |
| 41 | } |
| 42 | |
| 43 | |
| 44 | |
| 45 | if entries as u64 > bits.remaining() + 64 { |
| 46 | return Err(Error::corrupt("codebook claims more entries than bits")); |
| 47 | } |
| 48 | |
| 49 | let mut lengths = vec![0u8; entries]; |
| 50 | if bits.bit() { |
| 51 | |
| 52 | let mut entry = 0usize; |
| 53 | let mut length = bits.read(5) + 1; |
| 54 | while entry < entries { |
| 55 | if length > 32 { |
| 56 | return Err(Error::corrupt("ordered codebook overran 32 bits")); |
| 57 | } |
| 58 | let bits_needed = ilog((entries - entry) as u32); |
| 59 | let run = bits.read(bits_needed) as usize; |
| 60 | if entry + run > entries { |
| 61 | return Err(Error::corrupt("ordered codebook run past the end")); |
| 62 | } |
| 63 | lengths[entry..entry + run].fill(length as u8); |
| 64 | entry += run; |
| 65 | length += 1; |
| 66 | if bits.eop() { |
| 67 | return Err(Error::corrupt("ordered codebook truncated")); |
| 68 | } |
| 69 | } |
| 70 | } else { |
| 71 | let sparse = bits.bit(); |
| 72 | for length in lengths.iter_mut() { |
| 73 | if sparse && !bits.bit() { |
| 74 | continue; |
| 75 | } |
| 76 | *length = (bits.read(5) + 1) as u8; |
| 77 | } |
| 78 | if bits.eop() { |
| 79 | return Err(Error::corrupt("codebook lengths truncated")); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | let (tree, _) = assign_codes(&lengths)?; |
| 84 | |
| 85 | let lookup_type = bits.read(4); |
| 86 | let values = match lookup_type { |
| 87 | 0 => Vec::new(), |
| 88 | 1 | 2 => { |
| 89 | let minimum = bits.float32(); |
| 90 | let delta = bits.float32(); |
| 91 | let value_bits = bits.read(4) + 1; |
| 92 | let sequence_p = bits.bit(); |
| 93 | let lookup_values = match lookup_type { |
| 94 | 1 => lookup1_values(entries, dimensions), |
| 95 | _ => entries * dimensions, |
| 96 | }; |
| 97 | if bits.eop() || lookup_values as u64 > bits.remaining() + 64 { |
| 98 | return Err(Error::corrupt("codebook lookup truncated")); |
| 99 | } |
| 100 | let multiplicands: Vec<f32> = (0..lookup_values) |
| 101 | .map(|_| bits.read(value_bits) as f32) |
| 102 | .collect(); |
| 103 | expand_lookup( |
| 104 | lookup_type, |
| 105 | entries, |
| 106 | dimensions, |
| 107 | minimum, |
| 108 | delta, |
| 109 | sequence_p, |
| 110 | &multiplicands, |
| 111 | )? |
| 112 | } |
| 113 | other => { |
| 114 | return Err(Error::unsupported( |
| 115 | format!("codebook lookup type {other}"), |
| 116 | "Vorbis I defines 0, 1 and 2", |
| 117 | )); |
| 118 | } |
| 119 | }; |
| 120 | if bits.eop() { |
| 121 | return Err(Error::corrupt("codebook truncated")); |
| 122 | } |
| 123 | |
| 124 | Ok(Codebook { |
| 125 | dimensions, |
| 126 | tree, |
| 127 | values, |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub fn has_values(&self) -> bool { |
| 134 | !self.values.is_empty() |
| 135 | } |
| 136 | |
| 137 | |
| 138 | pub fn decode_scalar(&self, bits: &mut Bits) -> Option<u32> { |
| 139 | let mut node = 0usize; |
| 140 | loop { |
| 141 | let child = self.tree[node].child[usize::from(bits.bit())]; |
| 142 | if bits.eop() { |
| 143 | return None; |
| 144 | } |
| 145 | match child { |
| 146 | 0 => return None, |
| 147 | c if c < 0 => return Some((-c - 1) as u32), |
| 148 | c => node = c as usize, |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | |
| 154 | pub fn decode_vector(&self, bits: &mut Bits) -> Option<&[f32]> { |
| 155 | let entry = self.decode_scalar(bits)? as usize; |
| 156 | self.vector(entry) |
| 157 | } |
| 158 | |
| 159 | |
| 160 | pub fn vector(&self, entry: usize) -> Option<&[f32]> { |
| 161 | let start = entry.checked_mul(self.dimensions)?; |
| 162 | self.values.get(start..start + self.dimensions) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | pub fn lookup1_values(entries: usize, dimensions: usize) -> usize { |
| 169 | let mut value = 1usize; |
| 170 | loop { |
| 171 | let mut product = 1usize; |
| 172 | let mut overflow = false; |
| 173 | for _ in 0..dimensions { |
| 174 | match product.checked_mul(value + 1) { |
| 175 | Some(p) if p <= entries => product = p, |
| 176 | _ => { |
| 177 | overflow = true; |
| 178 | break; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | if overflow { |
| 183 | return value; |
| 184 | } |
| 185 | value += 1; |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | |
| 190 | fn expand_lookup( |
| 191 | lookup_type: u32, |
| 192 | entries: usize, |
| 193 | dimensions: usize, |
| 194 | minimum: f32, |
| 195 | delta: f32, |
| 196 | sequence_p: bool, |
| 197 | multiplicands: &[f32], |
| 198 | ) -> Result<Vec<f32>> { |
| 199 | let total = entries |
| 200 | .checked_mul(dimensions) |
| 201 | .filter(|n| *n <= 1 << 24) |
| 202 | .ok_or_else(|| Error::corrupt("codebook value table too large"))?; |
| 203 | let mut values = vec![0.0f32; total]; |
| 204 | let lookup_values = multiplicands.len(); |
| 205 | for entry in 0..entries { |
| 206 | let mut last = 0.0f32; |
| 207 | let mut divisor = 1usize; |
| 208 | for i in 0..dimensions { |
| 209 | let offset = match lookup_type { |
| 210 | 1 => (entry / divisor) % lookup_values.max(1), |
| 211 | _ => entry * dimensions + i, |
| 212 | }; |
| 213 | let value = multiplicands.get(offset).copied().unwrap_or(0.0) * delta + minimum + last; |
| 214 | values[entry * dimensions + i] = value; |
| 215 | if sequence_p { |
| 216 | last = value; |
| 217 | } |
| 218 | divisor = divisor.saturating_mul(lookup_values.max(1)); |
| 219 | } |
| 220 | } |
| 221 | Ok(values) |
| 222 | } |
| 223 | |
| 224 | |
| 225 | pub fn ilog(mut value: u32) -> u32 { |
| 226 | let mut bits = 0; |
| 227 | while value > 0 { |
| 228 | bits += 1; |
| 229 | value >>= 1; |
| 230 | } |
| 231 | bits |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | fn assign_codes(lengths: &[u8]) -> Result<(Vec<Node>, Vec<u32>)> { |
| 250 | let mut nodes = vec![Node::default()]; |
| 251 | let mut codes = vec![0u32; lengths.len()]; |
| 252 | for (entry, &length) in lengths.iter().enumerate() { |
| 253 | if length == 0 { |
| 254 | continue; |
| 255 | } |
| 256 | if length > 32 { |
| 257 | return Err(Error::corrupt("codebook codeword longer than 32 bits")); |
| 258 | } |
| 259 | let mut node = 0usize; |
| 260 | let mut code = 0u32; |
| 261 | let mut path: Vec<usize> = Vec::with_capacity(usize::from(length)); |
| 262 | for step in 0..length { |
| 263 | |
| 264 | let below = length - step - 1; |
| 265 | let branch = (0..2) |
| 266 | .find(|&bit| free_depth(nodes[node].child[bit], &nodes) <= below) |
| 267 | .ok_or_else(|| Error::corrupt("codebook is over-full"))?; |
| 268 | code = (code << 1) | branch as u32; |
| 269 | path.push(node); |
| 270 | match below { |
| 271 | 0 => nodes[node].child[branch] = -((entry as i32) + 1), |
| 272 | _ => { |
| 273 | if nodes[node].child[branch] == 0 { |
| 274 | nodes.push(Node::default()); |
| 275 | nodes[node].child[branch] = (nodes.len() - 1) as i32; |
| 276 | } |
| 277 | node = nodes[node].child[branch] as usize; |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | for &node in path.iter().rev() { |
| 283 | let left = free_depth(nodes[node].child[0], &nodes); |
| 284 | let right = free_depth(nodes[node].child[1], &nodes); |
| 285 | nodes[node].free = left.min(right).saturating_add(1); |
| 286 | } |
| 287 | codes[entry] = code; |
| 288 | } |
| 289 | Ok((nodes, codes)) |
| 290 | } |
| 291 | |
| 292 | |
| 293 | #[derive(Debug, Clone, Copy)] |
| 294 | pub struct Node { |
| 295 | |
| 296 | |
| 297 | child: [i32; 2], |
| 298 | |
| 299 | free: u8, |
| 300 | } |
| 301 | |
| 302 | impl Default for Node { |
| 303 | fn default() -> Node { |
| 304 | |
| 305 | |
| 306 | Node { |
| 307 | child: [0, 0], |
| 308 | free: 1, |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | |
| 314 | fn free_depth(slot: i32, nodes: &[Node]) -> u8 { |
| 315 | match slot { |
| 316 | 0 => 0, |
| 317 | s if s < 0 => 255, |
| 318 | s => nodes[s as usize].free, |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | #[derive(Debug, Clone)] |
| 325 | pub struct CodebookSpec { |
| 326 | |
| 327 | pub dimensions: usize, |
| 328 | |
| 329 | pub lengths: Vec<u8>, |
| 330 | |
| 331 | pub codes: Vec<u32>, |
| 332 | |
| 333 | |
| 334 | pub values: Vec<f32>, |
| 335 | } |
| 336 | |
| 337 | impl CodebookSpec { |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | pub fn huffman(weights: &[f64], values: Vec<f32>) -> CodebookSpec { |
| 345 | let lengths = huffman_lengths(weights); |
| 346 | |
| 347 | let (_, codes) = assign_codes(&lengths).expect("a Kraft-complete book always assigns"); |
| 348 | CodebookSpec { |
| 349 | dimensions: 1, |
| 350 | lengths, |
| 351 | codes, |
| 352 | values, |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | |
| 357 | pub fn entries(&self) -> usize { |
| 358 | self.lengths.len() |
| 359 | } |
| 360 | |
| 361 | |
| 362 | pub fn write(&self, out: &mut BitsOut, entry: usize) { |
| 363 | let length = u32::from(self.lengths[entry]); |
| 364 | let code = self.codes[entry]; |
| 365 | |
| 366 | |
| 367 | for depth in (0..length).rev() { |
| 368 | out.bit((code >> depth) & 1 != 0); |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | fn huffman_lengths(weights: &[f64]) -> Vec<u8> { |
| 380 | let n = weights.len(); |
| 381 | assert!(n > 0, "a codebook needs at least one entry"); |
| 382 | if n == 1 { |
| 383 | return vec![1]; |
| 384 | } |
| 385 | let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0; |
| 386 | let mut nodes: Vec<(f64, usize)> = weights |
| 387 | .iter() |
| 388 | .enumerate() |
| 389 | .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i)) |
| 390 | .collect(); |
| 391 | |
| 392 | let mut parent = vec![usize::MAX; n]; |
| 393 | let mut heap: Vec<(f64, usize)> = nodes.clone(); |
| 394 | heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); |
| 395 | let mut merged: Vec<(f64, usize)> = Vec::new(); |
| 396 | let mut next_id = n; |
| 397 | while heap.len() + merged.len() > 1 { |
| 398 | let mut take = || -> (f64, usize) { |
| 399 | let from_heap = heap.last().map(|x| x.0); |
| 400 | let from_merged = merged.first().map(|x| x.0); |
| 401 | match (from_heap, from_merged) { |
| 402 | (Some(a), Some(b)) if a <= b => heap.pop().unwrap(), |
| 403 | (Some(_), None) => heap.pop().unwrap(), |
| 404 | _ => merged.remove(0), |
| 405 | } |
| 406 | }; |
| 407 | let (wa, a) = take(); |
| 408 | let (wb, b) = take(); |
| 409 | parent.push(usize::MAX); |
| 410 | parent[a] = next_id; |
| 411 | parent[b] = next_id; |
| 412 | merged.push((wa + wb, next_id)); |
| 413 | next_id += 1; |
| 414 | } |
| 415 | nodes.clear(); |
| 416 | |
| 417 | let mut lengths = vec![0u8; n]; |
| 418 | for (i, length) in lengths.iter_mut().enumerate() { |
| 419 | let mut node = i; |
| 420 | let mut depth = 0u32; |
| 421 | while parent[node] != usize::MAX { |
| 422 | node = parent[node]; |
| 423 | depth += 1; |
| 424 | } |
| 425 | *length = depth.clamp(1, 24) as u8; |
| 426 | } |
| 427 | |
| 428 | |
| 429 | balance(&mut lengths); |
| 430 | lengths |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | fn balance(lengths: &mut [u8]) { |
| 436 | let kraft = |lengths: &[u8]| -> f64 { |
| 437 | lengths |
| 438 | .iter() |
| 439 | .map(|&l| 2f64.powi(-i32::from(l))) |
| 440 | .sum::<f64>() |
| 441 | }; |
| 442 | |
| 443 | while kraft(lengths) > 1.0 + 1e-12 { |
| 444 | let (index, _) = lengths |
| 445 | .iter() |
| 446 | .enumerate() |
| 447 | .min_by_key(|(_, l)| **l) |
| 448 | .expect("non-empty"); |
| 449 | lengths[index] += 1; |
| 450 | } |
| 451 | |
| 452 | loop { |
| 453 | let sum = kraft(lengths); |
| 454 | let (index, &longest) = lengths |
| 455 | .iter() |
| 456 | .enumerate() |
| 457 | .max_by_key(|(_, l)| **l) |
| 458 | .expect("non-empty"); |
| 459 | if longest <= 1 || sum + 2f64.powi(-i32::from(longest)) > 1.0 + 1e-12 { |
| 460 | break; |
| 461 | } |
| 462 | lengths[index] -= 1; |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | #[cfg(test)] |
| 467 | mod tests { |
| 468 | use super::*; |
| 469 | use crate::bits::BitsOut; |
| 470 | |
| 471 | #[test] |
| 472 | fn lookup1_values_matches_the_definition() { |
| 473 | assert_eq!(lookup1_values(1, 1), 1); |
| 474 | assert_eq!(lookup1_values(64, 2), 8); |
| 475 | assert_eq!(lookup1_values(63, 2), 7); |
| 476 | assert_eq!(lookup1_values(1000, 3), 10); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn a_designed_book_decodes_back_through_the_parsed_tree() { |
| 481 | |
| 482 | |
| 483 | let weights: Vec<f64> = (0..17).map(|i| 1.0 / (1.0 + f64::from(i))).collect(); |
| 484 | let spec = CodebookSpec::huffman(&weights, Vec::new()); |
| 485 | assert_eq!(spec.entries(), 17); |
| 486 | let kraft: f64 = spec.lengths.iter().map(|&l| 2f64.powi(-i32::from(l))).sum(); |
| 487 | assert!((kraft - 1.0).abs() < 1e-9, "kraft sum {kraft}"); |
| 488 | |
| 489 | let mut out = BitsOut::new(); |
| 490 | for entry in 0..spec.entries() { |
| 491 | spec.write(&mut out, entry); |
| 492 | } |
| 493 | let bytes = out.finish(); |
| 494 | |
| 495 | let (tree, _) = assign_codes(&spec.lengths).expect("tree"); |
| 496 | let book = Codebook { |
| 497 | dimensions: 1, |
| 498 | tree, |
| 499 | values: Vec::new(), |
| 500 | }; |
| 501 | let mut bits = Bits::new(&bytes); |
| 502 | for entry in 0..spec.entries() { |
| 503 | assert_eq!(book.decode_scalar(&mut bits), Some(entry as u32)); |
| 504 | } |
| 505 | } |
| 506 | } |