8 #include "bytesource.h"
11 // About 99% of all Huffman codes are <= 8 bits long (see codelen.txt),
12 // and it's what libjpeg uses. Thus, it seems like a reasonable size.
13 #define DEHUF_TABLE_BITS 8
14 #define DEHUF_TABLE_SIZE (1 << DEHUF_TABLE_BITS)
15 static const int DEHUF_SLOW_PATH = -1;
17 struct huffman_table {
18 unsigned num_codes[17]; // BITS
19 unsigned char codes[256]; // HUFFVAL
22 unsigned huffsize[256];
23 unsigned huffcode[256];
28 // Lookup table for fast decoding; given eight bits,
29 // return the symbol and length in bits. For longer codes,
30 // DEHUF_SLOW_PATH is returned.
32 // Note that the codes we return are 8-bit, but the type of
33 // the lookup tables is int to avoid extra zero extending.
34 int lookup_table_codes[DEHUF_TABLE_SIZE];
35 int lookup_table_length[DEHUF_TABLE_SIZE];
38 enum coefficient_class {
43 typedef struct huffman_table huffman_tables_t[NUM_COEFF_CLASSES][4];
45 // Read Huffman tables from a stream, and compute the derived values.
46 void read_huffman_tables(huffman_tables_t* dst, input_func_t* input_func, void* userdata);
48 unsigned read_huffman_symbol_slow_path(const struct huffman_table* table,
49 struct bit_source* source);
51 static inline unsigned read_huffman_symbol(const struct huffman_table* table,
52 struct bit_source* source)
54 // FIXME: We can read past the end of the stream here in some edge
55 // cases. We need to define some guarantees in the layers above.
56 possibly_refill(source, DEHUF_TABLE_BITS);
57 unsigned lookup = peek_bits(source, DEHUF_TABLE_BITS);
58 int code = table->lookup_table_codes[lookup];
59 int length = table->lookup_table_length[lookup];
61 if (code == DEHUF_SLOW_PATH) {
62 return read_huffman_symbol_slow_path(table, source);
65 read_bits(source, length);
69 // procedure EXTEND (figure F.12)
71 // Fast lookup table for (1 << (bits - 1)).
72 // The table actually helps, since the load can go in parallel with the shift
74 static const int bit_thresholds[16] = {
75 0, 1 << 0, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12, 1 << 13, 1 << 14, 1 << 15
78 static inline unsigned extend(int val, int bits)
80 if (val < bit_thresholds[bits]) {
81 return val + (-1 << bits) + 1;
87 #endif /* !defined(_DEHUFF_H) */