10 // About 99% of all Huffman codes are <= 8 bits long (see codelen.txt),
11 // and it's what libjpeg uses. Thus, it seems like a reasonable size.
12 #define DEHUF_TABLE_BITS 8
13 #define DEHUF_TABLE_SIZE (1 << DEHUF_TABLE_BITS)
14 static const int DEHUF_SLOW_PATH = -1;
16 // A function to read bytes from some input source. The bytes should be
17 // already unstuffed (and thus without markers).
18 // A return value of -1 indicates error, a return value of 0 indicates EOF.
19 typedef ssize_t (raw_input_func_t)(void*, uint8_t*, size_t);
21 struct huffman_table {
22 unsigned num_codes[17]; // BITS
23 unsigned char codes[256]; // HUFFVAL
26 unsigned huffsize[256];
27 unsigned huffcode[256];
32 // Lookup table for fast decoding; given eight bits,
33 // return the symbol and length in bits. For longer codes,
34 // DEHUF_SLOW_PATH is returned.
36 // Note that the codes we return are 8-bit, but the type of
37 // the lookup tables is int to avoid extra zero extending.
38 int lookup_table_codes[DEHUF_TABLE_SIZE];
39 int lookup_table_length[DEHUF_TABLE_SIZE];
42 enum coefficient_class {
47 typedef struct huffman_table huffman_tables_t[NUM_COEFF_CLASSES][4];
49 // Read Huffman tables from a stream, and compute the derived values.
50 void read_huffman_tables(huffman_tables_t* dst, raw_input_func_t* input_func, void* userdata);
52 unsigned read_huffman_symbol_slow_path(const struct huffman_table* table,
53 struct bit_source* source);
57 static inline unsigned read_huffman_symbol(const struct huffman_table* table,
58 struct bit_source* source)
60 // FIXME: We can read past the end of the stream here in some edge
61 // cases. We need to define some guarantees in the layers above.
62 possibly_refill(source, DEHUF_TABLE_BITS);
63 unsigned lookup = peek_bits(source, DEHUF_TABLE_BITS);
64 int code = table->lookup_table_codes[lookup];
65 int length = table->lookup_table_length[lookup];
67 if (code == DEHUF_SLOW_PATH) {
68 return read_huffman_symbol_slow_path(table, source);
71 read_bits(source, length);
75 #endif /* !defined(_DEHUFF_H) */