Coverage Report

Created: 2024-06-18 06:09

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