Length-limited Huffman via package-merge (cherry-pick 01cfce6)
Browse files at this commitc52d51c2ae2367b5baa3572743f15531158981b1Parent: a4a1e96- perf
- length-limited Huffman via package-merge (cherry-pick 01cfce6)
1 changed file +48 -73
- crates/ec-vorbis/src/codebook.rs +48 -73
crates/ec-vorbis/src/codebook.rsmodified+48 -73
| @@ -370,97 +370,72 @@ impl CodebookSpec { | |||
| 370 | } | 370 | } |
| 371 | } | 371 | } |
| 372 | 372 | ||
| 373 | -/// Huffman code lengths for `weights`, capped at 24 bits. | 373 | +/// Length-limited Huffman code lengths for `weights`, capped at 24 bits. |
| 374 | /// | 374 | /// |
| 375 | -/// The cap is enforced by flattening: a weight small enough to earn a 25-bit | 375 | +/// Package-merge (Larmore–Hirschberg): optimal under the cap and |
| 376 | -/// codeword is raised until it does not. With at most a few hundred entries and | 376 | +/// Kraft-complete by construction, so the decoder's canonical rebuild has no |
| 377 | -/// weights within a few decades of each other the cap never binds, and when it | 377 | +/// ambiguity and no hole. The earlier clamp-then-rebalance scheme was O(n) |
| 378 | -/// does the cost is a fraction of a bit on the rarest symbol. | 378 | +/// per 2^-25 of Kraft slack: corpus-fitted books with weights spanning five |
| 379 | +/// decades made one encoder construction cost nine seconds. | ||
| 379 | fn huffman_lengths(weights: &[f64]) -> Vec<u8> { | 380 | fn huffman_lengths(weights: &[f64]) -> Vec<u8> { |
| 381 | + const MAX_LENGTH: usize = 24; | ||
| 380 | let n = weights.len(); | 382 | let n = weights.len(); |
| 381 | assert!(n > 0, "a codebook needs at least one entry"); | 383 | assert!(n > 0, "a codebook needs at least one entry"); |
| 382 | if n == 1 { | 384 | if n == 1 { |
| 383 | return vec![1]; | 385 | return vec![1]; |
| 384 | } | 386 | } |
| 387 | + assert!(n <= 1 << MAX_LENGTH, "more entries than 24-bit codewords"); | ||
| 388 | + // Zero weights still need a codeword; keep them far below everything real. | ||
| 385 | let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0; | 389 | let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0; |
| 386 | - let mut nodes: Vec<(f64, usize)> = weights | 390 | + let mut leaves: Vec<(f64, usize)> = weights |
| 387 | .iter() | 391 | .iter() |
| 388 | .enumerate() | 392 | .enumerate() |
| 389 | .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i)) | 393 | .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i)) |
| 390 | .collect(); | 394 | .collect(); |
| 391 | - // Leaves first, then merged nodes, tracked as a forest over `parent`. | 395 | + leaves.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap().then(a.1.cmp(&b.1))); |
| 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 | 396 | ||
| 417 | - let mut lengths = vec![0u8; n]; | 397 | + // An item is a leaf or a package of two items from the previous level. |
| 418 | - for (i, length) in lengths.iter_mut().enumerate() { | 398 | + #[derive(Clone, Copy)] |
| 419 | - let mut node = i; | 399 | + enum Item { |
| 420 | - let mut depth = 0u32; | 400 | + Leaf(usize), |
| 421 | - while parent[node] != usize::MAX { | 401 | + Package(usize, usize), |
| 422 | - node = parent[node]; | ||
| 423 | - depth += 1; | ||
| 424 | - } | ||
| 425 | - *length = depth.clamp(1, 24) as u8; | ||
| 426 | } | 402 | } |
| 427 | - // Clamping can leave the tree over-full; rebalance by lengthening the | 403 | + // levels[l] = sorted items at that level; level 0 is the deepest. |
| 428 | - // shallowest entries until Kraft's sum is back at one. | 404 | + let mut levels: Vec<Vec<(f64, Item)>> = Vec::with_capacity(MAX_LENGTH); |
| 429 | - balance(&mut lengths); | 405 | + let leaf_items: Vec<(f64, Item)> = leaves.iter().map(|&(w, i)| (w, Item::Leaf(i))).collect(); |
| 430 | - lengths | 406 | + levels.push(leaf_items.clone()); |
| 431 | -} | 407 | + for level in 1..MAX_LENGTH { |
| 432 | - | 408 | + let prev = &levels[level - 1]; |
| 433 | -/// Push a length vector to exactly Kraft-complete, so the decoder's canonical | 409 | + let mut packages: Vec<(f64, Item)> = prev |
| 434 | -/// rebuild has no ambiguity and no hole. | 410 | + .chunks_exact(2) |
| 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 | - // Over-full: lengthen the shortest codes. | ||
| 443 | - while kraft(lengths) > 1.0 + 1e-12 { | ||
| 444 | - let (index, _) = lengths | ||
| 445 | - .iter() | ||
| 446 | .enumerate() | 411 | .enumerate() |
| 447 | - .min_by_key(|(_, l)| **l) | 412 | + .map(|(k, pair)| (pair[0].0 + pair[1].0, Item::Package(2 * k, 2 * k + 1))) |
| 448 | - .expect("non-empty"); | 413 | + .collect(); |
| 449 | - lengths[index] += 1; | 414 | + let mut merged = leaf_items.clone(); |
| 415 | + merged.append(&mut packages); | ||
| 416 | + merged.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); | ||
| 417 | + levels.push(merged); | ||
| 450 | } | 418 | } |
| 451 | - // Under-full: shorten the longest, which only ever helps the rare symbols. | 419 | + |
| 452 | - loop { | 420 | + // The cheapest 2n-2 items of the top level; each leaf occurrence adds one |
| 453 | - let sum = kraft(lengths); | 421 | + // to that symbol's length. |
| 454 | - let (index, &longest) = lengths | 422 | + let mut lengths = vec![0u8; n]; |
| 455 | - .iter() | 423 | + let mut stack: Vec<(usize, usize)> = (0..2 * n - 2).map(|k| (MAX_LENGTH - 1, k)).collect(); |
| 456 | - .enumerate() | 424 | + while let Some((level, index)) = stack.pop() { |
| 457 | - .max_by_key(|(_, l)| **l) | 425 | + match levels[level][index].1 { |
| 458 | - .expect("non-empty"); | 426 | + Item::Leaf(i) => lengths[i] += 1, |
| 459 | - if longest <= 1 || sum + 2f64.powi(-i32::from(longest)) > 1.0 + 1e-12 { | 427 | + Item::Package(a, b) => { |
| 460 | - break; | 428 | + stack.push((level - 1, a)); |
| 429 | + stack.push((level - 1, b)); | ||
| 430 | + } | ||
| 461 | } | 431 | } |
| 462 | - lengths[index] -= 1; | ||
| 463 | } | 432 | } |
| 433 | + debug_assert!(lengths.iter().all(|&l| (1..=MAX_LENGTH as u8).contains(&l))); | ||
| 434 | + debug_assert!( | ||
| 435 | + (lengths.iter().map(|&l| 2f64.powi(-i32::from(l))).sum::<f64>() - 1.0).abs() < 1e-9, | ||
| 436 | + "package-merge yields a complete code" | ||
| 437 | + ); | ||
| 438 | + lengths | ||
| 464 | } | 439 | } |
| 465 | 440 | ||
| 466 | #[cfg(test)] | 441 | #[cfg(test)] |