nx_huffman.nx
buildroot/runtime/nx_huffman.nx
about
nx_huffman.nx -- canonical Huffman decoder.
Composes against nx_bitstream. Used by:
- DEFLATE (RFC 1951) -- literal/length + distance trees
- JPEG -- DHT segments (DC + AC coefficient tables)
- MP3 / AAC / Vorbis / Opus -- spectral coefficient codes
- brotli -- many sub-tables
- FLAC -- Rice partitions (not strictly Huffman; close family)
Canonical Huffman is the convention where:
- codes are assigned ONLY by their length sequence
- shortest codes first; within a length, in symbol order
- given just an array of (length per symbol), the decoder
can reconstruct the tree
Build algorithm (RFC 1951 section 3.2.2):
1. count[L] = number of symbols with length L
2. first_code[L] = (first_code[L-1] + count[L-1]) << 1
3. sort symbols by (length, symbol index) -> symbol_table
4. first_symbol[L] = cumulative count of lengths < L
Decode algorithm:
- read bits MSB-first into accumulator
- for L = 1..max_length:
if accumulator < first_code[L] + count[L]:
idx = accumulator - first_code[L]
return symbol_table[first_symbol[L] + idx]
else:
shift accumulator left by 1, read next bit, OR in
- return -1 (invalid bitstream)
genealogy_id: rfc1951_canonical_huffman_1996
lineage_id: nx_huffman_v1
dependencies 4 imports · 8 importers
imports: nx_syscalls.nxnx_runtime.nxnx_tier.nxnx_bitstream.nx
imported by: nx_deflate.nxnx_huffman_kat.nxnx_jpeg_decoder.nxnx_webp.nxnx_webp_huff.nxnx_webp_huff_gate.nxnx_webp_vp8l.nxnx_webp_vp8l_gate.nx
call flow from main pre-order; caps 40 nodes / depth 6 declared; ↻ = already shown
structs
| 53 | struct NxHuffmanTable |
consts
| 48 | const NX_HUFF_MAX_SYMBOLS: nx_int = 65536 // covers DEFLATE 288 + JPEG 256 + most use cases |
| 49 | const NX_HUFF_MAX_LENGTH: nx_int = 32 |
| 62 | const NX_HUFF_TABLE_BYTES: nx_size = 56 |
functions
| 69 | func nx_huffman_build(code_lengths: *nx_int, n_symbols: nx_int) -> *NxHuffmanTable |
| 157 | func nx_huffman_decode_msb(t: *NxHuffmanTable, bs: *NxBitStream) -> nx_int |
| 185 | func _huff_reverse_bits(v: nx_int, n: nx_int) -> nx_int called by 1: main |
| 198 | func nx_huffman_decode_lsb(t: *NxHuffmanTable, bs: *NxBitStream) -> nx_int |
| 221 | func main() -> nx_int |