| 1 |
use std::io::{self, Error, Seek}; |
| 2 |
|
| 3 |
use bitstream_io::{BitRead, BitReader, Endianness}; |
| 4 |
|
| 5 |
#[derive(Default, Clone, Copy)] |
| 6 |
pub struct TableEntry { |
| 7 |
/// Wide enough to fit the max symbol nbr. |
| 8 |
pub sym: u16, |
| 9 |
/// 0 means no symbol. |
| 10 |
pub len: u8, |
| 11 |
} |
| 12 |
|
| 13 |
/// Deflate uses max 288 symbols. |
| 14 |
const MAX_HUFFMAN_SYMBOLS: usize = 288; |
| 15 |
/// Implode uses max 16-bit codewords. |
| 16 |
const MAX_HUFFMAN_BITS: usize = 16; |
| 17 |
/// Seems a good trade-off. |
| 18 |
const HUFFMAN_LOOKUP_TABLE_BITS: u8 = 8; |
| 19 |
|
| 20 |
pub struct HuffmanDecoder { |
| 21 |
/// Lookup table for fast decoding of short codewords. |
| 22 |
pub table: [TableEntry; 1 << HUFFMAN_LOOKUP_TABLE_BITS], |
| 23 |
/// "Sentinel bits" value for each codeword length. |
| 24 |
pub sentinel_bits: [u32; MAX_HUFFMAN_BITS + 1], |
| 25 |
/// First symbol index minus first codeword mod 2**16 for each length. |
| 26 |
pub offset_first_sym_idx: [u16; MAX_HUFFMAN_BITS + 1], |
| 27 |
/// Map from symbol index to symbol. |
| 28 |
pub syms: [u16; MAX_HUFFMAN_SYMBOLS], |
| 29 |
// num_syms:usize |
| 30 |
} |
| 31 |
|
| 32 |
impl Default for HuffmanDecoder { |
| 33 |
fn default() -> Self { |
| 34 |
Self { |
| 35 |
table: [TableEntry::default(); 1 << HUFFMAN_LOOKUP_TABLE_BITS], |
| 36 |
sentinel_bits: [0; MAX_HUFFMAN_BITS + 1], |
| 37 |
offset_first_sym_idx: [0; MAX_HUFFMAN_BITS + 1], |
| 38 |
syms: [0; MAX_HUFFMAN_SYMBOLS], |
| 39 |
} |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/// Reverse the n least significant bits of x. |
| 44 |
/// The (16 - n) most significant bits of the result will be zero. |
| 45 |
pub fn reverse_lsb(x: u16, n: usize) -> u16 { |
| 46 |
debug_assert!(n > 0); |
| 47 |
debug_assert!(n <= 16); |
| 48 |
x.reverse_bits() >> (16 - n) |
| 49 |
} |
| 50 |
|
| 51 |
/// Initialize huffman decoder d for a code defined by the n codeword lengths. |
| 52 |
/// Returns `Err` if the codeword lengths do not correspond to a valid prefix |
| 53 |
/// code. |
| 54 |
impl HuffmanDecoder { |
| 55 |
pub fn init(&mut self, lengths: &[u8], n: usize) -> std::io::Result<()> { |
| 56 |
let mut count = [0; MAX_HUFFMAN_BITS + 1]; |
| 57 |
let mut code = [0; MAX_HUFFMAN_BITS + 1]; |
| 58 |
let mut sym_idx = [0u16; MAX_HUFFMAN_BITS + 1]; |
| 59 |
|
| 60 |
// Count the number of codewords of each length. |
| 61 |
for i in 0..n { |
| 62 |
debug_assert!(lengths[i] as usize <= MAX_HUFFMAN_BITS); |
| 63 |
count[lengths[i] as usize] += 1; |
| 64 |
} |
| 65 |
count[0] = 0; // Ignore zero-length codewords. |
| 66 |
// Compute sentinel_bits and offset_first_sym_idx for each length. |
| 67 |
code[0] = 0; |
| 68 |
sym_idx[0] = 0; |
| 69 |
for l in 1..=MAX_HUFFMAN_BITS { |
| 70 |
// First canonical codeword of this length. |
| 71 |
code[l] = (code[l - 1] + count[l - 1]) << 1; |
| 72 |
|
| 73 |
if count[l] != 0 && u32::from(code[l]) + u32::from(count[l]) - 1 > (1u32 << l) - 1 { |
| 74 |
// The last codeword is longer than l bits. |
| 75 |
return Err(Error::new( |
| 76 |
io::ErrorKind::InvalidData, |
| 77 |
"the last codeword is longer than len bits", |
| 78 |
)); |
| 79 |
} |
| 80 |
|
| 81 |
let s = (u32::from(code[l]) + u32::from(count[l])) << (MAX_HUFFMAN_BITS - l); |
| 82 |
self.sentinel_bits[l] = s; |
| 83 |
debug_assert!(self.sentinel_bits[l] >= u32::from(code[l]), "No overflow!"); |
| 84 |
|
| 85 |
sym_idx[l] = sym_idx[l - 1] + count[l - 1]; |
| 86 |
self.offset_first_sym_idx[l] = sym_idx[l].wrapping_sub(code[l]); |
| 87 |
} |
| 88 |
|
| 89 |
// Zero-initialize the lookup table. |
| 90 |
self.table.fill(TableEntry::default()); |
| 91 |
|
| 92 |
// Build mapping from index to symbol and populate the lookup table. |
| 93 |
lengths |
| 94 |
.iter() |
| 95 |
.enumerate() |
| 96 |
.take(n) |
| 97 |
.for_each(|(i, code_len)| { |
| 98 |
let l = *code_len as usize; |
| 99 |
if l == 0 { |
| 100 |
return; |
| 101 |
} |
| 102 |
|
| 103 |
self.syms[sym_idx[l] as usize] = i as u16; |
| 104 |
sym_idx[l] += 1; |
| 105 |
|
| 106 |
if l <= HUFFMAN_LOOKUP_TABLE_BITS as usize { |
| 107 |
self.table_insert(i, l, code[l]); |
| 108 |
code[l] += 1; |
| 109 |
} |
| 110 |
}); |
| 111 |
|
| 112 |
Ok(()) |
| 113 |
} |
| 114 |
|
| 115 |
pub fn table_insert(&mut self, sym: usize, len: usize, codeword: u16) { |
| 116 |
debug_assert!(len <= HUFFMAN_LOOKUP_TABLE_BITS as usize); |
| 117 |
|
| 118 |
let codeword = reverse_lsb(codeword, len); // Make it LSB-first. |
| 119 |
let pad_len = HUFFMAN_LOOKUP_TABLE_BITS as usize - len; |
| 120 |
|
| 121 |
// Pad the pad_len upper bits with all bit combinations. |
| 122 |
for padding in 0..(1 << pad_len) { |
| 123 |
let index = (codeword | (padding << len)) as usize; |
| 124 |
debug_assert!(sym <= u16::MAX as usize); |
| 125 |
self.table[index].sym = sym as u16; |
| 126 |
debug_assert!(len <= u8::MAX as usize); |
| 127 |
self.table[index].len = len as u8; |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
/// Use the decoder d to decode a symbol from the LSB-first zero-padded bits. |
| 132 |
/// Returns the decoded symbol number or an error if no symbol could be decoded. |
| 133 |
/// *num_used_bits will be set to the number of bits used to decode the symbol, |
| 134 |
/// or zero if no symbol could be decoded. |
| 135 |
pub fn huffman_decode<T: std::io::Read + Seek, E: Endianness>( |
| 136 |
&mut self, |
| 137 |
length: u64, |
| 138 |
is: &mut BitReader<T, E>, |
| 139 |
) -> std::io::Result<u16> { |
| 140 |
// First try the lookup table. |
| 141 |
let read_bits1 = u64::from(HUFFMAN_LOOKUP_TABLE_BITS).min(length - is.position_in_bits()?); |
| 142 |
let lookup_bits = !is.read_var::<u8>(read_bits1 as u32)? as usize; |
| 143 |
debug_assert!(lookup_bits < self.table.len()); |
| 144 |
if self.table[lookup_bits].len != 0 { |
| 145 |
debug_assert!(self.table[lookup_bits].len <= HUFFMAN_LOOKUP_TABLE_BITS); |
| 146 |
is.seek_bits(io::SeekFrom::Current( |
| 147 |
-(read_bits1 as i64) + i64::from(self.table[lookup_bits].len), |
| 148 |
))?; |
| 149 |
return Ok(self.table[lookup_bits].sym); |
| 150 |
} |
| 151 |
|
| 152 |
// Then do canonical decoding with the bits in MSB-first order. |
| 153 |
let read_bits2 = u64::from(HUFFMAN_LOOKUP_TABLE_BITS).min(length - is.position_in_bits()?); |
| 154 |
let mut bits = reverse_lsb( |
| 155 |
(lookup_bits | ((!is.read_var::<u8>(read_bits2 as u32)? as usize) << read_bits1)) |
| 156 |
as u16, |
| 157 |
MAX_HUFFMAN_BITS, |
| 158 |
); |
| 159 |
|
| 160 |
for l in (HUFFMAN_LOOKUP_TABLE_BITS as usize + 1)..=MAX_HUFFMAN_BITS { |
| 161 |
if u32::from(bits) < self.sentinel_bits[l] { |
| 162 |
bits >>= MAX_HUFFMAN_BITS - l; |
| 163 |
let sym_idx = (self.offset_first_sym_idx[l] as usize + bits as usize) & 0xFFFF; |
| 164 |
//assert(sym_idx < self.num_syms); |
| 165 |
is.seek_bits(io::SeekFrom::Current( |
| 166 |
-(read_bits1 as i64 + read_bits2 as i64) + l as i64, |
| 167 |
))?; |
| 168 |
return Ok(self.syms[sym_idx]); |
| 169 |
} |
| 170 |
} |
| 171 |
Err(Error::new( |
| 172 |
io::ErrorKind::InvalidData, |
| 173 |
"huffman decode failed", |
| 174 |
)) |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
#[cfg(test)] |
| 179 |
mod tests { |
| 180 |
use std::io::Cursor; |
| 181 |
|
| 182 |
use bitstream_io::{BitReader, LittleEndian}; |
| 183 |
|
| 184 |
use super::HuffmanDecoder; |
| 185 |
#[test] |
| 186 |
fn test_huffman_decode_basic() { |
| 187 |
let lens = [ |
| 188 |
3, // sym 0: 000 |
| 189 |
3, // sym 1: 001 |
| 190 |
3, // sym 2: 010 |
| 191 |
3, // sym 3: 011 |
| 192 |
3, // sym 4: 100 |
| 193 |
3, // sym 5: 101 |
| 194 |
4, // sym 6: 1100 |
| 195 |
4, // sym 7: 1101 |
| 196 |
0, // sym 8: |
| 197 |
0, // sym 9: |
| 198 |
0, // sym 10: |
| 199 |
0, // sym 11: |
| 200 |
0, // sym 12: |
| 201 |
0, // sym 13: |
| 202 |
0, // sym 14: |
| 203 |
0, // sym 15: |
| 204 |
6, // sym 16: 111110 |
| 205 |
5, // sym 17: 11110 |
| 206 |
4, // sym 18: 1110 |
| 207 |
]; |
| 208 |
|
| 209 |
let mut d = HuffmanDecoder::default(); |
| 210 |
d.init(&lens, lens.len()).unwrap(); |
| 211 |
|
| 212 |
// 000 (msb-first) -> 000 (lsb-first) |
| 213 |
assert_eq!( |
| 214 |
d.huffman_decode( |
| 215 |
8, |
| 216 |
&mut BitReader::endian(&mut Cursor::new(&[!0x0]), LittleEndian) |
| 217 |
) |
| 218 |
.unwrap(), |
| 219 |
0 |
| 220 |
); |
| 221 |
|
| 222 |
/* 011 (msb-first) -> 110 (lsb-first)*/ |
| 223 |
assert_eq!( |
| 224 |
d.huffman_decode( |
| 225 |
8, |
| 226 |
&mut BitReader::endian(&mut Cursor::new(&[!0b110]), LittleEndian) |
| 227 |
) |
| 228 |
.unwrap(), |
| 229 |
0b011 |
| 230 |
); |
| 231 |
|
| 232 |
/* 11110 (msb-first) -> 01111 (lsb-first)*/ |
| 233 |
assert_eq!( |
| 234 |
d.huffman_decode( |
| 235 |
8, |
| 236 |
&mut BitReader::endian(&mut Cursor::new(&[!0b1111]), LittleEndian) |
| 237 |
) |
| 238 |
.unwrap(), |
| 239 |
0b10001 |
| 240 |
); |
| 241 |
|
| 242 |
/* 111110 (msb-first) -> 011111 (lsb-first)*/ |
| 243 |
assert_eq!( |
| 244 |
d.huffman_decode( |
| 245 |
8, |
| 246 |
&mut BitReader::endian(&mut Cursor::new(&[!0b11111]), LittleEndian) |
| 247 |
) |
| 248 |
.unwrap(), |
| 249 |
0b10000 |
| 250 |
); |
| 251 |
|
| 252 |
/* 1111111 (msb-first) -> 1111111 (lsb-first)*/ |
| 253 |
assert!( |
| 254 |
d.huffman_decode( |
| 255 |
8, |
| 256 |
&mut BitReader::endian(&mut Cursor::new(&[!0x7f]), LittleEndian) |
| 257 |
) |
| 258 |
.is_err() |
| 259 |
); |
| 260 |
} |
| 261 |
} |