Coverage Report

Created: 2026-07-25 07:03

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