Coverage Report

Created: 2025-08-11 08:01

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