7 struct custom_read_userdata {
12 ssize_t custom_read(void* userdata, uint8_t* buf, size_t count)
14 struct custom_read_userdata* ud = (struct custom_read_userdata*)userdata;
15 size_t num_to_read = (ud->bytes_left > count ? count : ud->bytes_left);
16 memcpy(buf, ud->bytes, num_to_read);
17 ud->bytes += num_to_read;
18 ud->bytes_left -= num_to_read;
22 // The example from section K.3.1 from the JPEG standard.
23 uint8_t example_table_bytes[] = {
24 // Chunk length: Chunk length (2) + coefficient class (1) +
25 // code lengths (16) + code words (12)
28 // DC coefficient, table 0
31 // List of code lengths
32 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
35 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
38 void read_example_tables(huffman_tables_t* tables)
40 struct custom_read_userdata ud;
41 ud.bytes = example_table_bytes;
42 ud.bytes_left = sizeof(example_table_bytes);
44 read_huffman_tables(tables, custom_read, &ud);
47 // Test that the generated code tables are what we expect.
50 huffman_tables_t tables;
51 read_example_tables(&tables);
53 // Expected results (table K.3)
57 } expected_table[12] = {
72 struct huffman_table* tbl = &tables[DC_CLASS][0];
73 for (unsigned i = 0; i < 12; ++i) {
74 assert(tbl->huffsize[i] == expected_table[i].code_length);
75 assert(tbl->huffcode[i] == expected_table[i].code_word);
79 // Test that we can decode a simple bit stream.
80 // Note that since we end on a long code, we won't crash into
81 // the end-of-stream problems we currently have.
84 huffman_tables_t tables;
85 read_example_tables(&tables);
87 // Our stream looks like this:
89 // 0 1 2 3 4 5 6 7 8 9 10 11
90 // 00 010 011 100 101 110 1110 11110 111110 1111110 11111110 111111110
92 0x13, 0x97, 0x77, 0xbe, 0xfd, 0xfd, 0xfe
95 struct custom_read_userdata ud;
97 ud.bytes_left = sizeof(bytes);
99 struct bit_source source;
100 init_bit_source(&source, custom_read, &ud);
102 struct huffman_table* tbl = &tables[DC_CLASS][0];
103 for (unsigned i = 0; i < 12; ++i) {
104 unsigned symbol = read_huffman_symbol(tbl, &source);
108 assert(source.bits_available == 0);
113 printf("test_table_gen()\n");
116 printf("test_decoding()\n");
119 printf("All tests pass.\n");