Coverage Report

Created: 2025-09-08 07:52

/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
20.2k
inline int DecodeVarLenUint8(BitReader* input) {
27
20.2k
  if (input->ReadFixedBits<1>()) {
28
13.8k
    int nbits = static_cast<int>(input->ReadFixedBits<3>());
29
13.8k
    if (nbits == 0) {
30
501
      return 1;
31
13.3k
    } else {
32
13.3k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
33
13.3k
    }
34
13.8k
  }
35
6.42k
  return 0;
36
20.2k
}
37
38
// Decodes a number in the range [0..65535], by reading 1 - 21 bits.
39
29.1k
inline int DecodeVarLenUint16(BitReader* input) {
40
29.1k
  if (input->ReadFixedBits<1>()) {
41
12.0k
    int nbits = static_cast<int>(input->ReadFixedBits<4>());
42
12.0k
    if (nbits == 0) {
43
44
      return 1;
44
11.9k
    } else {
45
11.9k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
46
11.9k
    }
47
12.0k
  }
48
17.1k
  return 0;
49
29.1k
}
50
51
Status ReadHistogram(int precision_bits, std::vector<int32_t>* counts,
52
14.7k
                     BitReader* input) {
53
14.7k
  int range = 1 << precision_bits;
54
14.7k
  int simple_code = input->ReadBits(1);
55
14.7k
  if (simple_code == 1) {
56
2.14k
    int i;
57
2.14k
    int symbols[2] = {0};
58
2.14k
    int max_symbol = 0;
59
2.14k
    const int num_symbols = input->ReadBits(1) + 1;
60
4.60k
    for (i = 0; i < num_symbols; ++i) {
61
2.45k
      symbols[i] = DecodeVarLenUint8(input);
62
2.45k
      if (symbols[i] > max_symbol) max_symbol = symbols[i];
63
2.45k
    }
64
2.14k
    counts->resize(max_symbol + 1);
65
2.14k
    if (num_symbols == 1) {
66
1.83k
      (*counts)[symbols[0]] = range;
67
1.83k
    } else {
68
314
      if (symbols[0] == symbols[1]) {  // corrupt data
69
2
        return false;
70
2
      }
71
312
      (*counts)[symbols[0]] = input->ReadBits(precision_bits);
72
312
      (*counts)[symbols[1]] = range - (*counts)[symbols[0]];
73
312
    }
74
12.6k
  } else {
75
12.6k
    int is_flat = input->ReadBits(1);
76
12.6k
    if (is_flat == 1) {
77
3.07k
      int alphabet_size = DecodeVarLenUint8(input) + 1;
78
3.07k
      JXL_ENSURE(alphabet_size <= range);
79
3.07k
      *counts = CreateFlatHistogram(alphabet_size, range);
80
3.07k
      return true;
81
3.07k
    }
82
83
9.57k
    uint32_t shift;
84
9.57k
    {
85
      // TODO(veluca): speed up reading with table lookups.
86
9.57k
      int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
87
9.57k
      int log = 0;
88
13.3k
      for (; log < upper_bound_log; log++) {
89
13.3k
        if (input->ReadFixedBits<1>() == 0) break;
90
13.3k
      }
91
9.57k
      shift = (input->ReadBits(log) | (1 << log)) - 1;
92
9.57k
      if (shift > ANS_LOG_TAB_SIZE + 1) {
93
0
        return JXL_FAILURE("Invalid shift value");
94
0
      }
95
9.57k
    }
96
97
9.57k
    int length = DecodeVarLenUint8(input) + 3;
98
9.57k
    counts->resize(length);
99
9.57k
    int total_count = 0;
100
101
9.57k
    static const uint8_t huff[128][2] = {
102
9.57k
        {3, 10}, {7, 12}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
103
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
104
9.57k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
105
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
106
9.57k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
107
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
108
9.57k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
109
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
110
9.57k
        {3, 10}, {7, 13}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
111
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
112
9.57k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
113
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
114
9.57k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
115
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
116
9.57k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
117
9.57k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
118
9.57k
    };
119
120
9.57k
    std::vector<int> logcounts(counts->size());
121
9.57k
    int omit_log = -1;
122
9.57k
    int omit_pos = -1;
123
    // This array remembers which symbols have an RLE length.
124
9.57k
    std::vector<int> same(counts->size(), 0);
125
160k
    for (size_t i = 0; i < logcounts.size(); ++i) {
126
150k
      input->Refill();  // for PeekFixedBits + Advance
127
150k
      int idx = input->PeekFixedBits<7>();
128
150k
      input->Consume(huff[idx][0]);
129
150k
      logcounts[i] = huff[idx][1];
130
      // The RLE symbol.
131
150k
      if (logcounts[i] == ANS_LOG_TAB_SIZE + 1) {
132
5.12k
        int rle_length = DecodeVarLenUint8(input);
133
5.12k
        same[i] = rle_length + 5;
134
5.12k
        i += rle_length + 3;
135
5.12k
        continue;
136
5.12k
      }
137
145k
      if (logcounts[i] > omit_log) {
138
15.0k
        omit_log = logcounts[i];
139
15.0k
        omit_pos = i;
140
15.0k
      }
141
145k
    }
142
    // Invalid input, e.g. due to invalid usage of RLE.
143
9.57k
    if (omit_pos < 0) return JXL_FAILURE("Invalid histogram.");
144
9.57k
    if (static_cast<size_t>(omit_pos) + 1 < logcounts.size() &&
145
9.57k
        logcounts[omit_pos + 1] == ANS_TAB_SIZE + 1) {
146
0
      return JXL_FAILURE("Invalid histogram.");
147
0
    }
148
9.57k
    int prev = 0;
149
9.57k
    int numsame = 0;
150
228k
    for (size_t i = 0; i < logcounts.size(); ++i) {
151
219k
      if (same[i]) {
152
        // RLE sequence, let this loop output the same count for the next
153
        // iterations.
154
5.12k
        numsame = same[i] - 1;
155
5.12k
        prev = i > 0 ? (*counts)[i - 1] : 0;
156
5.12k
      }
157
219k
      if (numsame > 0) {
158
73.7k
        (*counts)[i] = prev;
159
73.7k
        numsame--;
160
145k
      } else {
161
145k
        unsigned int code = logcounts[i];
162
        // omit_pos may not be negative at this point (checked before).
163
145k
        if (i == static_cast<size_t>(omit_pos)) {
164
9.57k
          continue;
165
136k
        } else if (code == 0) {
166
34.1k
          continue;
167
101k
        } else if (code == 1) {
168
3.78k
          (*counts)[i] = 1;
169
98.0k
        } else {
170
98.0k
          int bitcount = GetPopulationCountPrecision(code - 1, shift);
171
98.0k
          (*counts)[i] = (1u << (code - 1)) +
172
98.0k
                         (input->ReadBits(bitcount) << (code - 1 - bitcount));
173
98.0k
        }
174
145k
      }
175
175k
      total_count += (*counts)[i];
176
175k
    }
177
9.57k
    (*counts)[omit_pos] = range - total_count;
178
9.57k
    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
0
      return JXL_FAILURE("Invalid histogram count.");
182
0
    }
183
9.57k
  }
184
11.7k
  return true;
185
14.7k
}
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
33.8k
                      ANSCode* result) {
193
33.8k
  result->memory_manager = memory_manager;
194
33.8k
  result->degenerate_symbols.resize(num_histograms, -1);
195
33.8k
  if (result->use_prefix_code) {
196
26.4k
    JXL_ENSURE(max_alphabet_size <= 1 << PREFIX_MAX_BITS);
197
26.4k
    result->huffman_data.resize(num_histograms);
198
26.4k
    std::vector<uint16_t> alphabet_sizes(num_histograms);
199
55.6k
    for (size_t c = 0; c < num_histograms; c++) {
200
29.1k
      alphabet_sizes[c] = DecodeVarLenUint16(in) + 1;
201
29.1k
      if (alphabet_sizes[c] > max_alphabet_size) {
202
0
        return JXL_FAILURE("Alphabet size is too long: %u", alphabet_sizes[c]);
203
0
      }
204
29.1k
    }
205
55.4k
    for (size_t c = 0; c < num_histograms; c++) {
206
29.1k
      if (alphabet_sizes[c] > 1) {
207
11.9k
        if (!result->huffman_data[c].ReadFromBitStream(alphabet_sizes[c], in)) {
208
148
          if (!in->AllReadsWithinBounds()) {
209
142
            return JXL_STATUS(StatusCode::kNotEnoughBytes,
210
142
                              "Not enough bytes for huffman code");
211
142
          }
212
6
          return JXL_FAILURE("Invalid huffman tree number %" PRIuS
213
148
                             ", alphabet size %u",
214
148
                             c, alphabet_sizes[c]);
215
148
        }
216
17.1k
      } else {
217
        // 0-bit codes does not require extension tables.
218
17.1k
        result->huffman_data[c].table_.clear();
219
17.1k
        result->huffman_data[c].table_.resize(1u << kHuffmanTableBits);
220
17.1k
      }
221
7.42M
      for (const auto& h : result->huffman_data[c].table_) {
222
7.42M
        if (h.bits <= kHuffmanTableBits) {
223
7.42M
          result->UpdateMaxNumBits(c, h.value);
224
7.42M
        }
225
7.42M
      }
226
28.9k
    }
227
26.4k
  } else {
228
7.40k
    JXL_ENSURE(max_alphabet_size <= ANS_MAX_ALPHABET_SIZE);
229
7.40k
    size_t alloc_size = num_histograms * (1 << result->log_alpha_size) *
230
7.40k
                        sizeof(AliasTable::Entry);
231
7.40k
    JXL_ASSIGN_OR_RETURN(result->alias_tables,
232
7.40k
                         AlignedMemory::Create(memory_manager, alloc_size));
233
7.40k
    AliasTable::Entry* alias_tables =
234
7.40k
        result->alias_tables.address<AliasTable::Entry>();
235
22.1k
    for (size_t c = 0; c < num_histograms; ++c) {
236
14.7k
      std::vector<int32_t> counts;
237
14.7k
      if (!ReadHistogram(ANS_LOG_TAB_SIZE, &counts, in)) {
238
2
        return JXL_FAILURE("Invalid histogram bitstream.");
239
2
      }
240
14.7k
      if (counts.size() > max_alphabet_size) {
241
1
        return JXL_FAILURE("Alphabet size is too long: %" PRIuS, counts.size());
242
1
      }
243
14.7k
      while (!counts.empty() && counts.back() == 0) {
244
8
        counts.pop_back();
245
8
      }
246
275k
      for (size_t s = 0; s < counts.size(); s++) {
247
260k
        if (counts[s] != 0) {
248
147k
          result->UpdateMaxNumBits(c, s);
249
147k
        }
250
260k
      }
251
      // InitAliasTable "fixes" empty counts to contain degenerate "0" symbol.
252
14.7k
      int degenerate_symbol = counts.empty() ? 0 : (counts.size() - 1);
253
18.3k
      for (int s = 0; s < degenerate_symbol; ++s) {
254
14.1k
        if (counts[s] != 0) {
255
10.5k
          degenerate_symbol = -1;
256
10.5k
          break;
257
10.5k
        }
258
14.1k
      }
259
14.7k
      result->degenerate_symbols[c] = degenerate_symbol;
260
14.7k
      JXL_RETURN_IF_ERROR(
261
14.7k
          InitAliasTable(counts, ANS_LOG_TAB_SIZE, result->log_alpha_size,
262
14.7k
                         alias_tables + c * (1 << result->log_alpha_size)));
263
14.7k
    }
264
7.40k
  }
265
33.7k
  return true;
266
33.8k
}
267
Status DecodeUintConfig(size_t log_alpha_size, HybridUintConfig* uint_config,
268
59.1k
                        BitReader* br) {
269
59.1k
  br->Refill();
270
59.1k
  size_t split_exponent = br->ReadBits(CeilLog2Nonzero(log_alpha_size + 1));
271
59.1k
  size_t msb_in_token = 0;
272
59.1k
  size_t lsb_in_token = 0;
273
59.1k
  if (split_exponent != log_alpha_size) {
274
    // otherwise, msb/lsb don't matter.
275
52.5k
    size_t nbits = CeilLog2Nonzero(split_exponent + 1);
276
52.5k
    msb_in_token = br->ReadBits(nbits);
277
52.5k
    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
2
      return JXL_FAILURE("Invalid HybridUintConfig");
281
2
    }
282
52.5k
    nbits = CeilLog2Nonzero(split_exponent - msb_in_token + 1);
283
52.5k
    lsb_in_token = br->ReadBits(nbits);
284
52.5k
  }
285
59.1k
  if (lsb_in_token + msb_in_token > split_exponent) {
286
2
    return JXL_FAILURE("Invalid HybridUintConfig");
287
2
  }
288
59.1k
  *uint_config = HybridUintConfig(split_exponent, msb_in_token, lsb_in_token);
289
59.1k
  return true;
290
59.1k
}
291
292
Status DecodeUintConfigs(size_t log_alpha_size,
293
                         std::vector<HybridUintConfig>* uint_config,
294
33.8k
                         BitReader* br) {
295
  // TODO(veluca): RLE?
296
43.9k
  for (auto& cfg : *uint_config) {
297
43.9k
    JXL_RETURN_IF_ERROR(DecodeUintConfig(log_alpha_size, &cfg, br));
298
43.9k
  }
299
33.8k
  return true;
300
33.8k
}
301
302
119k
LZ77Params::LZ77Params() { Bundle::Init(this); }
303
153k
Status LZ77Params::VisitFields(Visitor* JXL_RESTRICT visitor) {
304
153k
  JXL_QUIET_RETURN_IF_ERROR(visitor->Bool(false, &enabled));
305
153k
  if (!visitor->Conditional(enabled)) return true;
306
134k
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(224), Val(512), Val(4096),
307
134k
                                         BitsOffset(15, 8), 224, &min_symbol));
308
134k
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(3), Val(4), BitsOffset(2, 5),
309
134k
                                         BitsOffset(8, 9), 3, &min_length));
310
134k
  return true;
311
134k
}
312
313
7.56M
void ANSCode::UpdateMaxNumBits(size_t ctx, size_t symbol) {
314
7.56M
  HybridUintConfig* cfg = &uint_config[ctx];
315
  // LZ77 symbols use a different uint config.
316
7.56M
  if (lz77.enabled && lz77.nonserialized_distance_context != ctx &&
317
7.56M
      symbol >= lz77.min_symbol) {
318
3.26k
    symbol -= lz77.min_symbol;
319
3.26k
    cfg = &lz77.length_uint_config;
320
3.26k
  }
321
7.56M
  size_t split_token = cfg->split_token;
322
7.56M
  size_t msb_in_token = cfg->msb_in_token;
323
7.56M
  size_t lsb_in_token = cfg->lsb_in_token;
324
7.56M
  size_t split_exponent = cfg->split_exponent;
325
7.56M
  if (symbol < split_token) {
326
6.52M
    max_num_bits = std::max(max_num_bits, split_exponent);
327
6.52M
    return;
328
6.52M
  }
329
1.03M
  uint32_t n_extra_bits =
330
1.03M
      split_exponent - (msb_in_token + lsb_in_token) +
331
1.03M
      ((symbol - split_token) >> (msb_in_token + lsb_in_token));
332
1.03M
  size_t total_bits = msb_in_token + lsb_in_token + n_extra_bits + 1;
333
1.03M
  max_num_bits = std::max(max_num_bits, total_bits);
334
1.03M
}
335
336
Status DecodeHistograms(JxlMemoryManager* memory_manager, BitReader* br,
337
                        size_t num_contexts, ANSCode* code,
338
34.0k
                        std::vector<uint8_t>* context_map, bool disallow_lz77) {
339
34.0k
  JXL_RETURN_IF_ERROR(Bundle::Read(br, &code->lz77));
340
34.0k
  if (code->lz77.enabled) {
341
15.2k
    num_contexts++;
342
15.2k
    JXL_RETURN_IF_ERROR(DecodeUintConfig(/*log_alpha_size=*/8,
343
15.2k
                                         &code->lz77.length_uint_config, br));
344
15.2k
  }
345
34.0k
  if (code->lz77.enabled && disallow_lz77) {
346
0
    return JXL_FAILURE("Using LZ77 when explicitly disallowed");
347
0
  }
348
34.0k
  size_t num_histograms = 1;
349
34.0k
  context_map->resize(num_contexts);
350
34.0k
  if (num_contexts > 1) {
351
22.8k
    JXL_RETURN_IF_ERROR(
352
22.8k
        DecodeContextMap(memory_manager, context_map, &num_histograms, br));
353
22.8k
  }
354
33.8k
  JXL_DEBUG_V(
355
33.8k
      4, "Decoded context map of size %" PRIuS " and %" PRIuS " histograms",
356
33.8k
      num_contexts, num_histograms);
357
33.8k
  code->lz77.nonserialized_distance_context = context_map->back();
358
33.8k
  code->use_prefix_code = static_cast<bool>(br->ReadFixedBits<1>());
359
33.8k
  if (code->use_prefix_code) {
360
26.4k
    code->log_alpha_size = PREFIX_MAX_BITS;
361
26.4k
  } else {
362
7.40k
    code->log_alpha_size = br->ReadFixedBits<2>() + 5;
363
7.40k
  }
364
33.8k
  code->uint_config.resize(num_histograms);
365
33.8k
  JXL_RETURN_IF_ERROR(
366
33.8k
      DecodeUintConfigs(code->log_alpha_size, &code->uint_config, br));
367
33.8k
  const size_t max_alphabet_size = 1 << code->log_alpha_size;
368
33.8k
  JXL_RETURN_IF_ERROR(DecodeANSCodes(memory_manager, num_histograms,
369
33.8k
                                     max_alphabet_size, br, code));
370
33.7k
  return true;
371
33.8k
}
372
373
StatusOr<ANSSymbolReader> ANSSymbolReader::Create(const ANSCode* code,
374
                                                  BitReader* JXL_RESTRICT br,
375
45.3k
                                                  size_t distance_multiplier) {
376
45.3k
  AlignedMemory lz77_window_storage;
377
45.3k
  if (code->lz77.enabled) {
378
17.9k
    JxlMemoryManager* memory_manager = code->memory_manager;
379
17.9k
    JXL_ASSIGN_OR_RETURN(
380
17.9k
        lz77_window_storage,
381
17.9k
        AlignedMemory::Create(memory_manager, kWindowSize * sizeof(uint32_t)));
382
17.9k
  }
383
45.3k
  return ANSSymbolReader(code, br, distance_multiplier,
384
45.3k
                         std::move(lz77_window_storage));
385
45.3k
}
386
387
ANSSymbolReader::ANSSymbolReader(const ANSCode* code,
388
                                 BitReader* JXL_RESTRICT br,
389
                                 size_t distance_multiplier,
390
                                 AlignedMemory&& lz77_window_storage)
391
45.3k
    : alias_tables_(code->alias_tables.address<AliasTable::Entry>()),
392
45.3k
      huffman_data_(code->huffman_data.data()),
393
45.3k
      use_prefix_code_(code->use_prefix_code),
394
45.3k
      configs(code->uint_config.data()),
395
45.3k
      lz77_window_storage_(std::move(lz77_window_storage)) {
396
45.3k
  if (!use_prefix_code_) {
397
8.65k
    state_ = static_cast<uint32_t>(br->ReadFixedBits<32>());
398
8.65k
    log_alpha_size_ = code->log_alpha_size;
399
8.65k
    log_entry_size_ = ANS_LOG_TAB_SIZE - code->log_alpha_size;
400
8.65k
    entry_size_minus_1_ = (1 << log_entry_size_) - 1;
401
36.7k
  } else {
402
36.7k
    state_ = (ANS_SIGNATURE << 16u);
403
36.7k
  }
404
45.3k
  if (!code->lz77.enabled) return;
405
17.9k
  lz77_window_ = lz77_window_storage_.address<uint32_t>();
406
17.9k
  lz77_ctx_ = code->lz77.nonserialized_distance_context;
407
17.9k
  lz77_length_uint_ = code->lz77.length_uint_config;
408
17.9k
  lz77_threshold_ = code->lz77.min_symbol;
409
17.9k
  lz77_min_length_ = code->lz77.min_length;
410
17.9k
  num_special_distances_ = distance_multiplier == 0 ? 0 : kNumSpecialDistances;
411
380k
  for (size_t i = 0; i < num_special_distances_; i++) {
412
362k
    special_distances_[i] = SpecialDistance(i, distance_multiplier);
413
362k
  }
414
17.9k
}
415
416
}  // namespace jxl