Coverage Report

Created: 2026-06-16 07:20

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