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_no_refill(
52 const struct huffman_table* table,
53 struct bit_source* source)
55 assert(source->bits_available >= DEHUF_TABLE_BITS);
56 unsigned lookup = peek_bits(source, DEHUF_TABLE_BITS);
57 int code = table->lookup_table_codes[lookup];
58 int length = table->lookup_table_length[lookup];
60 if (code == DEHUF_SLOW_PATH) {
61 return read_huffman_symbol_slow_path(table, source);
64 read_bits(source, length);
68 static inline unsigned read_huffman_symbol(const struct huffman_table* table,
69 struct bit_source* source)
71 possibly_refill(source, DEHUF_TABLE_BITS);
72 return read_huffman_symbol_no_refill(table, source);
75 // procedure EXTEND (figure F.12)
77 // Fast lookup table for (1 << (bits - 1)).
78 // The table actually helps, since the load can go in parallel with the shift
80 static const int bit_thresholds[16] = {
81 0, 1 << 0, 1 << 1, 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
84 static inline unsigned extend(int val, unsigned bits)
86 #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
87 // GCC should ideally be able to figure out that the conditional move is better, but
88 // it doesn't for various reasons, and this is pretty important for speed, so we hardcode.
89 asm("cmp %2, %0 ; cmovl %3, %0"
92 "g" (bit_thresholds[bits]),
93 "r" (val + (-1 << bits) + 1)
97 if (val < bit_thresholds[bits]) {
98 return val + (-1 << bits) + 1;
105 #endif /* !defined(_DEHUFF_H) */