Coverage Report

Created: 2025-06-22 08:04

/src/libjxl/lib/jxl/dec_ans.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/dec_ans.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <cstdint>
11
#include <vector>
12
13
#include "lib/jxl/ans_common.h"
14
#include "lib/jxl/ans_params.h"
15
#include "lib/jxl/base/bits.h"
16
#include "lib/jxl/base/printf_macros.h"
17
#include "lib/jxl/base/status.h"
18
#include "lib/jxl/dec_context_map.h"
19
#include "lib/jxl/fields.h"
20
#include "lib/jxl/memory_manager_internal.h"
21
22
namespace jxl {
23
namespace {
24
25
// Decodes a number in the range [0..255], by reading 1 - 11 bits.
26
66.5k
inline int DecodeVarLenUint8(BitReader* input) {
27
66.5k
  if (input->ReadFixedBits<1>()) {
28
27.1k
    int nbits = static_cast<int>(input->ReadFixedBits<3>());
29
27.1k
    if (nbits == 0) {
30
2.55k
      return 1;
31
24.6k
    } else {
32
24.6k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
33
24.6k
    }
34
27.1k
  }
35
39.3k
  return 0;
36
66.5k
}
37
38
// Decodes a number in the range [0..65535], by reading 1 - 21 bits.
39
114k
inline int DecodeVarLenUint16(BitReader* input) {
40
114k
  if (input->ReadFixedBits<1>()) {
41
30.8k
    int nbits = static_cast<int>(input->ReadFixedBits<4>());
42
30.8k
    if (nbits == 0) {
43
693
      return 1;
44
30.1k
    } else {
45
30.1k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
46
30.1k
    }
47
30.8k
  }
48
83.3k
  return 0;
49
114k
}
50
51
Status ReadHistogram(int precision_bits, std::vector<int32_t>* counts,
52
59.4k
                     BitReader* input) {
53
59.4k
  int range = 1 << precision_bits;
54
59.4k
  int simple_code = input->ReadBits(1);
55
59.4k
  if (simple_code == 1) {
56
18.3k
    int i;
57
18.3k
    int symbols[2] = {0};
58
18.3k
    int max_symbol = 0;
59
18.3k
    const int num_symbols = input->ReadBits(1) + 1;
60
39.6k
    for (i = 0; i < num_symbols; ++i) {
61
21.3k
      symbols[i] = DecodeVarLenUint8(input);
62
21.3k
      if (symbols[i] > max_symbol) max_symbol = symbols[i];
63
21.3k
    }
64
18.3k
    counts->resize(max_symbol + 1);
65
18.3k
    if (num_symbols == 1) {
66
15.2k
      (*counts)[symbols[0]] = range;
67
15.2k
    } else {
68
3.04k
      if (symbols[0] == symbols[1]) {  // corrupt data
69
239
        return false;
70
239
      }
71
2.80k
      (*counts)[symbols[0]] = input->ReadBits(precision_bits);
72
2.80k
      (*counts)[symbols[1]] = range - (*counts)[symbols[0]];
73
2.80k
    }
74
41.1k
  } else {
75
41.1k
    int is_flat = input->ReadBits(1);
76
41.1k
    if (is_flat == 1) {
77
12.1k
      int alphabet_size = DecodeVarLenUint8(input) + 1;
78
12.1k
      JXL_ENSURE(alphabet_size <= range);
79
12.1k
      *counts = CreateFlatHistogram(alphabet_size, range);
80
12.1k
      return true;
81
12.1k
    }
82
83
29.0k
    uint32_t shift;
84
29.0k
    {
85
      // TODO(veluca): speed up reading with table lookups.
86
29.0k
      int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
87
29.0k
      int log = 0;
88
40.1k
      for (; log < upper_bound_log; log++) {
89
38.3k
        if (input->ReadFixedBits<1>() == 0) break;
90
38.3k
      }
91
29.0k
      shift = (input->ReadBits(log) | (1 << log)) - 1;
92
29.0k
      if (shift > ANS_LOG_TAB_SIZE + 1) {
93
4
        return JXL_FAILURE("Invalid shift value");
94
4
      }
95
29.0k
    }
96
97
29.0k
    int length = DecodeVarLenUint8(input) + 3;
98
29.0k
    counts->resize(length);
99
29.0k
    int total_count = 0;
100
101
29.0k
    static const uint8_t huff[128][2] = {
102
29.0k
        {3, 10}, {7, 12}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
103
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
104
29.0k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
105
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
106
29.0k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
107
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
108
29.0k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
109
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
110
29.0k
        {3, 10}, {7, 13}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
111
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
112
29.0k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
113
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
114
29.0k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
115
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
116
29.0k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
117
29.0k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
118
29.0k
    };
119
120
29.0k
    std::vector<int> logcounts(counts->size());
121
29.0k
    int omit_log = -1;
122
29.0k
    int omit_pos = -1;
123
    // This array remembers which symbols have an RLE length.
124
29.0k
    std::vector<int> same(counts->size(), 0);
125
346k
    for (size_t i = 0; i < logcounts.size(); ++i) {
126
317k
      input->Refill();  // for PeekFixedBits + Advance
127
317k
      int idx = input->PeekFixedBits<7>();
128
317k
      input->Consume(huff[idx][0]);
129
317k
      logcounts[i] = huff[idx][1];
130
      // The RLE symbol.
131
317k
      if (logcounts[i] == ANS_LOG_TAB_SIZE + 1) {
132
4.04k
        int rle_length = DecodeVarLenUint8(input);
133
4.04k
        same[i] = rle_length + 5;
134
4.04k
        i += rle_length + 3;
135
4.04k
        continue;
136
4.04k
      }
137
313k
      if (logcounts[i] > omit_log) {
138
40.3k
        omit_log = logcounts[i];
139
40.3k
        omit_pos = i;
140
40.3k
      }
141
313k
    }
142
    // Invalid input, e.g. due to invalid usage of RLE.
143
29.0k
    if (omit_pos < 0) return JXL_FAILURE("Invalid histogram.");
144
29.0k
    if (static_cast<size_t>(omit_pos) + 1 < logcounts.size() &&
145
29.0k
        logcounts[omit_pos + 1] == ANS_TAB_SIZE + 1) {
146
0
      return JXL_FAILURE("Invalid histogram.");
147
0
    }
148
29.0k
    int prev = 0;
149
29.0k
    int numsame = 0;
150
384k
    for (size_t i = 0; i < logcounts.size(); ++i) {
151
355k
      if (same[i]) {
152
        // RLE sequence, let this loop output the same count for the next
153
        // iterations.
154
4.03k
        numsame = same[i] - 1;
155
4.03k
        prev = i > 0 ? (*counts)[i - 1] : 0;
156
4.03k
      }
157
355k
      if (numsame > 0) {
158
41.6k
        (*counts)[i] = prev;
159
41.6k
        numsame--;
160
313k
      } else {
161
313k
        unsigned int code = logcounts[i];
162
        // omit_pos may not be negative at this point (checked before).
163
313k
        if (i == static_cast<size_t>(omit_pos)) {
164
28.9k
          continue;
165
284k
        } else if (code == 0) {
166
17.4k
          continue;
167
267k
        } else if (code == 1) {
168
7.75k
          (*counts)[i] = 1;
169
259k
        } else {
170
259k
          int bitcount = GetPopulationCountPrecision(code - 1, shift);
171
259k
          (*counts)[i] = (1u << (code - 1)) +
172
259k
                         (input->ReadBits(bitcount) << (code - 1 - bitcount));
173
259k
        }
174
313k
      }
175
309k
      total_count += (*counts)[i];
176
309k
    }
177
29.0k
    (*counts)[omit_pos] = range - total_count;
178
29.0k
    if ((*counts)[omit_pos] <= 0) {
179
      // The histogram we've read sums to more than total_count (including at
180
      // least 1 for the omitted value).
181
1.42k
      return JXL_FAILURE("Invalid histogram count.");
182
1.42k
    }
183
29.0k
  }
184
45.6k
  return true;
185
59.4k
}
186
187
}  // namespace
188
189
Status DecodeANSCodes(JxlMemoryManager* memory_manager,
190
                      const size_t num_histograms,
191
                      const size_t max_alphabet_size, BitReader* in,
192
134k
                      ANSCode* result) {
193
134k
  result->memory_manager = memory_manager;
194
134k
  result->degenerate_symbols.resize(num_histograms, -1);
195
134k
  if (result->use_prefix_code) {
196
91.6k
    JXL_ENSURE(max_alphabet_size <= 1 << PREFIX_MAX_BITS);
197
91.6k
    result->huffman_data.resize(num_histograms);
198
91.6k
    std::vector<uint16_t> alphabet_sizes(num_histograms);
199
205k
    for (size_t c = 0; c < num_histograms; c++) {
200
114k
      alphabet_sizes[c] = DecodeVarLenUint16(in) + 1;
201
114k
      if (alphabet_sizes[c] > max_alphabet_size) {
202
113
        return JXL_FAILURE("Alphabet size is too long: %u", alphabet_sizes[c]);
203
113
      }
204
114k
    }
205
200k
    for (size_t c = 0; c < num_histograms; c++) {
206
111k
      if (alphabet_sizes[c] > 1) {
207
29.3k
        if (!result->huffman_data[c].ReadFromBitStream(alphabet_sizes[c], in)) {
208
2.36k
          if (!in->AllReadsWithinBounds()) {
209
2.27k
            return JXL_STATUS(StatusCode::kNotEnoughBytes,
210
2.27k
                              "Not enough bytes for huffman code");
211
2.27k
          }
212
95
          return JXL_FAILURE("Invalid huffman tree number %" PRIuS
213
2.36k
                             ", alphabet size %u",
214
2.36k
                             c, alphabet_sizes[c]);
215
2.36k
        }
216
82.3k
      } else {
217
        // 0-bit codes does not require extension tables.
218
82.3k
        result->huffman_data[c].table_.clear();
219
82.3k
        result->huffman_data[c].table_.resize(1u << kHuffmanTableBits);
220
82.3k
      }
221
34.4M
      for (const auto& h : result->huffman_data[c].table_) {
222
34.4M
        if (h.bits <= kHuffmanTableBits) {
223
34.3M
          result->UpdateMaxNumBits(c, h.value);
224
34.3M
        }
225
34.4M
      }
226
109k
    }
227
91.5k
  } else {
228
42.7k
    JXL_ENSURE(max_alphabet_size <= ANS_MAX_ALPHABET_SIZE);
229
42.7k
    size_t alloc_size = num_histograms * (1 << result->log_alpha_size) *
230
42.7k
                        sizeof(AliasTable::Entry);
231
42.7k
    JXL_ASSIGN_OR_RETURN(result->alias_tables,
232
42.7k
                         AlignedMemory::Create(memory_manager, alloc_size));
233
42.7k
    AliasTable::Entry* alias_tables =
234
42.7k
        result->alias_tables.address<AliasTable::Entry>();
235
100k
    for (size_t c = 0; c < num_histograms; ++c) {
236
59.4k
      std::vector<int32_t> counts;
237
59.4k
      if (!ReadHistogram(ANS_LOG_TAB_SIZE, &counts, in)) {
238
1.66k
        return JXL_FAILURE("Invalid histogram bitstream.");
239
1.66k
      }
240
57.8k
      if (counts.size() > max_alphabet_size) {
241
231
        return JXL_FAILURE("Alphabet size is too long: %" PRIuS, counts.size());
242
231
      }
243
61.6k
      while (!counts.empty() && counts.back() == 0) {
244
4.01k
        counts.pop_back();
245
4.01k
      }
246
774k
      for (size_t s = 0; s < counts.size(); s++) {
247
717k
        if (counts[s] != 0) {
248
452k
          result->UpdateMaxNumBits(c, s);
249
452k
        }
250
717k
      }
251
      // InitAliasTable "fixes" empty counts to contain degenerate "0" symbol.
252
57.5k
      int degenerate_symbol = counts.empty() ? 0 : (counts.size() - 1);
253
191k
      for (int s = 0; s < degenerate_symbol; ++s) {
254
169k
        if (counts[s] != 0) {
255
35.6k
          degenerate_symbol = -1;
256
35.6k
          break;
257
35.6k
        }
258
169k
      }
259
57.5k
      result->degenerate_symbols[c] = degenerate_symbol;
260
57.5k
      JXL_RETURN_IF_ERROR(
261
57.5k
          InitAliasTable(counts, ANS_LOG_TAB_SIZE, result->log_alpha_size,
262
57.5k
                         alias_tables + c * (1 << result->log_alpha_size)));
263
57.5k
    }
264
42.7k
  }
265
130k
  return true;
266
134k
}
267
Status DecodeUintConfig(size_t log_alpha_size, HybridUintConfig* uint_config,
268
217k
                        BitReader* br) {
269
217k
  br->Refill();
270
217k
  size_t split_exponent = br->ReadBits(CeilLog2Nonzero(log_alpha_size + 1));
271
217k
  size_t msb_in_token = 0;
272
217k
  size_t lsb_in_token = 0;
273
217k
  if (split_exponent != log_alpha_size) {
274
    // otherwise, msb/lsb don't matter.
275
196k
    size_t nbits = CeilLog2Nonzero(split_exponent + 1);
276
196k
    msb_in_token = br->ReadBits(nbits);
277
196k
    if (msb_in_token > split_exponent) {
278
      // This could be invalid here already and we need to check this before
279
      // we use its value to read more bits.
280
98
      return JXL_FAILURE("Invalid HybridUintConfig");
281
98
    }
282
196k
    nbits = CeilLog2Nonzero(split_exponent - msb_in_token + 1);
283
196k
    lsb_in_token = br->ReadBits(nbits);
284
196k
  }
285
217k
  if (lsb_in_token + msb_in_token > split_exponent) {
286
58
    return JXL_FAILURE("Invalid HybridUintConfig");
287
58
  }
288
216k
  *uint_config = HybridUintConfig(split_exponent, msb_in_token, lsb_in_token);
289
216k
  return true;
290
217k
}
291
292
Status DecodeUintConfigs(size_t log_alpha_size,
293
                         std::vector<HybridUintConfig>* uint_config,
294
134k
                         BitReader* br) {
295
  // TODO(veluca): RLE?
296
176k
  for (auto& cfg : *uint_config) {
297
176k
    JXL_RETURN_IF_ERROR(DecodeUintConfig(log_alpha_size, &cfg, br));
298
176k
  }
299
134k
  return true;
300
134k
}
301
302
285k
LZ77Params::LZ77Params() { Bundle::Init(this); }
303
426k
Status LZ77Params::VisitFields(Visitor* JXL_RESTRICT visitor) {
304
426k
  JXL_QUIET_RETURN_IF_ERROR(visitor->Bool(false, &enabled));
305
425k
  if (!visitor->Conditional(enabled)) return true;
306
327k
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(224), Val(512), Val(4096),
307
327k
                                         BitsOffset(15, 8), 224, &min_symbol));
308
327k
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(3), Val(4), BitsOffset(2, 5),
309
327k
                                         BitsOffset(8, 9), 3, &min_length));
310
326k
  return true;
311
327k
}
312
313
34.8M
void ANSCode::UpdateMaxNumBits(size_t ctx, size_t symbol) {
314
34.8M
  HybridUintConfig* cfg = &uint_config[ctx];
315
  // LZ77 symbols use a different uint config.
316
34.8M
  if (lz77.enabled && lz77.nonserialized_distance_context != ctx &&
317
34.8M
      symbol >= lz77.min_symbol) {
318
44.8k
    symbol -= lz77.min_symbol;
319
44.8k
    cfg = &lz77.length_uint_config;
320
44.8k
  }
321
34.8M
  size_t split_token = cfg->split_token;
322
34.8M
  size_t msb_in_token = cfg->msb_in_token;
323
34.8M
  size_t lsb_in_token = cfg->lsb_in_token;
324
34.8M
  size_t split_exponent = cfg->split_exponent;
325
34.8M
  if (symbol < split_token) {
326
32.1M
    max_num_bits = std::max(max_num_bits, split_exponent);
327
32.1M
    return;
328
32.1M
  }
329
2.64M
  uint32_t n_extra_bits =
330
2.64M
      split_exponent - (msb_in_token + lsb_in_token) +
331
2.64M
      ((symbol - split_token) >> (msb_in_token + lsb_in_token));
332
2.64M
  size_t total_bits = msb_in_token + lsb_in_token + n_extra_bits + 1;
333
2.64M
  max_num_bits = std::max(max_num_bits, total_bits);
334
2.64M
}
335
336
Status DecodeHistograms(JxlMemoryManager* memory_manager, BitReader* br,
337
                        size_t num_contexts, ANSCode* code,
338
140k
                        std::vector<uint8_t>* context_map, bool disallow_lz77) {
339
140k
  JXL_RETURN_IF_ERROR(Bundle::Read(br, &code->lz77));
340
139k
  if (code->lz77.enabled) {
341
41.0k
    num_contexts++;
342
41.0k
    JXL_RETURN_IF_ERROR(DecodeUintConfig(/*log_alpha_size=*/8,
343
41.0k
                                         &code->lz77.length_uint_config, br));
344
41.0k
  }
345
139k
  if (code->lz77.enabled && disallow_lz77) {
346
279
    return JXL_FAILURE("Using LZ77 when explicitly disallowed");
347
279
  }
348
139k
  size_t num_histograms = 1;
349
139k
  context_map->resize(num_contexts);
350
139k
  if (num_contexts > 1) {
351
85.0k
    JXL_RETURN_IF_ERROR(
352
85.0k
        DecodeContextMap(memory_manager, context_map, &num_histograms, br));
353
85.0k
  }
354
134k
  JXL_DEBUG_V(
355
134k
      4, "Decoded context map of size %" PRIuS " and %" PRIuS " histograms",
356
134k
      num_contexts, num_histograms);
357
134k
  code->lz77.nonserialized_distance_context = context_map->back();
358
134k
  code->use_prefix_code = static_cast<bool>(br->ReadFixedBits<1>());
359
134k
  if (code->use_prefix_code) {
360
91.7k
    code->log_alpha_size = PREFIX_MAX_BITS;
361
91.7k
  } else {
362
42.8k
    code->log_alpha_size = br->ReadFixedBits<2>() + 5;
363
42.8k
  }
364
134k
  code->uint_config.resize(num_histograms);
365
134k
  JXL_RETURN_IF_ERROR(
366
134k
      DecodeUintConfigs(code->log_alpha_size, &code->uint_config, br));
367
134k
  const size_t max_alphabet_size = 1 << code->log_alpha_size;
368
134k
  JXL_RETURN_IF_ERROR(DecodeANSCodes(memory_manager, num_histograms,
369
134k
                                     max_alphabet_size, br, code));
370
130k
  return true;
371
134k
}
372
373
StatusOr<ANSSymbolReader> ANSSymbolReader::Create(const ANSCode* code,
374
                                                  BitReader* JXL_RESTRICT br,
375
148k
                                                  size_t distance_multiplier) {
376
148k
  AlignedMemory lz77_window_storage;
377
148k
  if (code->lz77.enabled) {
378
40.6k
    JxlMemoryManager* memory_manager = code->memory_manager;
379
40.6k
    JXL_ASSIGN_OR_RETURN(
380
40.6k
        lz77_window_storage,
381
40.6k
        AlignedMemory::Create(memory_manager, kWindowSize * sizeof(uint32_t)));
382
40.6k
  }
383
148k
  return ANSSymbolReader(code, br, distance_multiplier,
384
148k
                         std::move(lz77_window_storage));
385
148k
}
386
387
ANSSymbolReader::ANSSymbolReader(const ANSCode* code,
388
                                 BitReader* JXL_RESTRICT br,
389
                                 size_t distance_multiplier,
390
                                 AlignedMemory&& lz77_window_storage)
391
148k
    : alias_tables_(code->alias_tables.address<AliasTable::Entry>()),
392
148k
      huffman_data_(code->huffman_data.data()),
393
148k
      use_prefix_code_(code->use_prefix_code),
394
148k
      configs(code->uint_config.data()),
395
148k
      lz77_window_storage_(std::move(lz77_window_storage)) {
396
148k
  if (!use_prefix_code_) {
397
41.5k
    state_ = static_cast<uint32_t>(br->ReadFixedBits<32>());
398
41.5k
    log_alpha_size_ = code->log_alpha_size;
399
41.5k
    log_entry_size_ = ANS_LOG_TAB_SIZE - code->log_alpha_size;
400
41.5k
    entry_size_minus_1_ = (1 << log_entry_size_) - 1;
401
107k
  } else {
402
107k
    state_ = (ANS_SIGNATURE << 16u);
403
107k
  }
404
148k
  if (!code->lz77.enabled) return;
405
40.6k
  lz77_window_ = lz77_window_storage_.address<uint32_t>();
406
40.6k
  lz77_ctx_ = code->lz77.nonserialized_distance_context;
407
40.6k
  lz77_length_uint_ = code->lz77.length_uint_config;
408
40.6k
  lz77_threshold_ = code->lz77.min_symbol;
409
40.6k
  lz77_min_length_ = code->lz77.min_length;
410
40.6k
  num_special_distances_ = distance_multiplier == 0 ? 0 : kNumSpecialDistances;
411
750k
  for (size_t i = 0; i < num_special_distances_; i++) {
412
709k
    special_distances_[i] = SpecialDistance(i, distance_multiplier);
413
709k
  }
414
40.6k
}
415
416
}  // namespace jxl