Coverage Report

Created: 2025-10-12 07:48

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