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