Coverage Report

Created: 2026-05-24 07:45

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
742k
inline int DecodeVarLenUint8(BitReader* input) {
34
742k
  if (input->ReadFixedBits<1>()) {
35
202k
    int nbits = static_cast<int>(input->ReadFixedBits<3>());
36
202k
    if (nbits == 0) {
37
40.9k
      return 1;
38
161k
    } else {
39
161k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
40
161k
    }
41
202k
  }
42
539k
  return 0;
43
742k
}
44
45
// Decodes a number in the range [0..65535], by reading 1 - 21 bits.
46
307k
inline int DecodeVarLenUint16(BitReader* input) {
47
307k
  if (input->ReadFixedBits<1>()) {
48
42.0k
    int nbits = static_cast<int>(input->ReadFixedBits<4>());
49
42.0k
    if (nbits == 0) {
50
1.89k
      return 1;
51
40.1k
    } else {
52
40.1k
      return static_cast<int>(input->ReadBits(nbits)) + (1 << nbits);
53
40.1k
    }
54
42.0k
  }
55
265k
  return 0;
56
307k
}
57
58
Status ReadHistogram(int precision_bits, std::vector<int32_t>* counts,
59
673k
                     BitReader* input) {
60
673k
  int range = 1 << precision_bits;
61
673k
  int simple_code = input->ReadBits(1);
62
673k
  if (simple_code == 1) {
63
81.8k
    int i;
64
81.8k
    int symbols[2] = {0};
65
81.8k
    int max_symbol = 0;
66
81.8k
    const int num_symbols = input->ReadBits(1) + 1;
67
195k
    for (i = 0; i < num_symbols; ++i) {
68
113k
      symbols[i] = DecodeVarLenUint8(input);
69
113k
      if (symbols[i] > max_symbol) max_symbol = symbols[i];
70
113k
    }
71
81.8k
    counts->resize(max_symbol + 1);
72
81.8k
    if (num_symbols == 1) {
73
50.2k
      (*counts)[symbols[0]] = range;
74
50.2k
    } else {
75
31.5k
      if (symbols[0] == symbols[1]) {  // corrupt data
76
4.58k
        return false;
77
4.58k
      }
78
27.0k
      (*counts)[symbols[0]] = input->ReadBits(precision_bits);
79
27.0k
      (*counts)[symbols[1]] = range - (*counts)[symbols[0]];
80
27.0k
    }
81
591k
  } else {
82
591k
    int is_flat = input->ReadBits(1);
83
591k
    if (is_flat == 1) {
84
92.1k
      int alphabet_size = DecodeVarLenUint8(input) + 1;
85
92.1k
      JXL_ENSURE(alphabet_size <= range);
86
92.1k
      *counts = CreateFlatHistogram(alphabet_size, range);
87
92.1k
      return true;
88
92.1k
    }
89
90
499k
    uint32_t shift;
91
499k
    {
92
      // TODO(veluca): speed up reading with table lookups.
93
499k
      int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
94
499k
      int log = 0;
95
605k
      for (; log < upper_bound_log; log++) {
96
595k
        if (input->ReadFixedBits<1>() == 0) break;
97
595k
      }
98
499k
      shift = (input->ReadBits(log) | (1 << log)) - 1;
99
499k
      if (shift > ANS_LOG_TAB_SIZE + 1) {
100
1.68k
        return JXL_FAILURE("Invalid shift value");
101
1.68k
      }
102
499k
    }
103
104
498k
    const size_t length = DecodeVarLenUint8(input) + 3;
105
498k
    counts->resize(length);
106
498k
    int total_count = 0;
107
108
498k
    static const uint8_t huff[128][2] = {
109
498k
        {3, 10}, {7, 12}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
110
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
111
498k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
112
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
113
498k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
114
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
115
498k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
116
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
117
498k
        {3, 10}, {7, 13}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
118
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
119
498k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
120
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
121
498k
        {3, 10}, {6, 11}, {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
122
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
123
498k
        {3, 10}, {5, 0},  {3, 7}, {4, 3}, {3, 6}, {3, 8}, {3, 9}, {4, 5},
124
498k
        {3, 10}, {4, 4},  {3, 7}, {4, 1}, {3, 6}, {3, 8}, {3, 9}, {4, 2},
125
498k
    };
126
127
498k
    std::vector<int> logcounts(length);
128
498k
    int omit_log = -1;
129
498k
    int omit_pos = -1;
130
    // This array remembers which symbols have an RLE length.
131
498k
    std::vector<int> same(length);
132
3.44M
    for (size_t i = 0; i < length; ++i) {
133
2.94M
      input->Refill();  // for PeekFixedBits + Advance
134
2.94M
      int idx = input->PeekFixedBits<7>();
135
2.94M
      input->Consume(huff[idx][0]);
136
2.94M
      logcounts[i] = int(huff[idx][1]) - 1;
137
      // The RLE symbol.
138
2.94M
      if (logcounts[i] == ANS_LOG_TAB_SIZE) {
139
38.4k
        int rle_length = DecodeVarLenUint8(input);
140
38.4k
        same[i] = rle_length + 5;
141
38.4k
        i += rle_length + 3;
142
38.4k
        continue;
143
38.4k
      }
144
2.90M
      if (logcounts[i] > omit_log) {
145
667k
        omit_log = logcounts[i];
146
667k
        omit_pos = i;
147
667k
      }
148
2.90M
    }
149
    // Invalid input, e.g. due to invalid usage of RLE.
150
498k
    if (omit_pos < 0) return JXL_FAILURE("Invalid histogram.");
151
497k
    if (static_cast<size_t>(omit_pos) + 1 < length &&
152
467k
        logcounts[omit_pos + 1] == ANS_LOG_TAB_SIZE) {
153
340
      return JXL_FAILURE("Invalid histogram.");
154
340
    }
155
497k
    int prev = 0;
156
497k
    int numsame = 0;
157
4.02M
    for (size_t i = 0; i < length; ++i) {
158
3.52M
      if (same[i]) {
159
        // RLE sequence, let this loop output the same count for the next
160
        // iterations.
161
37.9k
        numsame = same[i] - 1;
162
37.9k
        prev = i > 0 ? (*counts)[i - 1] : 0;
163
37.9k
      }
164
3.52M
      if (numsame > 0) {
165
625k
        (*counts)[i] = prev;
166
625k
        numsame--;
167
2.90M
      } else {
168
2.90M
        int code = logcounts[i];
169
        // omit_pos may not be negative at this point (checked before).
170
2.90M
        if (i == static_cast<size_t>(omit_pos) || code < 0) {
171
861k
          continue;
172
2.04M
        } else if (shift == 0 || code == 0) {
173
          // `shift = 0` means `bitcount = 0`
174
1.53M
          (*counts)[i] = 1 << code;
175
1.53M
        } else {
176
508k
          int bitcount = GetPopulationCountPrecision(code, shift);
177
508k
          (*counts)[i] = (1 << code) +
178
508k
                         (input->ReadBits(bitcount) << (code - bitcount));
179
508k
        }
180
2.90M
      }
181
2.66M
      total_count += (*counts)[i];
182
2.66M
    }
183
497k
    (*counts)[omit_pos] = range - total_count;
184
497k
    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
2.84k
      return JXL_FAILURE("Invalid histogram count.");
188
2.84k
    }
189
497k
  }
190
572k
  return true;
191
673k
}
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
721k
                      ANSCode* result) {
199
721k
  result->memory_manager = memory_manager;
200
721k
  result->degenerate_symbols.resize(num_histograms, -1);
201
721k
  if (result->use_prefix_code) {
202
229k
    JXL_ENSURE(max_alphabet_size <= 1 << PREFIX_MAX_BITS);
203
229k
    result->huffman_data.resize(num_histograms);
204
229k
    std::vector<uint16_t> alphabet_sizes(num_histograms);
205
536k
    for (size_t c = 0; c < num_histograms; c++) {
206
307k
      alphabet_sizes[c] = DecodeVarLenUint16(in) + 1;
207
307k
      if (alphabet_sizes[c] > max_alphabet_size) {
208
269
        return JXL_FAILURE("Alphabet size is too long: %u", alphabet_sizes[c]);
209
269
      }
210
307k
    }
211
523k
    for (size_t c = 0; c < num_histograms; c++) {
212
304k
      if (alphabet_sizes[c] > 1) {
213
39.8k
        if (!result->huffman_data[c].ReadFromBitStream(alphabet_sizes[c], in)) {
214
10.0k
          if (!in->AllReadsWithinBounds()) {
215
1.23k
            return JXL_NOT_ENOUGH_BYTES("Not enough bytes for huffman code");
216
1.23k
          }
217
8.82k
          return JXL_FAILURE("Invalid huffman tree number %" PRIuS
218
10.0k
                             ", alphabet size %u",
219
10.0k
                             c, alphabet_sizes[c]);
220
10.0k
        }
221
264k
      } else {
222
        // 0-bit codes does not require extension tables.
223
264k
        result->huffman_data[c].table_.clear();
224
264k
        result->huffman_data[c].table_.resize(1u << kHuffmanTableBits);
225
264k
      }
226
77.6M
      for (const auto& h : result->huffman_data[c].table_) {
227
77.6M
        if (h.bits <= kHuffmanTableBits) {
228
77.5M
          result->UpdateMaxNumBits(c, h.value);
229
77.5M
        }
230
77.6M
      }
231
294k
    }
232
491k
  } else {
233
491k
    JXL_ENSURE(max_alphabet_size <= ANS_MAX_ALPHABET_SIZE);
234
491k
    size_t alloc_size = num_histograms * (1 << result->log_alpha_size) *
235
491k
                        sizeof(AliasTable::Entry);
236
491k
    JXL_ASSIGN_OR_RETURN(result->alias_tables,
237
491k
                         AlignedMemory::Create(memory_manager, alloc_size));
238
491k
    AliasTable::Entry* alias_tables =
239
491k
        result->alias_tables.address<AliasTable::Entry>();
240
1.15M
    for (size_t c = 0; c < num_histograms; ++c) {
241
673k
      std::vector<int32_t> counts;
242
673k
      if (!ReadHistogram(ANS_LOG_TAB_SIZE, &counts, in)) {
243
9.50k
        return JXL_FAILURE("Invalid histogram bitstream.");
244
9.50k
      }
245
664k
      if (counts.size() > max_alphabet_size) {
246
2.56k
        return JXL_FAILURE("Alphabet size is too long: %" PRIuS, counts.size());
247
2.56k
      }
248
693k
      while (!counts.empty() && counts.back() == 0) {
249
32.1k
        counts.pop_back();
250
32.1k
      }
251
5.37M
      for (size_t s = 0; s < counts.size(); s++) {
252
4.71M
        if (counts[s] != 0) {
253
3.13M
          result->UpdateMaxNumBits(c, s);
254
3.13M
        }
255
4.71M
      }
256
      // InitAliasTable "fixes" empty counts to contain degenerate "0" symbol.
257
661k
      int degenerate_symbol = counts.empty() ? 0 : (counts.size() - 1);
258
959k
      for (int s = 0; s < degenerate_symbol; ++s) {
259
829k
        if (counts[s] != 0) {
260
531k
          degenerate_symbol = -1;
261
531k
          break;
262
531k
        }
263
829k
      }
264
661k
      result->degenerate_symbols[c] = degenerate_symbol;
265
661k
      JXL_RETURN_IF_ERROR(
266
661k
          InitAliasTable(counts, ANS_LOG_TAB_SIZE, result->log_alpha_size,
267
661k
                         alias_tables + c * (1 << result->log_alpha_size)));
268
661k
    }
269
491k
  }
270
698k
  return true;
271
721k
}
272
Status DecodeUintConfig(size_t log_alpha_size, HybridUintConfig* uint_config,
273
1.22M
                        BitReader* br) {
274
1.22M
  br->Refill();
275
1.22M
  size_t split_exponent = br->ReadBits(CeilLog2Nonzero(log_alpha_size + 1));
276
1.22M
  size_t msb_in_token = 0;
277
1.22M
  size_t lsb_in_token = 0;
278
1.22M
  if (split_exponent != log_alpha_size) {
279
    // otherwise, msb/lsb don't matter.
280
1.17M
    size_t nbits = CeilLog2Nonzero(split_exponent + 1);
281
1.17M
    msb_in_token = br->ReadBits(nbits);
282
1.17M
    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
5.35k
      return JXL_FAILURE("Invalid HybridUintConfig");
286
5.35k
    }
287
1.17M
    nbits = CeilLog2Nonzero(split_exponent - msb_in_token + 1);
288
1.17M
    lsb_in_token = br->ReadBits(nbits);
289
1.17M
  }
290
1.21M
  if (lsb_in_token + msb_in_token > split_exponent) {
291
1.60k
    return JXL_FAILURE("Invalid HybridUintConfig");
292
1.60k
  }
293
1.21M
  *uint_config = HybridUintConfig(split_exponent, msb_in_token, lsb_in_token);
294
1.21M
  return true;
295
1.21M
}
296
297
Status DecodeUintConfigs(size_t log_alpha_size,
298
                         std::vector<HybridUintConfig>* uint_config,
299
725k
                         BitReader* br) {
300
  // TODO(veluca): RLE?
301
1.00M
  for (auto& cfg : *uint_config) {
302
1.00M
    JXL_RETURN_IF_ERROR(DecodeUintConfig(log_alpha_size, &cfg, br));
303
1.00M
  }
304
721k
  return true;
305
725k
}
306
307
1.59M
LZ77Params::LZ77Params() { Bundle::Init(this); }
308
2.50M
Status LZ77Params::VisitFields(Visitor* JXL_RESTRICT visitor) {
309
2.50M
  JXL_QUIET_RETURN_IF_ERROR(visitor->Bool(false, &enabled));
310
2.46M
  if (!visitor->Conditional(enabled)) return true;
311
1.83M
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(224), Val(512), Val(4096),
312
1.83M
                                         BitsOffset(15, 8), 224, &min_symbol));
313
1.83M
  JXL_QUIET_RETURN_IF_ERROR(visitor->U32(Val(3), Val(4), BitsOffset(2, 5),
314
1.83M
                                         BitsOffset(8, 9), 3, &min_length));
315
1.82M
  return true;
316
1.83M
}
317
318
80.6M
void ANSCode::UpdateMaxNumBits(size_t ctx, size_t symbol) {
319
80.6M
  HybridUintConfig* cfg = &uint_config[ctx];
320
  // LZ77 symbols use a different uint config.
321
80.6M
  if (lz77.enabled && lz77.nonserialized_distance_context != ctx &&
322
15.6M
      symbol >= lz77.min_symbol) {
323
331k
    symbol -= lz77.min_symbol;
324
331k
    cfg = &lz77.length_uint_config;
325
331k
  }
326
80.6M
  size_t split_token = cfg->split_token;
327
80.6M
  size_t msb_in_token = cfg->msb_in_token;
328
80.6M
  size_t lsb_in_token = cfg->lsb_in_token;
329
80.6M
  size_t split_exponent = cfg->split_exponent;
330
80.6M
  if (symbol < split_token) {
331
74.9M
    max_num_bits = std::max(max_num_bits, split_exponent);
332
74.9M
    return;
333
74.9M
  }
334
5.72M
  uint32_t n_extra_bits =
335
5.72M
      split_exponent - (msb_in_token + lsb_in_token) +
336
5.72M
      ((symbol - split_token) >> (msb_in_token + lsb_in_token));
337
5.72M
  size_t total_bits = msb_in_token + lsb_in_token + n_extra_bits + 1;
338
5.72M
  max_num_bits = std::max(max_num_bits, total_bits);
339
5.72M
}
340
341
Status DecodeHistograms(JxlMemoryManager* memory_manager, BitReader* br,
342
                        size_t num_contexts, ANSCode* code,
343
807k
                        std::vector<uint8_t>* context_map, bool disallow_lz77) {
344
807k
  JXL_RETURN_IF_ERROR(Bundle::Read(br, &code->lz77));
345
766k
  if (code->lz77.enabled) {
346
223k
    num_contexts++;
347
223k
    JXL_RETURN_IF_ERROR(DecodeUintConfig(/*log_alpha_size=*/8,
348
223k
                                         &code->lz77.length_uint_config, br));
349
223k
  }
350
763k
  if (code->lz77.enabled && disallow_lz77) {
351
5.31k
    return JXL_FAILURE("Using LZ77 when explicitly disallowed");
352
5.31k
  }
353
758k
  size_t num_histograms = 1;
354
758k
  context_map->resize(num_contexts);
355
758k
  if (num_contexts > 1) {
356
450k
    JXL_RETURN_IF_ERROR(
357
450k
        DecodeContextMap(memory_manager, context_map, &num_histograms, br));
358
450k
  }
359
725k
  JXL_DEBUG_V(
360
725k
      4, "Decoded context map of size %" PRIuS " and %" PRIuS " histograms",
361
725k
      num_contexts, num_histograms);
362
725k
  code->lz77.nonserialized_distance_context = context_map->back();
363
725k
  code->use_prefix_code = static_cast<bool>(br->ReadFixedBits<1>());
364
725k
  if (code->use_prefix_code) {
365
231k
    code->log_alpha_size = PREFIX_MAX_BITS;
366
493k
  } else {
367
493k
    code->log_alpha_size = br->ReadFixedBits<2>() + 5;
368
493k
  }
369
725k
  code->uint_config.resize(num_histograms);
370
725k
  JXL_RETURN_IF_ERROR(
371
725k
      DecodeUintConfigs(code->log_alpha_size, &code->uint_config, br));
372
721k
  const size_t max_alphabet_size = 1 << code->log_alpha_size;
373
721k
  JXL_RETURN_IF_ERROR(DecodeANSCodes(memory_manager, num_histograms,
374
721k
                                     max_alphabet_size, br, code));
375
698k
  return true;
376
721k
}
377
378
StatusOr<ANSSymbolReader> ANSSymbolReader::Create(const ANSCode* code,
379
                                                  BitReader* JXL_RESTRICT br,
380
720k
                                                  size_t distance_multiplier) {
381
720k
  AlignedMemory lz77_window_storage;
382
720k
  if (code->lz77.enabled) {
383
187k
    JxlMemoryManager* memory_manager = code->memory_manager;
384
187k
    JXL_ASSIGN_OR_RETURN(
385
187k
        lz77_window_storage,
386
187k
        AlignedMemory::Create(memory_manager, kWindowSize * sizeof(uint32_t)));
387
187k
  }
388
720k
  return ANSSymbolReader(code, br, distance_multiplier,
389
720k
                         std::move(lz77_window_storage));
390
720k
}
391
392
ANSSymbolReader::ANSSymbolReader(const ANSCode* code,
393
                                 BitReader* JXL_RESTRICT br,
394
                                 size_t distance_multiplier,
395
                                 AlignedMemory&& lz77_window_storage)
396
720k
    : alias_tables_(code->alias_tables.address<AliasTable::Entry>()),
397
720k
      huffman_data_(code->huffman_data.data()),
398
720k
      use_prefix_code_(code->use_prefix_code),
399
720k
      configs(code->uint_config.data()),
400
720k
      lz77_window_storage_(std::move(lz77_window_storage)) {
401
720k
  if (!use_prefix_code_) {
402
488k
    state_ = static_cast<uint32_t>(br->ReadFixedBits<32>());
403
488k
    log_alpha_size_ = code->log_alpha_size;
404
488k
    log_entry_size_ = ANS_LOG_TAB_SIZE - code->log_alpha_size;
405
488k
    entry_size_minus_1_ = (1 << log_entry_size_) - 1;
406
488k
  } else {
407
231k
    state_ = (ANS_SIGNATURE << 16u);
408
231k
  }
409
720k
  if (!code->lz77.enabled) return;
410
187k
  lz77_window_ = lz77_window_storage_.address<uint32_t>();
411
187k
  lz77_ctx_ = code->lz77.nonserialized_distance_context;
412
187k
  lz77_length_uint_ = code->lz77.length_uint_config;
413
187k
  lz77_threshold_ = code->lz77.min_symbol;
414
187k
  lz77_min_length_ = code->lz77.min_length;
415
187k
  num_special_distances_ = distance_multiplier == 0 ? 0 : kNumSpecialDistances;
416
4.17M
  for (size_t i = 0; i < num_special_distances_; i++) {
417
3.98M
    special_distances_[i] = SpecialDistance(i, distance_multiplier);
418
3.98M
  }
419
187k
}
420
421
}  // namespace jxl