]> git.sesse.net Git - fjl/blob - dehuff.h
d93e7931ee17f081e734e7ff5397dd2f973f200d
[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 "input.h"
9
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;
15
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);
20
21 struct huffman_table {
22         unsigned num_codes[17];     // BITS
23         unsigned char codes[256];   // HUFFVAL
24         
25         // Derived values.
26         unsigned huffsize[256];
27         unsigned huffcode[256];
28         int maxcode[16];
29         int mincode[16];
30         unsigned valptr[16];
31
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.
35
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]; 
40 };
41
42 enum coefficient_class {
43         DC_CLASS = 0,
44         AC_CLASS,
45         NUM_COEFF_CLASSES
46 };
47 typedef struct huffman_table huffman_tables_t[NUM_COEFF_CLASSES][4];
48
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);
51
52 unsigned read_huffman_symbol_slow_path(const struct huffman_table* table,
53                                        struct bit_source* source);
54
55 #include <stdio.h>
56
57 static inline unsigned read_huffman_symbol(const struct huffman_table* table,
58                                            struct bit_source* source)
59 {
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];
66
67         if (code == DEHUF_SLOW_PATH) {
68                 return read_huffman_symbol_slow_path(table, source);
69         }
70
71         read_bits(source, length);
72         return code;
73 }
74
75 #endif /* !defined(_DEHUFF_H) */