]> git.sesse.net Git - fjl/blob - dehuff.h
3d3d8c5b049b192bdb772355603c3ec4f92accc6
[fjl] / dehuff.h
1 #ifndef _DEHUFF_H
2 #define _DEHUFF_H 1
3
4 #include <stddef.h>
5 #include <stdint.h>
6 #include <sys/types.h>
7
8 #include "bytesource.h"
9 #include "input.h"
10
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;
16
17 struct huffman_table {
18         unsigned num_codes[17];     // BITS
19         unsigned char codes[256];   // HUFFVAL
20         
21         // Derived values.
22         unsigned huffsize[256];
23         unsigned huffcode[256];
24         int maxcode[16];
25         int mincode[16];
26         unsigned valptr[16];
27
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.
31
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]; 
36 };
37
38 enum coefficient_class {
39         DC_CLASS = 0,
40         AC_CLASS,
41         NUM_COEFF_CLASSES
42 };
43 typedef struct huffman_table huffman_tables_t[NUM_COEFF_CLASSES][4];
44
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);
47
48 unsigned read_huffman_symbol_slow_path(const struct huffman_table* table,
49                                        struct bit_source* source);
50
51 static inline unsigned read_huffman_symbol(const struct huffman_table* table,
52                                            struct bit_source* source)
53 {
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];
60
61         if (code == DEHUF_SLOW_PATH) {
62                 return read_huffman_symbol_slow_path(table, source);
63         }
64
65         read_bits(source, length);
66         return code;
67 }
68
69 #endif /* !defined(_DEHUFF_H) */