xref: /aosp_15_r20/external/webp/src/utils/huffman_utils.c (revision b2055c353e87c8814eb2b6b1b11112a1562253bd)
1*b2055c35SXin Li // Copyright 2012 Google Inc. All Rights Reserved.
2*b2055c35SXin Li //
3*b2055c35SXin Li // Use of this source code is governed by a BSD-style license
4*b2055c35SXin Li // that can be found in the COPYING file in the root of the source
5*b2055c35SXin Li // tree. An additional intellectual property rights grant can be found
6*b2055c35SXin Li // in the file PATENTS. All contributing project authors may
7*b2055c35SXin Li // be found in the AUTHORS file in the root of the source tree.
8*b2055c35SXin Li // -----------------------------------------------------------------------------
9*b2055c35SXin Li //
10*b2055c35SXin Li // Utilities for building and looking up Huffman trees.
11*b2055c35SXin Li //
12*b2055c35SXin Li // Author: Urvang Joshi ([email protected])
13*b2055c35SXin Li 
14*b2055c35SXin Li #include <assert.h>
15*b2055c35SXin Li #include <stdlib.h>
16*b2055c35SXin Li #include <string.h>
17*b2055c35SXin Li #include "src/utils/huffman_utils.h"
18*b2055c35SXin Li #include "src/utils/utils.h"
19*b2055c35SXin Li #include "src/webp/format_constants.h"
20*b2055c35SXin Li 
21*b2055c35SXin Li // Huffman data read via DecodeImageStream is represented in two (red and green)
22*b2055c35SXin Li // bytes.
23*b2055c35SXin Li #define MAX_HTREE_GROUPS    0x10000
24*b2055c35SXin Li 
VP8LHtreeGroupsNew(int num_htree_groups)25*b2055c35SXin Li HTreeGroup* VP8LHtreeGroupsNew(int num_htree_groups) {
26*b2055c35SXin Li   HTreeGroup* const htree_groups =
27*b2055c35SXin Li       (HTreeGroup*)WebPSafeMalloc(num_htree_groups, sizeof(*htree_groups));
28*b2055c35SXin Li   if (htree_groups == NULL) {
29*b2055c35SXin Li     return NULL;
30*b2055c35SXin Li   }
31*b2055c35SXin Li   assert(num_htree_groups <= MAX_HTREE_GROUPS);
32*b2055c35SXin Li   return htree_groups;
33*b2055c35SXin Li }
34*b2055c35SXin Li 
VP8LHtreeGroupsFree(HTreeGroup * const htree_groups)35*b2055c35SXin Li void VP8LHtreeGroupsFree(HTreeGroup* const htree_groups) {
36*b2055c35SXin Li   if (htree_groups != NULL) {
37*b2055c35SXin Li     WebPSafeFree(htree_groups);
38*b2055c35SXin Li   }
39*b2055c35SXin Li }
40*b2055c35SXin Li 
41*b2055c35SXin Li // Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the
42*b2055c35SXin Li // bit-wise reversal of the len least significant bits of key.
GetNextKey(uint32_t key,int len)43*b2055c35SXin Li static WEBP_INLINE uint32_t GetNextKey(uint32_t key, int len) {
44*b2055c35SXin Li   uint32_t step = 1 << (len - 1);
45*b2055c35SXin Li   while (key & step) {
46*b2055c35SXin Li     step >>= 1;
47*b2055c35SXin Li   }
48*b2055c35SXin Li   return step ? (key & (step - 1)) + step : key;
49*b2055c35SXin Li }
50*b2055c35SXin Li 
51*b2055c35SXin Li // Stores code in table[0], table[step], table[2*step], ..., table[end].
52*b2055c35SXin Li // Assumes that end is an integer multiple of step.
ReplicateValue(HuffmanCode * table,int step,int end,HuffmanCode code)53*b2055c35SXin Li static WEBP_INLINE void ReplicateValue(HuffmanCode* table,
54*b2055c35SXin Li                                        int step, int end,
55*b2055c35SXin Li                                        HuffmanCode code) {
56*b2055c35SXin Li   assert(end % step == 0);
57*b2055c35SXin Li   do {
58*b2055c35SXin Li     end -= step;
59*b2055c35SXin Li     table[end] = code;
60*b2055c35SXin Li   } while (end > 0);
61*b2055c35SXin Li }
62*b2055c35SXin Li 
63*b2055c35SXin Li // Returns the table width of the next 2nd level table. count is the histogram
64*b2055c35SXin Li // of bit lengths for the remaining symbols, len is the code length of the next
65*b2055c35SXin Li // processed symbol
NextTableBitSize(const int * const count,int len,int root_bits)66*b2055c35SXin Li static WEBP_INLINE int NextTableBitSize(const int* const count,
67*b2055c35SXin Li                                         int len, int root_bits) {
68*b2055c35SXin Li   int left = 1 << (len - root_bits);
69*b2055c35SXin Li   while (len < MAX_ALLOWED_CODE_LENGTH) {
70*b2055c35SXin Li     left -= count[len];
71*b2055c35SXin Li     if (left <= 0) break;
72*b2055c35SXin Li     ++len;
73*b2055c35SXin Li     left <<= 1;
74*b2055c35SXin Li   }
75*b2055c35SXin Li   return len - root_bits;
76*b2055c35SXin Li }
77*b2055c35SXin Li 
78*b2055c35SXin Li // sorted[code_lengths_size] is a pre-allocated array for sorting symbols
79*b2055c35SXin Li // by code length.
BuildHuffmanTable(HuffmanCode * const root_table,int root_bits,const int code_lengths[],int code_lengths_size,uint16_t sorted[])80*b2055c35SXin Li static int BuildHuffmanTable(HuffmanCode* const root_table, int root_bits,
81*b2055c35SXin Li                              const int code_lengths[], int code_lengths_size,
82*b2055c35SXin Li                              uint16_t sorted[]) {
83*b2055c35SXin Li   HuffmanCode* table = root_table;  // next available space in table
84*b2055c35SXin Li   int total_size = 1 << root_bits;  // total size root table + 2nd level table
85*b2055c35SXin Li   int len;                          // current code length
86*b2055c35SXin Li   int symbol;                       // symbol index in original or sorted table
87*b2055c35SXin Li   // number of codes of each length:
88*b2055c35SXin Li   int count[MAX_ALLOWED_CODE_LENGTH + 1] = { 0 };
89*b2055c35SXin Li   // offsets in sorted table for each length:
90*b2055c35SXin Li   int offset[MAX_ALLOWED_CODE_LENGTH + 1];
91*b2055c35SXin Li 
92*b2055c35SXin Li   assert(code_lengths_size != 0);
93*b2055c35SXin Li   assert(code_lengths != NULL);
94*b2055c35SXin Li   assert((root_table != NULL && sorted != NULL) ||
95*b2055c35SXin Li          (root_table == NULL && sorted == NULL));
96*b2055c35SXin Li   assert(root_bits > 0);
97*b2055c35SXin Li 
98*b2055c35SXin Li   // Build histogram of code lengths.
99*b2055c35SXin Li   for (symbol = 0; symbol < code_lengths_size; ++symbol) {
100*b2055c35SXin Li     if (code_lengths[symbol] > MAX_ALLOWED_CODE_LENGTH) {
101*b2055c35SXin Li       return 0;
102*b2055c35SXin Li     }
103*b2055c35SXin Li     ++count[code_lengths[symbol]];
104*b2055c35SXin Li   }
105*b2055c35SXin Li 
106*b2055c35SXin Li   // Error, all code lengths are zeros.
107*b2055c35SXin Li   if (count[0] == code_lengths_size) {
108*b2055c35SXin Li     return 0;
109*b2055c35SXin Li   }
110*b2055c35SXin Li 
111*b2055c35SXin Li   // Generate offsets into sorted symbol table by code length.
112*b2055c35SXin Li   offset[1] = 0;
113*b2055c35SXin Li   for (len = 1; len < MAX_ALLOWED_CODE_LENGTH; ++len) {
114*b2055c35SXin Li     if (count[len] > (1 << len)) {
115*b2055c35SXin Li       return 0;
116*b2055c35SXin Li     }
117*b2055c35SXin Li     offset[len + 1] = offset[len] + count[len];
118*b2055c35SXin Li   }
119*b2055c35SXin Li 
120*b2055c35SXin Li   // Sort symbols by length, by symbol order within each length.
121*b2055c35SXin Li   for (symbol = 0; symbol < code_lengths_size; ++symbol) {
122*b2055c35SXin Li     const int symbol_code_length = code_lengths[symbol];
123*b2055c35SXin Li     if (code_lengths[symbol] > 0) {
124*b2055c35SXin Li       if (sorted != NULL) {
125*b2055c35SXin Li         if(offset[symbol_code_length] >= code_lengths_size) {
126*b2055c35SXin Li             return 0;
127*b2055c35SXin Li         }
128*b2055c35SXin Li         sorted[offset[symbol_code_length]++] = symbol;
129*b2055c35SXin Li       } else {
130*b2055c35SXin Li         offset[symbol_code_length]++;
131*b2055c35SXin Li       }
132*b2055c35SXin Li     }
133*b2055c35SXin Li   }
134*b2055c35SXin Li 
135*b2055c35SXin Li   // Special case code with only one value.
136*b2055c35SXin Li   if (offset[MAX_ALLOWED_CODE_LENGTH] == 1) {
137*b2055c35SXin Li     if (sorted != NULL) {
138*b2055c35SXin Li       HuffmanCode code;
139*b2055c35SXin Li       code.bits = 0;
140*b2055c35SXin Li       code.value = (uint16_t)sorted[0];
141*b2055c35SXin Li       ReplicateValue(table, 1, total_size, code);
142*b2055c35SXin Li     }
143*b2055c35SXin Li     return total_size;
144*b2055c35SXin Li   }
145*b2055c35SXin Li 
146*b2055c35SXin Li   {
147*b2055c35SXin Li     int step;              // step size to replicate values in current table
148*b2055c35SXin Li     uint32_t low = 0xffffffffu;        // low bits for current root entry
149*b2055c35SXin Li     uint32_t mask = total_size - 1;    // mask for low bits
150*b2055c35SXin Li     uint32_t key = 0;      // reversed prefix code
151*b2055c35SXin Li     int num_nodes = 1;     // number of Huffman tree nodes
152*b2055c35SXin Li     int num_open = 1;      // number of open branches in current tree level
153*b2055c35SXin Li     int table_bits = root_bits;        // key length of current table
154*b2055c35SXin Li     int table_size = 1 << table_bits;  // size of current table
155*b2055c35SXin Li     symbol = 0;
156*b2055c35SXin Li     // Fill in root table.
157*b2055c35SXin Li     for (len = 1, step = 2; len <= root_bits; ++len, step <<= 1) {
158*b2055c35SXin Li       num_open <<= 1;
159*b2055c35SXin Li       num_nodes += num_open;
160*b2055c35SXin Li       num_open -= count[len];
161*b2055c35SXin Li       if (num_open < 0) {
162*b2055c35SXin Li         return 0;
163*b2055c35SXin Li       }
164*b2055c35SXin Li       if (root_table == NULL) continue;
165*b2055c35SXin Li       for (; count[len] > 0; --count[len]) {
166*b2055c35SXin Li         HuffmanCode code;
167*b2055c35SXin Li         code.bits = (uint8_t)len;
168*b2055c35SXin Li         code.value = (uint16_t)sorted[symbol++];
169*b2055c35SXin Li         ReplicateValue(&table[key], step, table_size, code);
170*b2055c35SXin Li         key = GetNextKey(key, len);
171*b2055c35SXin Li       }
172*b2055c35SXin Li     }
173*b2055c35SXin Li 
174*b2055c35SXin Li     // Fill in 2nd level tables and add pointers to root table.
175*b2055c35SXin Li     for (len = root_bits + 1, step = 2; len <= MAX_ALLOWED_CODE_LENGTH;
176*b2055c35SXin Li          ++len, step <<= 1) {
177*b2055c35SXin Li       num_open <<= 1;
178*b2055c35SXin Li       num_nodes += num_open;
179*b2055c35SXin Li       num_open -= count[len];
180*b2055c35SXin Li       if (num_open < 0) {
181*b2055c35SXin Li         return 0;
182*b2055c35SXin Li       }
183*b2055c35SXin Li       for (; count[len] > 0; --count[len]) {
184*b2055c35SXin Li         HuffmanCode code;
185*b2055c35SXin Li         if ((key & mask) != low) {
186*b2055c35SXin Li           if (root_table != NULL) table += table_size;
187*b2055c35SXin Li           table_bits = NextTableBitSize(count, len, root_bits);
188*b2055c35SXin Li           table_size = 1 << table_bits;
189*b2055c35SXin Li           total_size += table_size;
190*b2055c35SXin Li           low = key & mask;
191*b2055c35SXin Li           if (root_table != NULL) {
192*b2055c35SXin Li             root_table[low].bits = (uint8_t)(table_bits + root_bits);
193*b2055c35SXin Li             root_table[low].value = (uint16_t)((table - root_table) - low);
194*b2055c35SXin Li           }
195*b2055c35SXin Li         }
196*b2055c35SXin Li         if (root_table != NULL) {
197*b2055c35SXin Li           code.bits = (uint8_t)(len - root_bits);
198*b2055c35SXin Li           code.value = (uint16_t)sorted[symbol++];
199*b2055c35SXin Li           ReplicateValue(&table[key >> root_bits], step, table_size, code);
200*b2055c35SXin Li         }
201*b2055c35SXin Li         key = GetNextKey(key, len);
202*b2055c35SXin Li       }
203*b2055c35SXin Li     }
204*b2055c35SXin Li 
205*b2055c35SXin Li     // Check if tree is full.
206*b2055c35SXin Li     if (num_nodes != 2 * offset[MAX_ALLOWED_CODE_LENGTH] - 1) {
207*b2055c35SXin Li       return 0;
208*b2055c35SXin Li     }
209*b2055c35SXin Li   }
210*b2055c35SXin Li 
211*b2055c35SXin Li   return total_size;
212*b2055c35SXin Li }
213*b2055c35SXin Li 
214*b2055c35SXin Li // Maximum code_lengths_size is 2328 (reached for 11-bit color_cache_bits).
215*b2055c35SXin Li // More commonly, the value is around ~280.
216*b2055c35SXin Li #define MAX_CODE_LENGTHS_SIZE \
217*b2055c35SXin Li   ((1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES)
218*b2055c35SXin Li // Cut-off value for switching between heap and stack allocation.
219*b2055c35SXin Li #define SORTED_SIZE_CUTOFF 512
VP8LBuildHuffmanTable(HuffmanTables * const root_table,int root_bits,const int code_lengths[],int code_lengths_size)220*b2055c35SXin Li int VP8LBuildHuffmanTable(HuffmanTables* const root_table, int root_bits,
221*b2055c35SXin Li                           const int code_lengths[], int code_lengths_size) {
222*b2055c35SXin Li   const int total_size =
223*b2055c35SXin Li       BuildHuffmanTable(NULL, root_bits, code_lengths, code_lengths_size, NULL);
224*b2055c35SXin Li   assert(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);
225*b2055c35SXin Li   if (total_size == 0 || root_table == NULL) return total_size;
226*b2055c35SXin Li 
227*b2055c35SXin Li   if (root_table->curr_segment->curr_table + total_size >=
228*b2055c35SXin Li       root_table->curr_segment->start + root_table->curr_segment->size) {
229*b2055c35SXin Li     // If 'root_table' does not have enough memory, allocate a new segment.
230*b2055c35SXin Li     // The available part of root_table->curr_segment is left unused because we
231*b2055c35SXin Li     // need a contiguous buffer.
232*b2055c35SXin Li     const int segment_size = root_table->curr_segment->size;
233*b2055c35SXin Li     struct HuffmanTablesSegment* next =
234*b2055c35SXin Li         (HuffmanTablesSegment*)WebPSafeMalloc(1, sizeof(*next));
235*b2055c35SXin Li     if (next == NULL) return 0;
236*b2055c35SXin Li     // Fill the new segment.
237*b2055c35SXin Li     // We need at least 'total_size' but if that value is small, it is better to
238*b2055c35SXin Li     // allocate a big chunk to prevent more allocations later. 'segment_size' is
239*b2055c35SXin Li     // therefore chosen (any other arbitrary value could be chosen).
240*b2055c35SXin Li     next->size = total_size > segment_size ? total_size : segment_size;
241*b2055c35SXin Li     next->start =
242*b2055c35SXin Li         (HuffmanCode*)WebPSafeMalloc(next->size, sizeof(*next->start));
243*b2055c35SXin Li     if (next->start == NULL) {
244*b2055c35SXin Li       WebPSafeFree(next);
245*b2055c35SXin Li       return 0;
246*b2055c35SXin Li     }
247*b2055c35SXin Li     next->curr_table = next->start;
248*b2055c35SXin Li     next->next = NULL;
249*b2055c35SXin Li     // Point to the new segment.
250*b2055c35SXin Li     root_table->curr_segment->next = next;
251*b2055c35SXin Li     root_table->curr_segment = next;
252*b2055c35SXin Li   }
253*b2055c35SXin Li   if (code_lengths_size <= SORTED_SIZE_CUTOFF) {
254*b2055c35SXin Li     // use local stack-allocated array.
255*b2055c35SXin Li     uint16_t sorted[SORTED_SIZE_CUTOFF];
256*b2055c35SXin Li     BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,
257*b2055c35SXin Li                       code_lengths, code_lengths_size, sorted);
258*b2055c35SXin Li   } else {  // rare case. Use heap allocation.
259*b2055c35SXin Li     uint16_t* const sorted =
260*b2055c35SXin Li         (uint16_t*)WebPSafeMalloc(code_lengths_size, sizeof(*sorted));
261*b2055c35SXin Li     if (sorted == NULL) return 0;
262*b2055c35SXin Li     BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,
263*b2055c35SXin Li                       code_lengths, code_lengths_size, sorted);
264*b2055c35SXin Li     WebPSafeFree(sorted);
265*b2055c35SXin Li   }
266*b2055c35SXin Li   return total_size;
267*b2055c35SXin Li }
268*b2055c35SXin Li 
VP8LHuffmanTablesAllocate(int size,HuffmanTables * huffman_tables)269*b2055c35SXin Li int VP8LHuffmanTablesAllocate(int size, HuffmanTables* huffman_tables) {
270*b2055c35SXin Li   // Have 'segment' point to the first segment for now, 'root'.
271*b2055c35SXin Li   HuffmanTablesSegment* const root = &huffman_tables->root;
272*b2055c35SXin Li   huffman_tables->curr_segment = root;
273*b2055c35SXin Li   root->next = NULL;
274*b2055c35SXin Li   // Allocate root.
275*b2055c35SXin Li   root->start = (HuffmanCode*)WebPSafeMalloc(size, sizeof(*root->start));
276*b2055c35SXin Li   if (root->start == NULL) return 0;
277*b2055c35SXin Li   root->curr_table = root->start;
278*b2055c35SXin Li   root->size = size;
279*b2055c35SXin Li   return 1;
280*b2055c35SXin Li }
281*b2055c35SXin Li 
VP8LHuffmanTablesDeallocate(HuffmanTables * const huffman_tables)282*b2055c35SXin Li void VP8LHuffmanTablesDeallocate(HuffmanTables* const huffman_tables) {
283*b2055c35SXin Li   HuffmanTablesSegment *current, *next;
284*b2055c35SXin Li   if (huffman_tables == NULL) return;
285*b2055c35SXin Li   // Free the root node.
286*b2055c35SXin Li   current = &huffman_tables->root;
287*b2055c35SXin Li   next = current->next;
288*b2055c35SXin Li   WebPSafeFree(current->start);
289*b2055c35SXin Li   current->start = NULL;
290*b2055c35SXin Li   current->next = NULL;
291*b2055c35SXin Li   current = next;
292*b2055c35SXin Li   // Free the following nodes.
293*b2055c35SXin Li   while (current != NULL) {
294*b2055c35SXin Li     next = current->next;
295*b2055c35SXin Li     WebPSafeFree(current->start);
296*b2055c35SXin Li     WebPSafeFree(current);
297*b2055c35SXin Li     current = next;
298*b2055c35SXin Li   }
299*b2055c35SXin Li }
300