Coverage Report

Created: 2025-12-13 07:57

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