huffman_utils.c 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2012 Google Inc. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the COPYING file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. // -----------------------------------------------------------------------------
  9. //
  10. // Utilities for building and looking up Huffman trees.
  11. //
  12. // Author: Urvang Joshi (urvang@google.com)
  13. #include <assert.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include "./huffman_utils.h"
  17. #include "./utils.h"
  18. #include "../webp/format_constants.h"
  19. // Huffman data read via DecodeImageStream is represented in two (red and green)
  20. // bytes.
  21. #define MAX_HTREE_GROUPS 0x10000
  22. HTreeGroup* VP8LHtreeGroupsNew(int num_htree_groups) {
  23. HTreeGroup* const htree_groups =
  24. (HTreeGroup*)WebPSafeMalloc(num_htree_groups, sizeof(*htree_groups));
  25. if (htree_groups == NULL) {
  26. return NULL;
  27. }
  28. assert(num_htree_groups <= MAX_HTREE_GROUPS);
  29. return htree_groups;
  30. }
  31. void VP8LHtreeGroupsFree(HTreeGroup* const htree_groups) {
  32. if (htree_groups != NULL) {
  33. WebPSafeFree(htree_groups);
  34. }
  35. }
  36. // Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the
  37. // bit-wise reversal of the len least significant bits of key.
  38. static WEBP_INLINE uint32_t GetNextKey(uint32_t key, int len) {
  39. uint32_t step = 1 << (len - 1);
  40. while (key & step) {
  41. step >>= 1;
  42. }
  43. return step ? (key & (step - 1)) + step : key;
  44. }
  45. // Stores code in table[0], table[step], table[2*step], ..., table[end].
  46. // Assumes that end is an integer multiple of step.
  47. static WEBP_INLINE void ReplicateValue(HuffmanCode* table,
  48. int step, int end,
  49. HuffmanCode code) {
  50. assert(end % step == 0);
  51. do {
  52. end -= step;
  53. table[end] = code;
  54. } while (end > 0);
  55. }
  56. // Returns the table width of the next 2nd level table. count is the histogram
  57. // of bit lengths for the remaining symbols, len is the code length of the next
  58. // processed symbol
  59. static WEBP_INLINE int NextTableBitSize(const int* const count,
  60. int len, int root_bits) {
  61. int left = 1 << (len - root_bits);
  62. while (len < MAX_ALLOWED_CODE_LENGTH) {
  63. left -= count[len];
  64. if (left <= 0) break;
  65. ++len;
  66. left <<= 1;
  67. }
  68. return len - root_bits;
  69. }
  70. // sorted[code_lengths_size] is a pre-allocated array for sorting symbols
  71. // by code length.
  72. static int BuildHuffmanTable(HuffmanCode* const root_table, int root_bits,
  73. const int code_lengths[], int code_lengths_size,
  74. uint16_t sorted[]) {
  75. HuffmanCode* table = root_table; // next available space in table
  76. int total_size = 1 << root_bits; // total size root table + 2nd level table
  77. int len; // current code length
  78. int symbol; // symbol index in original or sorted table
  79. // number of codes of each length:
  80. int count[MAX_ALLOWED_CODE_LENGTH + 1] = { 0 };
  81. // offsets in sorted table for each length:
  82. int offset[MAX_ALLOWED_CODE_LENGTH + 1];
  83. assert(code_lengths_size != 0);
  84. assert(code_lengths != NULL);
  85. assert((root_table != NULL && sorted != NULL) ||
  86. (root_table == NULL && sorted == NULL));
  87. assert(root_bits > 0);
  88. // Build histogram of code lengths.
  89. for (symbol = 0; symbol < code_lengths_size; ++symbol) {
  90. if (code_lengths[symbol] > MAX_ALLOWED_CODE_LENGTH) {
  91. return 0;
  92. }
  93. ++count[code_lengths[symbol]];
  94. }
  95. // Error, all code lengths are zeros.
  96. if (count[0] == code_lengths_size) {
  97. return 0;
  98. }
  99. // Generate offsets into sorted symbol table by code length.
  100. offset[1] = 0;
  101. for (len = 1; len < MAX_ALLOWED_CODE_LENGTH; ++len) {
  102. if (count[len] > (1 << len)) {
  103. return 0;
  104. }
  105. offset[len + 1] = offset[len] + count[len];
  106. }
  107. // Sort symbols by length, by symbol order within each length.
  108. for (symbol = 0; symbol < code_lengths_size; ++symbol) {
  109. const int symbol_code_length = code_lengths[symbol];
  110. if (code_lengths[symbol] > 0) {
  111. if (sorted != NULL) {
  112. sorted[offset[symbol_code_length]++] = symbol;
  113. } else {
  114. offset[symbol_code_length]++;
  115. }
  116. }
  117. }
  118. // Special case code with only one value.
  119. if (offset[MAX_ALLOWED_CODE_LENGTH] == 1) {
  120. if (sorted != NULL) {
  121. HuffmanCode code;
  122. code.bits = 0;
  123. code.value = (uint16_t)sorted[0];
  124. ReplicateValue(table, 1, total_size, code);
  125. }
  126. return total_size;
  127. }
  128. {
  129. int step; // step size to replicate values in current table
  130. uint32_t low = -1; // low bits for current root entry
  131. uint32_t mask = total_size - 1; // mask for low bits
  132. uint32_t key = 0; // reversed prefix code
  133. int num_nodes = 1; // number of Huffman tree nodes
  134. int num_open = 1; // number of open branches in current tree level
  135. int table_bits = root_bits; // key length of current table
  136. int table_size = 1 << table_bits; // size of current table
  137. symbol = 0;
  138. // Fill in root table.
  139. for (len = 1, step = 2; len <= root_bits; ++len, step <<= 1) {
  140. num_open <<= 1;
  141. num_nodes += num_open;
  142. num_open -= count[len];
  143. if (num_open < 0) {
  144. return 0;
  145. }
  146. if (root_table == NULL) continue;
  147. for (; count[len] > 0; --count[len]) {
  148. HuffmanCode code;
  149. code.bits = (uint8_t)len;
  150. code.value = (uint16_t)sorted[symbol++];
  151. ReplicateValue(&table[key], step, table_size, code);
  152. key = GetNextKey(key, len);
  153. }
  154. }
  155. // Fill in 2nd level tables and add pointers to root table.
  156. for (len = root_bits + 1, step = 2; len <= MAX_ALLOWED_CODE_LENGTH;
  157. ++len, step <<= 1) {
  158. num_open <<= 1;
  159. num_nodes += num_open;
  160. num_open -= count[len];
  161. if (num_open < 0) {
  162. return 0;
  163. }
  164. if (root_table == NULL) continue;
  165. for (; count[len] > 0; --count[len]) {
  166. HuffmanCode code;
  167. if ((key & mask) != low) {
  168. table += table_size;
  169. table_bits = NextTableBitSize(count, len, root_bits);
  170. table_size = 1 << table_bits;
  171. total_size += table_size;
  172. low = key & mask;
  173. root_table[low].bits = (uint8_t)(table_bits + root_bits);
  174. root_table[low].value = (uint16_t)((table - root_table) - low);
  175. }
  176. code.bits = (uint8_t)(len - root_bits);
  177. code.value = (uint16_t)sorted[symbol++];
  178. ReplicateValue(&table[key >> root_bits], step, table_size, code);
  179. key = GetNextKey(key, len);
  180. }
  181. }
  182. // Check if tree is full.
  183. if (num_nodes != 2 * offset[MAX_ALLOWED_CODE_LENGTH] - 1) {
  184. return 0;
  185. }
  186. }
  187. return total_size;
  188. }
  189. // Maximum code_lengths_size is 2328 (reached for 11-bit color_cache_bits).
  190. // More commonly, the value is around ~280.
  191. #define MAX_CODE_LENGTHS_SIZE \
  192. ((1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES)
  193. // Cut-off value for switching between heap and stack allocation.
  194. #define SORTED_SIZE_CUTOFF 512
  195. int VP8LBuildHuffmanTable(HuffmanCode* const root_table, int root_bits,
  196. const int code_lengths[], int code_lengths_size) {
  197. int total_size;
  198. assert(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);
  199. if (root_table == NULL) {
  200. total_size = BuildHuffmanTable(NULL, root_bits,
  201. code_lengths, code_lengths_size, NULL);
  202. } else if (code_lengths_size <= SORTED_SIZE_CUTOFF) {
  203. // use local stack-allocated array.
  204. uint16_t sorted[SORTED_SIZE_CUTOFF];
  205. total_size = BuildHuffmanTable(root_table, root_bits,
  206. code_lengths, code_lengths_size, sorted);
  207. } else { // rare case. Use heap allocation.
  208. uint16_t* const sorted =
  209. (uint16_t*)WebPSafeMalloc(code_lengths_size, sizeof(*sorted));
  210. if (sorted == NULL) return 0;
  211. total_size = BuildHuffmanTable(root_table, root_bits,
  212. code_lengths, code_lengths_size, sorted);
  213. WebPSafeFree(sorted);
  214. }
  215. return total_size;
  216. }