Coverage Report

Created: 2025-12-03 07:54

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