Coverage Report

Created: 2025-08-11 08:01

/src/libjxl/lib/jxl/enc_ans.cc
Line
Count
Source (jump to first uncovered line)
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/enc_ans.h"
7
8
#include <jxl/memory_manager.h>
9
#include <jxl/types.h>
10
11
#include <algorithm>
12
#include <array>
13
#include <cmath>
14
#include <cstddef>
15
#include <cstdint>
16
#include <limits>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/ans_common.h"
21
#include "lib/jxl/ans_params.h"
22
#include "lib/jxl/base/bits.h"
23
#include "lib/jxl/base/common.h"
24
#include "lib/jxl/base/compiler_specific.h"
25
#include "lib/jxl/base/status.h"
26
#include "lib/jxl/common.h"
27
#include "lib/jxl/dec_ans.h"
28
#include "lib/jxl/enc_ans_params.h"
29
#include "lib/jxl/enc_ans_simd.h"
30
#include "lib/jxl/enc_aux_out.h"
31
#include "lib/jxl/enc_cluster.h"
32
#include "lib/jxl/enc_context_map.h"
33
#include "lib/jxl/enc_fields.h"
34
#include "lib/jxl/enc_huffman.h"
35
#include "lib/jxl/enc_lz77.h"
36
#include "lib/jxl/enc_params.h"
37
#include "lib/jxl/fields.h"
38
#include "lib/jxl/memory_manager_internal.h"
39
#include "lib/jxl/modular/options.h"
40
#include "lib/jxl/simd_util.h"
41
42
namespace jxl {
43
44
namespace {
45
46
#if (!JXL_IS_DEBUG_BUILD)
47
constexpr
48
#endif
49
    bool ans_fuzzer_friendly_ = false;
50
51
const int kMaxNumSymbolsForSmallCode = 2;
52
53
template <typename Writer>
54
4.45M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
4.45M
  JXL_DASSERT(n <= 255);
56
4.45M
  if (n == 0) {
57
346k
    writer->Write(1, 0);
58
4.11M
  } else {
59
4.11M
    writer->Write(1, 1);
60
4.11M
    size_t nbits = FloorLog2Nonzero(n);
61
4.11M
    writer->Write(3, nbits);
62
4.11M
    writer->Write(nbits, n - (1ULL << nbits));
63
4.11M
  }
64
4.45M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
54
4.29M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
4.29M
  JXL_DASSERT(n <= 255);
56
4.29M
  if (n == 0) {
57
334k
    writer->Write(1, 0);
58
3.96M
  } else {
59
3.96M
    writer->Write(1, 1);
60
3.96M
    size_t nbits = FloorLog2Nonzero(n);
61
3.96M
    writer->Write(3, nbits);
62
3.96M
    writer->Write(nbits, n - (1ULL << nbits));
63
3.96M
  }
64
4.29M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
54
158k
void StoreVarLenUint8(size_t n, Writer* writer) {
55
158k
  JXL_DASSERT(n <= 255);
56
158k
  if (n == 0) {
57
12.2k
    writer->Write(1, 0);
58
146k
  } else {
59
146k
    writer->Write(1, 1);
60
146k
    size_t nbits = FloorLog2Nonzero(n);
61
146k
    writer->Write(3, nbits);
62
146k
    writer->Write(nbits, n - (1ULL << nbits));
63
146k
  }
64
158k
}
65
66
template <typename Writer>
67
24.4k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
24.4k
  JXL_DASSERT(n <= 65535);
69
24.4k
  if (n == 0) {
70
335
    writer->Write(1, 0);
71
24.1k
  } else {
72
24.1k
    writer->Write(1, 1);
73
24.1k
    size_t nbits = FloorLog2Nonzero(n);
74
24.1k
    writer->Write(4, nbits);
75
24.1k
    writer->Write(nbits, n - (1ULL << nbits));
76
24.1k
  }
77
24.4k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
67
6.90k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
6.90k
  JXL_DASSERT(n <= 65535);
69
6.90k
  if (n == 0) {
70
335
    writer->Write(1, 0);
71
6.56k
  } else {
72
6.56k
    writer->Write(1, 1);
73
6.56k
    size_t nbits = FloorLog2Nonzero(n);
74
6.56k
    writer->Write(4, nbits);
75
6.56k
    writer->Write(nbits, n - (1ULL << nbits));
76
6.56k
  }
77
6.90k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
67
17.5k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
17.5k
  JXL_DASSERT(n <= 65535);
69
17.5k
  if (n == 0) {
70
0
    writer->Write(1, 0);
71
17.5k
  } else {
72
17.5k
    writer->Write(1, 1);
73
17.5k
    size_t nbits = FloorLog2Nonzero(n);
74
17.5k
    writer->Write(4, nbits);
75
17.5k
    writer->Write(nbits, n - (1ULL << nbits));
76
17.5k
  }
77
17.5k
}
78
79
class ANSEncodingHistogram {
80
 public:
81
119k
  const std::vector<ANSHistBin>& Counts() const { return counts_; }
82
607k
  float Cost() const { return cost_; }
83
  // The only way to construct valid histogram for ANS encoding
84
  static StatusOr<ANSEncodingHistogram> ComputeBest(
85
      const Histogram& histo,
86
607k
      HistogramParams::ANSHistogramStrategy ans_histogram_strategy) {
87
607k
    ANSEncodingHistogram result;
88
89
607k
    result.alphabet_size_ = histo.alphabet_size();
90
607k
    if (result.alphabet_size_ > ANS_MAX_ALPHABET_SIZE)
91
0
      return JXL_FAILURE("Too many entries in an ANS histogram");
92
93
607k
    if (result.alphabet_size_ > 0) {
94
      // Flat code
95
607k
      result.method_ = 0;
96
607k
      result.num_symbols_ = result.alphabet_size_;
97
607k
      result.counts_ = CreateFlatHistogram(result.alphabet_size_, ANS_TAB_SIZE);
98
      // in this case length can be non-suitable for SIMD - fix it
99
607k
      result.counts_.resize(histo.counts.size());
100
607k
      SizeWriter writer;
101
607k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
102
607k
      result.cost_ = writer.size + EstimateDataBitsFlat(histo);
103
607k
    } else {
104
      // Empty histogram
105
0
      result.method_ = 1;
106
0
      result.num_symbols_ = 0;
107
0
      result.cost_ = 3;
108
0
      return result;
109
0
    }
110
111
607k
    size_t symbol_count = 0;
112
20.7M
    for (size_t n = 0; n < result.alphabet_size_; ++n) {
113
20.1M
      if (histo.counts[n] > 0) {
114
9.74M
        if (symbol_count < kMaxNumSymbolsForSmallCode) {
115
1.16M
          result.symbols_[symbol_count] = n;
116
1.16M
        }
117
9.74M
        ++symbol_count;
118
9.74M
      }
119
20.1M
    }
120
607k
    result.num_symbols_ = symbol_count;
121
607k
    if (symbol_count == 1) {
122
      // Single-bin histogram
123
53.8k
      result.method_ = 1;
124
53.8k
      result.counts_ = histo.counts;
125
53.8k
      result.counts_[result.symbols_[0]] = ANS_TAB_SIZE;
126
53.8k
      SizeWriter writer;
127
53.8k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
128
53.8k
      result.cost_ = writer.size;
129
53.8k
      return result;
130
53.8k
    }
131
132
    // Here min 2 symbols
133
553k
    ANSEncodingHistogram normalized = result;
134
2.17M
    auto try_shift = [&](uint32_t shift) -> Status {
135
      // `shift = 12` and `shift = 11` are the same
136
2.17M
      normalized.method_ = std::min(shift, ANS_LOG_TAB_SIZE - 1) + 1;
137
138
2.17M
      if (!normalized.RebalanceHistogram(histo)) {
139
0
        return JXL_FAILURE("Logic error: couldn't rebalance a histogram");
140
0
      }
141
2.17M
      SizeWriter writer;
142
2.17M
      JXL_RETURN_IF_ERROR(normalized.Encode(&writer));
143
2.17M
      normalized.cost_ = writer.size + normalized.EstimateDataBits(histo);
144
2.17M
      if (normalized.cost_ < result.cost_) {
145
557k
        result = normalized;
146
557k
      }
147
2.17M
      return true;
148
2.17M
    };
149
150
553k
    switch (ans_histogram_strategy) {
151
11.3k
      case HistogramParams::ANSHistogramStrategy::kPrecise:
152
148k
        for (uint32_t shift = 0; shift < ANS_LOG_TAB_SIZE; shift++) {
153
136k
          JXL_RETURN_IF_ERROR(try_shift(shift));
154
136k
        }
155
11.3k
        break;
156
103k
      case HistogramParams::ANSHistogramStrategy::kApproximate:
157
827k
        for (uint32_t shift = 0; shift <= ANS_LOG_TAB_SIZE; shift += 2) {
158
723k
          JXL_RETURN_IF_ERROR(try_shift(shift));
159
723k
        }
160
103k
        break;
161
439k
      case HistogramParams::ANSHistogramStrategy::kFast:
162
439k
        JXL_RETURN_IF_ERROR(try_shift(0));
163
439k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE / 2));
164
439k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE));
165
439k
        break;
166
553k
    }
167
168
      // Sanity check
169
553k
#if JXL_IS_DEBUG_BUILD
170
553k
    JXL_ENSURE(histo.counts.size() == result.counts_.size());
171
553k
    ANSHistBin total = 0;  // Used only in assert.
172
20.5M
    for (size_t i = 0; i < result.alphabet_size_; ++i) {
173
19.9M
      JXL_ENSURE(result.counts_[i] >= 0);
174
      // For non-flat histogram values should be zero or non-zero simultaneously
175
      // for the same symbol in both initial and normalized histograms.
176
19.9M
      JXL_ENSURE(result.method_ == 0 ||
177
19.9M
                 (histo.counts[i] > 0) == (result.counts_[i] > 0));
178
      // Check accuracy of the histogram values
179
19.9M
      if (result.method_ > 0 && result.counts_[i] > 0 &&
180
19.9M
          i != result.omit_pos_) {
181
7.07M
        int logcounts = FloorLog2Nonzero<uint32_t>(result.counts_[i]);
182
7.07M
        int bitcount =
183
7.07M
            GetPopulationCountPrecision(logcounts, result.method_ - 1);
184
7.07M
        int drop_bits = logcounts - bitcount;
185
        // Check that the value is divisible by 2^drop_bits
186
7.07M
        JXL_ENSURE((result.counts_[i] & ((1 << drop_bits) - 1)) == 0);
187
7.07M
      }
188
19.9M
      total += result.counts_[i];
189
19.9M
    }
190
2.40M
    for (size_t i = result.alphabet_size_; i < result.counts_.size(); ++i) {
191
1.85M
      JXL_ENSURE(histo.counts[i] == 0);
192
1.85M
      JXL_ENSURE(result.counts_[i] == 0);
193
1.85M
    }
194
553k
    JXL_ENSURE((histo.total_count == 0) || (total == ANS_TAB_SIZE));
195
553k
#endif
196
553k
    return result;
197
553k
  }
198
199
  template <typename Writer>
200
2.95M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
2.95M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
2.95M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
611k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
611k
      writer->Write(1, 1);
211
611k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
611k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
611k
      return true;
216
611k
    }
217
218
    /// Small tree.
219
2.34M
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
74.3k
      writer->Write(1, 1);
222
74.3k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
74.3k
      } else {
226
74.3k
        writer->Write(1, num_symbols_ - 1);
227
165k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
91.4k
          StoreVarLenUint8(symbols_[i], writer);
229
91.4k
        }
230
74.3k
      }
231
74.3k
      if (num_symbols_ == 2) {
232
17.0k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
17.0k
      }
234
235
74.3k
      return true;
236
74.3k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
2.26M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
2.26M
    writer->Write(1, 0);
243
244
    // Elias gamma-like code for `shift = method - 1`. Only difference is that
245
    // if the number of bits to be encoded is equal to `upper_bound_log`,
246
    // we skip the terminating 0 in unary coding.
247
2.26M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
2.26M
    int log = FloorLog2Nonzero(method_);
249
2.26M
    writer->Write(log, (1 << log) - 1);
250
2.26M
    if (log != upper_bound_log) writer->Write(1, 0);
251
2.26M
    writer->Write(log, ((1 << log) - 1) & method_);
252
253
    // Since `num_symbols_ >= 3`, we know that `alphabet_size_ >= 3`, therefore
254
    // we encode `alphabet_size_ - 3`.
255
2.26M
    StoreVarLenUint8(alphabet_size_ - 3, writer);
256
257
    // Precompute sequences for RLE encoding. Contains the number of identical
258
    // values starting at a given index. Only contains that value at the first
259
    // element of the series.
260
2.26M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
2.26M
    size_t last = 0;
262
84.1M
    for (size_t i = 1; i <= alphabet_size_; i++) {
263
      // Store the sequence length once different symbol reached, or we are
264
      // near the omit_pos_, or we're at the end. We don't support including the
265
      // omit_pos_ in an RLE sequence because this value may use a different
266
      // amount of log2 bits than standard, it is too complex to handle in the
267
      // decoder.
268
81.8M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
81.8M
          counts_[i] != counts_[last]) {
270
43.2M
        same[last] = i - last;
271
43.2M
        last = i;
272
43.2M
      }
273
81.8M
    }
274
275
2.26M
    uint8_t bit_width[ANS_MAX_ALPHABET_SIZE] = {};
276
    // Use shortest possible Huffman code to encode `omit_pos` (see
277
    // `kBitWidthLengths`). `bit_width` value at `omit_pos` should be the
278
    // first of maximal values in the whole `bit_width` array, so it can be
279
    // increased without changing that property
280
2.26M
    int omit_width = 10;
281
84.1M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
81.8M
      if (i != omit_pos_ && counts_[i] > 0) {
283
36.6M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
36.6M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
36.6M
      }
286
81.8M
    }
287
2.26M
    bit_width[omit_pos_] = static_cast<uint8_t>(omit_width);
288
289
    // The bit widths are encoded with a static Huffman code.
290
    // The last symbol is used as RLE sequence.
291
2.26M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
2.26M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
2.26M
    };
294
2.26M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
2.26M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
2.26M
    };
297
2.26M
    constexpr uint8_t kMinReps = 5;
298
2.26M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
54.2M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
51.9M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
51.9M
                    kBitWidthSymbols[bit_width[i]]);
303
51.9M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.48M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.48M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.48M
        i += same[i] - 1;
308
1.48M
      }
309
51.9M
    }
310
    // Encode additional bits of accuracy
311
2.26M
    uint32_t shift = method_ - 1;
312
2.26M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
39.4M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
37.7M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
26.0M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
26.0M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
26.0M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
26.0M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
26.0M
        }
320
37.7M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.03M
          i += same[i] - 1;
323
1.03M
        }
324
37.7M
      }
325
1.65M
    }
326
2.26M
    return true;
327
2.26M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::SizeWriter>(jxl::SizeWriter*)
Line
Count
Source
200
2.83M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
2.83M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
2.83M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
607k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
607k
      writer->Write(1, 1);
211
607k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
607k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
607k
      return true;
216
607k
    }
217
218
    /// Small tree.
219
2.23M
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
70.3k
      writer->Write(1, 1);
222
70.3k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
70.3k
      } else {
226
70.3k
        writer->Write(1, num_symbols_ - 1);
227
157k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
86.9k
          StoreVarLenUint8(symbols_[i], writer);
229
86.9k
        }
230
70.3k
      }
231
70.3k
      if (num_symbols_ == 2) {
232
16.5k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
16.5k
      }
234
235
70.3k
      return true;
236
70.3k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
2.16M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
2.16M
    writer->Write(1, 0);
243
244
    // Elias gamma-like code for `shift = method - 1`. Only difference is that
245
    // if the number of bits to be encoded is equal to `upper_bound_log`,
246
    // we skip the terminating 0 in unary coding.
247
2.16M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
2.16M
    int log = FloorLog2Nonzero(method_);
249
2.16M
    writer->Write(log, (1 << log) - 1);
250
2.16M
    if (log != upper_bound_log) writer->Write(1, 0);
251
2.16M
    writer->Write(log, ((1 << log) - 1) & method_);
252
253
    // Since `num_symbols_ >= 3`, we know that `alphabet_size_ >= 3`, therefore
254
    // we encode `alphabet_size_ - 3`.
255
2.16M
    StoreVarLenUint8(alphabet_size_ - 3, writer);
256
257
    // Precompute sequences for RLE encoding. Contains the number of identical
258
    // values starting at a given index. Only contains that value at the first
259
    // element of the series.
260
2.16M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
2.16M
    size_t last = 0;
262
81.1M
    for (size_t i = 1; i <= alphabet_size_; i++) {
263
      // Store the sequence length once different symbol reached, or we are
264
      // near the omit_pos_, or we're at the end. We don't support including the
265
      // omit_pos_ in an RLE sequence because this value may use a different
266
      // amount of log2 bits than standard, it is too complex to handle in the
267
      // decoder.
268
78.9M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
78.9M
          counts_[i] != counts_[last]) {
270
41.4M
        same[last] = i - last;
271
41.4M
        last = i;
272
41.4M
      }
273
78.9M
    }
274
275
2.16M
    uint8_t bit_width[ANS_MAX_ALPHABET_SIZE] = {};
276
    // Use shortest possible Huffman code to encode `omit_pos` (see
277
    // `kBitWidthLengths`). `bit_width` value at `omit_pos` should be the
278
    // first of maximal values in the whole `bit_width` array, so it can be
279
    // increased without changing that property
280
2.16M
    int omit_width = 10;
281
81.1M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
78.9M
      if (i != omit_pos_ && counts_[i] > 0) {
283
35.1M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
35.1M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
35.1M
      }
286
78.9M
    }
287
2.16M
    bit_width[omit_pos_] = static_cast<uint8_t>(omit_width);
288
289
    // The bit widths are encoded with a static Huffman code.
290
    // The last symbol is used as RLE sequence.
291
2.16M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
2.16M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
2.16M
    };
294
2.16M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
2.16M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
2.16M
    };
297
2.16M
    constexpr uint8_t kMinReps = 5;
298
2.16M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
51.9M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
49.8M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
49.8M
                    kBitWidthSymbols[bit_width[i]]);
303
49.8M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.44M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.44M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.44M
        i += same[i] - 1;
308
1.44M
      }
309
49.8M
    }
310
    // Encode additional bits of accuracy
311
2.16M
    uint32_t shift = method_ - 1;
312
2.16M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
38.5M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
36.9M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
25.5M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
25.5M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
25.5M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
25.5M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
25.5M
        }
320
36.9M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.01M
          i += same[i] - 1;
323
1.01M
        }
324
36.9M
      }
325
1.61M
    }
326
2.16M
    return true;
327
2.16M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::BitWriter>(jxl::BitWriter*)
Line
Count
Source
200
115k
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
115k
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
115k
    if (method_ == 0) {
207
      // Mark non-small tree.
208
3.72k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
3.72k
      writer->Write(1, 1);
211
3.72k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
3.72k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
3.72k
      return true;
216
3.72k
    }
217
218
    /// Small tree.
219
111k
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
3.96k
      writer->Write(1, 1);
222
3.96k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
3.96k
      } else {
226
3.96k
        writer->Write(1, num_symbols_ - 1);
227
8.49k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
4.53k
          StoreVarLenUint8(symbols_[i], writer);
229
4.53k
        }
230
3.96k
      }
231
3.96k
      if (num_symbols_ == 2) {
232
571
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
571
      }
234
235
3.96k
      return true;
236
3.96k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
107k
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
107k
    writer->Write(1, 0);
243
244
    // Elias gamma-like code for `shift = method - 1`. Only difference is that
245
    // if the number of bits to be encoded is equal to `upper_bound_log`,
246
    // we skip the terminating 0 in unary coding.
247
107k
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
107k
    int log = FloorLog2Nonzero(method_);
249
107k
    writer->Write(log, (1 << log) - 1);
250
107k
    if (log != upper_bound_log) writer->Write(1, 0);
251
107k
    writer->Write(log, ((1 << log) - 1) & method_);
252
253
    // Since `num_symbols_ >= 3`, we know that `alphabet_size_ >= 3`, therefore
254
    // we encode `alphabet_size_ - 3`.
255
107k
    StoreVarLenUint8(alphabet_size_ - 3, writer);
256
257
    // Precompute sequences for RLE encoding. Contains the number of identical
258
    // values starting at a given index. Only contains that value at the first
259
    // element of the series.
260
107k
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
107k
    size_t last = 0;
262
2.98M
    for (size_t i = 1; i <= alphabet_size_; i++) {
263
      // Store the sequence length once different symbol reached, or we are
264
      // near the omit_pos_, or we're at the end. We don't support including the
265
      // omit_pos_ in an RLE sequence because this value may use a different
266
      // amount of log2 bits than standard, it is too complex to handle in the
267
      // decoder.
268
2.87M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
2.87M
          counts_[i] != counts_[last]) {
270
1.75M
        same[last] = i - last;
271
1.75M
        last = i;
272
1.75M
      }
273
2.87M
    }
274
275
107k
    uint8_t bit_width[ANS_MAX_ALPHABET_SIZE] = {};
276
    // Use shortest possible Huffman code to encode `omit_pos` (see
277
    // `kBitWidthLengths`). `bit_width` value at `omit_pos` should be the
278
    // first of maximal values in the whole `bit_width` array, so it can be
279
    // increased without changing that property
280
107k
    int omit_width = 10;
281
2.98M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
2.87M
      if (i != omit_pos_ && counts_[i] > 0) {
283
1.54M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
1.54M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
1.54M
      }
286
2.87M
    }
287
107k
    bit_width[omit_pos_] = static_cast<uint8_t>(omit_width);
288
289
    // The bit widths are encoded with a static Huffman code.
290
    // The last symbol is used as RLE sequence.
291
107k
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
107k
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
107k
    };
294
107k
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
107k
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
107k
    };
297
107k
    constexpr uint8_t kMinReps = 5;
298
107k
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
2.25M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
2.15M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
2.15M
                    kBitWidthSymbols[bit_width[i]]);
303
2.15M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
42.7k
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
42.7k
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
42.7k
        i += same[i] - 1;
308
42.7k
      }
309
2.15M
    }
310
    // Encode additional bits of accuracy
311
107k
    uint32_t shift = method_ - 1;
312
107k
    if (shift != 0) {  // otherwise `bitcount = 0`
313
881k
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
840k
        if (bit_width[i] > 1 && i != omit_pos_) {
315
580k
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
580k
          int drop_bits = bit_width[i] - 1 - bitcount;
317
580k
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
580k
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
580k
        }
320
840k
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
16.3k
          i += same[i] - 1;
323
16.3k
        }
324
840k
      }
325
41.7k
    }
326
107k
    return true;
327
107k
  }
328
329
  void ANSBuildInfoTable(const AliasTable::Entry* table, size_t log_alpha_size,
330
119k
                         ANSEncSymbolInfo* info) {
331
    // Create valid alias table for empty streams
332
3.56M
    for (size_t s = 0; s < std::max(size_t{1}, alphabet_size_); ++s) {
333
3.44M
      const ANSHistBin freq = s == alphabet_size_ ? ANS_TAB_SIZE : counts_[s];
334
3.44M
      info[s].freq_ = static_cast<uint16_t>(freq);
335
3.44M
#ifdef USE_MULT_BY_RECIPROCAL
336
3.44M
      if (freq != 0) {
337
1.86M
        info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) /
338
1.86M
                         info[s].freq_;
339
1.86M
      } else {
340
1.58M
        info[s].ifreq_ =
341
1.58M
            1;  // Shouldn't matter (symbol shouldn't occur), but...
342
1.58M
      }
343
3.44M
#endif
344
3.44M
      info[s].reverse_map_.resize(freq);
345
3.44M
    }
346
119k
    size_t log_entry_size = ANS_LOG_TAB_SIZE - log_alpha_size;
347
119k
    size_t entry_size_minus_1 = (1 << log_entry_size) - 1;
348
490M
    for (int i = 0; i < ANS_TAB_SIZE; i++) {
349
490M
      AliasTable::Symbol s =
350
490M
          AliasTable::Lookup(table, i, log_entry_size, entry_size_minus_1);
351
490M
      info[s.value].reverse_map_[s.offset] = i;
352
490M
    }
353
119k
  }
354
355
 private:
356
607k
  ANSEncodingHistogram() {}
357
358
  // Fixed-point log2 LUT for values of [0,4096]
359
  using Lg2LUT = std::array<uint32_t, ANS_TAB_SIZE + 1>;
360
  static const Lg2LUT lg2;
361
362
2.17M
  float EstimateDataBits(const Histogram& histo) {
363
2.17M
    int64_t sum = 0;
364
81.2M
    for (size_t i = 0; i < alphabet_size_; ++i) {
365
      // += histogram[i] * -log(counts[i]/total_counts)
366
79.1M
      sum += histo.counts[i] * int64_t{lg2[counts_[i]]};
367
79.1M
    }
368
2.17M
    return (histo.total_count - ldexpf(sum, -31)) * ANS_LOG_TAB_SIZE;
369
2.17M
  }
370
371
607k
  static float EstimateDataBitsFlat(const Histogram& histo) {
372
607k
    size_t len = histo.alphabet_size();
373
607k
    int64_t flat_bits = int64_t{lg2[len]} * ANS_LOG_TAB_SIZE;
374
607k
    return ldexpf(histo.total_count * flat_bits, -31);
375
607k
  }
376
377
  struct CountsEntropy {
378
    ANSHistBin count : 16;     // allowed value of counts in a histogram bin
379
    ANSHistBin step_log : 16;  // log2 of increase step size (can use 5 bits)
380
    int32_t delta_lg2;  // change of log between that value and the next allowed
381
  };
382
383
  // Array is sorted by decreasing allowed counts for each possible shift.
384
  // Exclusion of single-bin histograms before `RebalanceHistogram` allows
385
  // to put count upper limit of 4095, and shifts of 11 and 12 produce the
386
  // same table
387
  using CountsArray =
388
      std::array<std::array<CountsEntropy, ANS_TAB_SIZE>, ANS_LOG_TAB_SIZE>;
389
  using CountsIndex =
390
      std::array<std::array<uint16_t, ANS_TAB_SIZE>, ANS_LOG_TAB_SIZE>;
391
  struct AllowedCounts {
392
    CountsArray array;
393
    CountsIndex index;
394
  };
395
  static const AllowedCounts allowed_counts;
396
397
  // Returns the difference between largest count that can be represented and is
398
  // smaller than "count" and smallest representable count larger than "count".
399
91.3M
  static uint32_t SmallestIncrementLog(uint32_t count, uint32_t shift) {
400
91.3M
    if (count == 0) return 0;
401
49.6M
    uint32_t bits = FloorLog2Nonzero(count);
402
49.6M
    uint32_t drop_bits = bits - GetPopulationCountPrecision(bits, shift);
403
49.6M
    return drop_bits;
404
91.3M
  }
405
  // We are growing/reducing histogram step by step trying to maximize total
406
  // entropy i.e. sum of `freq[n] * log[counts[n]]` with a given sum of
407
  // `counts[n]` chosen from `allowed_counts[shift]`. This sum is balanced by
408
  // the `counts[omit_pos_]` in the highest bin of histogram. We start from
409
  // close to correct solution and each time a step with maximum entropy
410
  // increase per unit of bin change is chosen. This greedy scheme is not
411
  // guaranteed to achieve the global maximum, but cannot produce invalid
412
  // histogram. We use a fixed-point approximation for logarithms and all
413
  // arithmetic is integer besides initial approximation. Sum of `freq` and each
414
  // of `lg2[counts]` are supposed to be limited to `int32_t` range, so that the
415
  // sum of their products should not exceed `int64_t`.
416
2.17M
  bool RebalanceHistogram(const Histogram& histo) {
417
2.17M
    constexpr ANSHistBin table_size = ANS_TAB_SIZE;
418
2.17M
    uint32_t shift = method_ - 1;
419
420
2.17M
    struct EntropyDelta {
421
2.17M
      ANSHistBin freq;   // initial count
422
2.17M
      size_t count_ind;  // index of current bin value in `allowed_counts`
423
2.17M
      size_t bin_ind;    // index of current bin in `counts`
424
2.17M
    };
425
    // Penalties corresponding to different step sizes - entropy decrease in
426
    // balancing bin, step of size (1 << ANS_LOG_TAB_SIZE - 1) is not possible
427
2.17M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_inc = {};
428
2.17M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_dec = {};
429
2.17M
    const auto& ac = allowed_counts.array[shift];
430
2.17M
    const auto& ai = allowed_counts.index[shift];
431
    // TODO(ivan) separate cases of shift >= 11 - all steps are 1 there, and
432
    // possibly 10 - all relevant steps are 2.
433
    // Total entropy change by a step: increase/decrease in current bin
434
    // together with corresponding decrease/increase in the balancing bin.
435
    // Inc steps increase current bin, dec steps decrease
436
692M
    const auto delta_entropy_inc = [&](const EntropyDelta& a) {
437
692M
      return a.freq * int64_t{ac[a.count_ind].delta_lg2} -
438
692M
             balance_inc[ac[a.count_ind].step_log];
439
692M
    };
440
102M
    const auto delta_entropy_dec = [&](const EntropyDelta& a) {
441
102M
      return a.freq * int64_t{ac[a.count_ind + 1].delta_lg2} -
442
102M
             balance_dec[ac[a.count_ind + 1].step_log];
443
102M
    };
444
    // Compare steps by entropy increase per unit of histogram bin change.
445
    // Truncation is OK here, accuracy is anyway better than float
446
339M
    const auto IncLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
447
339M
      return delta_entropy_inc(a) >> ac[a.count_ind].step_log <
448
339M
             delta_entropy_inc(b) >> ac[b.count_ind].step_log;
449
339M
    };
450
49.7M
    const auto DecLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
451
49.7M
      return delta_entropy_dec(a) >> ac[a.count_ind + 1].step_log <
452
49.7M
             delta_entropy_dec(b) >> ac[b.count_ind + 1].step_log;
453
49.7M
    };
454
    // Vector of adjustable bins from `allowed_counts`
455
2.17M
    std::vector<EntropyDelta> bins;
456
2.17M
    bins.reserve(256);
457
458
2.17M
    double norm = double{table_size} / histo.total_count;
459
460
2.17M
    size_t remainder_pos = 0;  // highest balancing bin in the histogram
461
2.17M
    int64_t max_freq = 0;
462
2.17M
    ANSHistBin rest = table_size;  // reserve of histogram counts to distribute
463
81.2M
    for (size_t n = 0; n < alphabet_size_; ++n) {
464
79.1M
      ANSHistBin freq = histo.counts[n];
465
79.1M
      if (freq > max_freq) {
466
4.60M
        remainder_pos = n;
467
4.60M
        max_freq = freq;
468
4.60M
      }
469
470
79.1M
      double target = freq * norm;  // rounding
471
      // Keep zeros and clamp nonzero freq counts to [1, table_size)
472
79.1M
      ANSHistBin count = std::max<ANSHistBin>(round(target), freq > 0);
473
79.1M
      count = std::min<ANSHistBin>(count, table_size - 1);
474
79.1M
      uint32_t step_log = SmallestIncrementLog(count, shift);
475
79.1M
      ANSHistBin inc = 1 << step_log;
476
79.1M
      count &= ~(inc - 1);
477
478
79.1M
      counts_[n] = count;
479
79.1M
      rest -= count;
480
79.1M
      if (target > 1.0) {
481
37.0M
        bins.push_back({freq, ai[count], n});
482
37.0M
      }
483
79.1M
    }
484
485
    // Delete the highest balancing bin from adjustable by `allowed_counts`
486
2.17M
    bins.erase(std::find_if(
487
2.17M
        bins.begin(), bins.end(),
488
11.6M
        [&](const EntropyDelta& a) { return a.bin_ind == remainder_pos; }));
489
    // From now on `rest` is the height of balancing bin,
490
    // here it can be negative, but will be tracted into positive domain later
491
2.17M
    rest += counts_[remainder_pos];
492
493
2.17M
    if (!bins.empty()) {
494
2.17M
      const uint32_t max_log = ac[1].step_log;
495
13.4M
      while (true) {
496
        // Update balancing bin penalties setting guards and tractors
497
118M
        for (uint32_t log = 0; log <= max_log; ++log) {
498
105M
          ANSHistBin delta = 1 << log;
499
105M
          if (rest >= table_size) {
500
            // Tract large `rest` into allowed domain:
501
0
            balance_inc[log] = 0;  // permit all inc steps
502
0
            balance_dec[log] = 0;  // forbid all dec steps
503
105M
          } else if (rest > 1) {
504
            // `rest` is OK, put guards against non-possible steps
505
105M
            balance_inc[log] =
506
105M
                rest > delta  // possible step
507
105M
                    ? max_freq * int64_t{lg2[rest] - lg2[rest - delta]}
508
105M
                    : std::numeric_limits<int64_t>::max();  // forbidden
509
105M
            balance_dec[log] =
510
105M
                rest + delta < table_size  // possible step
511
105M
                    ? max_freq * int64_t{lg2[rest + delta] - lg2[rest]}
512
105M
                    : 0;  // forbidden
513
105M
          } else {
514
            // Tract negative or zero `rest` into positive:
515
            // forbid all inc steps
516
276
            balance_inc[log] = std::numeric_limits<int64_t>::max();
517
            // permit all dec steps
518
276
            balance_dec[log] = std::numeric_limits<int64_t>::max();
519
276
          }
520
105M
        }
521
        // Try to increase entropy
522
13.4M
        auto best_bin_inc = std::max_element(bins.begin(), bins.end(), IncLess);
523
13.4M
        if (delta_entropy_inc(*best_bin_inc) > 0) {
524
          // Grow the bin with the best histogram entropy increase
525
10.6M
          rest -= 1 << ac[best_bin_inc->count_ind--].step_log;
526
10.6M
        } else {
527
          // This still implies that entropy is strictly increasing each step
528
          // (or `rest` is tracted into positive domain), so we cannot loop
529
          // infinitely
530
2.78M
          auto best_bin_dec =
531
2.78M
              std::min_element(bins.begin(), bins.end(), DecLess);
532
          // Break if no reverse steps can grow entropy (or valid)
533
2.78M
          if (delta_entropy_dec(*best_bin_dec) >= 0) break;
534
          // Decrease the bin with the best histogram entropy increase
535
611k
          rest += 1 << ac[++best_bin_dec->count_ind].step_log;
536
611k
        }
537
13.4M
      }
538
      // Set counts besides the balancing bin
539
34.8M
      for (auto& a : bins) counts_[a.bin_ind] = ac[a.count_ind].count;
540
541
      // The scheme works fine if we have room to grow `bit_width` of balancing
542
      // bin, otherwise we need to put balancing bin to the first bin of 12 bit
543
      // width. In this case both that bin and balancing one should be close to
544
      // 2048 in targets, so exchange of them will not produce much worse
545
      // histogram
546
19.2M
      for (size_t n = 0; n < remainder_pos; ++n) {
547
17.0M
        if (counts_[n] >= 2048) {
548
5.88k
          counts_[remainder_pos] = counts_[n];
549
5.88k
          remainder_pos = n;
550
5.88k
          break;
551
5.88k
        }
552
17.0M
      }
553
2.17M
    }
554
    // Set balancing bin
555
2.17M
    counts_[remainder_pos] = rest;
556
2.17M
    omit_pos_ = remainder_pos;
557
558
2.17M
    return counts_[remainder_pos] > 0;
559
2.17M
  }
560
561
  float cost_ = 0;
562
  uint32_t method_ = 0;
563
  size_t omit_pos_ = 0;
564
  size_t alphabet_size_ = 0;
565
  size_t num_symbols_ = 0;
566
  size_t symbols_[kMaxNumSymbolsForSmallCode] = {};
567
  std::vector<ANSHistBin> counts_{};
568
};
569
570
using AEH = ANSEncodingHistogram;
571
572
250
const AEH::Lg2LUT AEH::lg2 = [] {
573
250
  Lg2LUT lg2;
574
250
  lg2[0] = 0;  // for entropy calculations it is OK
575
1.02M
  for (size_t i = 1; i < lg2.size(); ++i) {
576
1.02M
    lg2[i] = round(ldexp(log2(i) / ANS_LOG_TAB_SIZE, 31));
577
1.02M
  }
578
250
  return lg2;
579
250
}();
580
581
250
const AEH::AllowedCounts AEH::allowed_counts = [] {
582
250
  AllowedCounts result;
583
584
3.25k
  for (uint32_t shift = 0; shift < result.array.size(); ++shift) {
585
3.00k
    auto& ac = result.array[shift];
586
3.00k
    auto& ai = result.index[shift];
587
3.00k
    ANSHistBin last = ~0;
588
3.00k
    size_t slot = 0;
589
    // TODO(eustas): are those "default" values relevant?
590
3.00k
    ac[0].delta_lg2 = 0;
591
3.00k
    ac[0].step_log = 0;
592
12.2M
    for (int32_t i = ac.size() - 1; i >= 0; --i) {
593
12.2M
      int32_t curr = i & ~((1 << SmallestIncrementLog(i, shift)) - 1);
594
12.2M
      if (curr == last) continue;
595
2.39M
      last = curr;
596
2.39M
      ac[slot].count = curr;
597
2.39M
      ai[curr] = slot;
598
2.39M
      if (curr == 0) {
599
        // Guards against non-possible steps:
600
        // at max value [0] - 0 (by init), at min value - max
601
3.00k
        ac[slot].delta_lg2 = std::numeric_limits<int32_t>::max();
602
3.00k
        ac[slot].step_log = 0;
603
2.39M
      } else if (slot > 0) {
604
2.39M
        ANSHistBin prev = ac[slot - 1].count;
605
2.39M
        ac[slot].delta_lg2 = round(ldexp(
606
2.39M
            log2(static_cast<double>(prev) / curr) / ANS_LOG_TAB_SIZE, 31));
607
2.39M
        ac[slot].step_log = FloorLog2Nonzero<uint32_t>(prev - curr);
608
2.39M
        prev = curr;
609
2.39M
      }
610
2.39M
      slot++;
611
2.39M
    }
612
3.00k
  }
613
614
250
  return result;
615
250
}();
616
617
}  // namespace
618
619
488k
StatusOr<float> Histogram::ANSPopulationCost() const {
620
488k
  if (counts.size() > ANS_MAX_ALPHABET_SIZE) {
621
0
    return std::numeric_limits<float>::max();
622
0
  }
623
488k
  JXL_ASSIGN_OR_RETURN(
624
488k
      ANSEncodingHistogram normalized,
625
488k
      ANSEncodingHistogram::ComputeBest(
626
488k
          *this, HistogramParams::ANSHistogramStrategy::kFast));
627
488k
  return normalized.Cost();
628
488k
}
629
630
// Returns an estimate or exact cost of encoding this histogram and the
631
// corresponding data.
632
StatusOr<size_t> EntropyEncodingData::BuildAndStoreANSEncodingData(
633
    JxlMemoryManager* memory_manager,
634
    HistogramParams::ANSHistogramStrategy ans_histogram_strategy,
635
144k
    const Histogram& histogram, BitWriter* writer) {
636
144k
  ANSEncSymbolInfo* info = encoding_info.back().data();
637
144k
  size_t size = histogram.alphabet_size();
638
144k
  if (use_prefix_code) {
639
24.4k
    size_t cost = 0;
640
24.4k
    if (size <= 1) return 0;
641
24.1k
    std::vector<uint32_t> histo(size);
642
203k
    for (size_t i = 0; i < size; i++) {
643
179k
      JXL_ENSURE(histogram.counts[i] >= 0);
644
179k
      histo[i] = histogram.counts[i];
645
179k
    }
646
24.1k
    std::vector<uint8_t> depths(size);
647
24.1k
    std::vector<uint16_t> bits(size);
648
24.1k
    if (writer == nullptr) {
649
17.5k
      BitWriter tmp_writer{memory_manager};
650
17.5k
      JXL_RETURN_IF_ERROR(tmp_writer.WithMaxBits(
651
17.5k
          8 * size + 8,  // safe upper bound
652
17.5k
          LayerType::Header, /*aux_out=*/nullptr, [&] {
653
17.5k
            return BuildAndStoreHuffmanTree(histo.data(), size, depths.data(),
654
17.5k
                                            bits.data(), &tmp_writer);
655
17.5k
          }));
656
17.5k
      cost = tmp_writer.BitsWritten();
657
17.5k
    } else {
658
6.56k
      size_t start = writer->BitsWritten();
659
6.56k
      JXL_RETURN_IF_ERROR(BuildAndStoreHuffmanTree(
660
6.56k
          histo.data(), size, depths.data(), bits.data(), writer));
661
6.56k
      cost = writer->BitsWritten() - start;
662
6.56k
    }
663
203k
    for (size_t i = 0; i < size; i++) {
664
179k
      info[i].bits = depths[i] == 0 ? 0 : bits[i];
665
179k
      info[i].depth = depths[i];
666
179k
    }
667
    // Estimate data cost.
668
203k
    for (size_t i = 0; i < size; i++) {
669
179k
      cost += histo[i] * info[i].depth;
670
179k
    }
671
24.1k
    return cost;
672
24.1k
  }
673
239k
  JXL_ASSIGN_OR_RETURN(
674
239k
      ANSEncodingHistogram normalized,
675
239k
      ANSEncodingHistogram::ComputeBest(histogram, ans_histogram_strategy));
676
239k
  AliasTable::Entry a[ANS_MAX_ALPHABET_SIZE];
677
239k
  JXL_RETURN_IF_ERROR(
678
239k
      InitAliasTable(normalized.Counts(), ANS_LOG_TAB_SIZE, log_alpha_size, a));
679
119k
  normalized.ANSBuildInfoTable(a, log_alpha_size, info);
680
119k
  if (writer != nullptr) {
681
    // size_t start = writer->BitsWritten();
682
115k
    JXL_RETURN_IF_ERROR(normalized.Encode(writer));
683
    // return writer->BitsWritten() - start;
684
115k
  }
685
119k
  return static_cast<size_t>(ceilf(normalized.Cost()));
686
119k
}
687
688
namespace {
689
690
Histogram HistogramFromSymbolInfo(
691
0
    const std::vector<ANSEncSymbolInfo>& encoding_info, bool use_prefix_code) {
692
0
  Histogram histo;
693
0
  histo.counts.resize(DivCeil(encoding_info.size(), Histogram::kRounding) *
694
0
                      Histogram::kRounding);
695
0
  histo.total_count = 0;
696
0
  for (size_t i = 0; i < encoding_info.size(); ++i) {
697
0
    const ANSEncSymbolInfo& info = encoding_info[i];
698
0
    int count = use_prefix_code
699
0
                    ? (info.depth ? (1u << (PREFIX_MAX_BITS - info.depth)) : 0)
700
0
                    : info.freq_;
701
0
    histo.counts[i] = count;
702
0
    histo.total_count += count;
703
0
  }
704
0
  return histo;
705
0
}
706
707
}  // namespace
708
709
Status EntropyEncodingData::ChooseUintConfigs(
710
    JxlMemoryManager* memory_manager, const HistogramParams& params,
711
    const std::vector<std::vector<Token>>& tokens,
712
37.7k
    std::vector<Histogram>& clustered_histograms) {
713
  // Set sane default `log_alpha_size`.
714
37.7k
  if (use_prefix_code) {
715
24.3k
    log_alpha_size = PREFIX_MAX_BITS;
716
24.3k
  } else if (params.streaming_mode) {
717
    // TODO(szabadka) Figure out if we can use lower values here.
718
0
    log_alpha_size = 8;
719
13.4k
  } else if (lz77.enabled) {
720
2.77k
    log_alpha_size = 8;
721
10.6k
  } else {
722
10.6k
    log_alpha_size = 7;
723
10.6k
  }
724
725
37.7k
  if (ans_fuzzer_friendly_) {
726
0
    uint_config.assign(1, HybridUintConfig(7, 0, 0));
727
0
    return true;
728
0
  }
729
730
37.7k
  uint_config.assign(clustered_histograms.size(), params.UintConfig());
731
  // If the uint config is fixed, just use it.
732
37.7k
  if (params.uint_method != HistogramParams::HybridUintMethod::kBest &&
733
37.7k
      params.uint_method != HistogramParams::HybridUintMethod::kFast) {
734
28.2k
    return true;
735
28.2k
  }
736
  // Even if the uint config is adaptive, just stick with the default in
737
  // streaming mode.
738
9.47k
  if (params.streaming_mode) {
739
0
    return true;
740
0
  }
741
742
  // Brute-force method that tries a few options.
743
9.47k
  std::vector<HybridUintConfig> configs;
744
9.47k
  if (params.uint_method == HistogramParams::HybridUintMethod::kBest) {
745
2.72k
    configs = {
746
2.72k
        HybridUintConfig(4, 2, 0),  // default
747
2.72k
        HybridUintConfig(4, 1, 0),  // less precise
748
2.72k
        HybridUintConfig(4, 2, 1),  // add sign
749
2.72k
        HybridUintConfig(4, 2, 2),  // add sign+parity
750
2.72k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
751
        // Same as above, but more direct coding.
752
2.72k
        HybridUintConfig(5, 2, 0), HybridUintConfig(5, 1, 0),
753
2.72k
        HybridUintConfig(5, 2, 1), HybridUintConfig(5, 2, 2),
754
2.72k
        HybridUintConfig(5, 1, 2),
755
        // Same as above, but less direct coding.
756
2.72k
        HybridUintConfig(3, 2, 0), HybridUintConfig(3, 1, 0),
757
2.72k
        HybridUintConfig(3, 2, 1), HybridUintConfig(3, 1, 2),
758
        // For near-lossless.
759
2.72k
        HybridUintConfig(4, 1, 3), HybridUintConfig(5, 1, 4),
760
2.72k
        HybridUintConfig(5, 2, 3), HybridUintConfig(6, 1, 5),
761
2.72k
        HybridUintConfig(6, 2, 4), HybridUintConfig(6, 0, 0),
762
        // Other
763
2.72k
        HybridUintConfig(0, 0, 0),   // varlenuint
764
2.72k
        HybridUintConfig(2, 0, 1),   // works well for ctx map
765
2.72k
        HybridUintConfig(7, 0, 0),   // direct coding
766
2.72k
        HybridUintConfig(8, 0, 0),   // direct coding
767
2.72k
        HybridUintConfig(9, 0, 0),   // direct coding
768
2.72k
        HybridUintConfig(10, 0, 0),  // direct coding
769
2.72k
        HybridUintConfig(11, 0, 0),  // direct coding
770
2.72k
        HybridUintConfig(12, 0, 0),  // direct coding
771
2.72k
    };
772
6.75k
  } else {
773
6.75k
    JXL_DASSERT(params.uint_method == HistogramParams::HybridUintMethod::kFast);
774
6.75k
    configs = {
775
6.75k
        HybridUintConfig(4, 2, 0),  // default
776
6.75k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
777
6.75k
        HybridUintConfig(0, 0, 0),  // smallest histograms
778
6.75k
        HybridUintConfig(2, 0, 1),  // works well for ctx map
779
6.75k
    };
780
6.75k
  }
781
782
9.47k
  size_t num_histo = clustered_histograms.size();
783
9.47k
  std::vector<uint8_t> is_valid(num_histo);
784
9.47k
  std::vector<size_t> histo_volume(2 * num_histo);
785
9.47k
  std::vector<size_t> histo_offset(2 * num_histo + 1);
786
9.47k
  std::vector<uint32_t> max_value_per_histo(2 * num_histo);
787
788
  // TODO(veluca): do not ignore lz77 commands.
789
790
83.7k
  for (const auto& stream : tokens) {
791
49.5M
    for (const auto& token : stream) {
792
49.5M
      size_t histo = context_map[token.context];
793
49.5M
      histo_volume[histo + (token.is_lz77_length ? num_histo : 0)]++;
794
49.5M
    }
795
83.7k
  }
796
9.47k
  size_t max_histo_volume = 0;
797
134k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
798
125k
    max_histo_volume = std::max(max_histo_volume, histo_volume[h]);
799
125k
    histo_offset[h + 1] = histo_offset[h] + histo_volume[h];
800
125k
  }
801
802
9.47k
  const size_t max_vec_size = MaxVectorSize();
803
9.47k
  std::vector<uint32_t> transposed(histo_offset[num_histo * 2] + max_vec_size);
804
9.47k
  {
805
9.47k
    std::vector<size_t> next_offset = histo_offset;  // copy
806
83.7k
    for (const auto& stream : tokens) {
807
49.5M
      for (const auto& token : stream) {
808
49.5M
        size_t histo =
809
49.5M
            context_map[token.context] + (token.is_lz77_length ? num_histo : 0);
810
49.5M
        transposed[next_offset[histo]++] = token.value;
811
49.5M
      }
812
83.7k
    }
813
9.47k
  }
814
134k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
815
125k
    max_value_per_histo[h] =
816
125k
        MaxValue(transposed.data() + histo_offset[h], histo_volume[h]);
817
125k
  }
818
9.47k
  uint32_t max_lz77 = 0;
819
72.1k
  for (size_t h = num_histo; h < 2 * num_histo; ++h) {
820
62.7k
    max_lz77 = std::max(max_lz77, MaxValue(transposed.data() + histo_offset[h],
821
62.7k
                                           histo_volume[h]));
822
62.7k
  }
823
824
  // Wider histograms are assigned max cost in PopulationCost anyway
825
  // and therefore will not be used
826
9.47k
  size_t max_alpha = ANS_MAX_ALPHABET_SIZE;
827
828
9.47k
  JXL_ASSIGN_OR_RETURN(
829
9.47k
      AlignedMemory tmp,
830
9.47k
      AlignedMemory::Create(memory_manager, (max_histo_volume + max_vec_size) *
831
9.47k
                                                sizeof(uint32_t)));
832
72.1k
  for (size_t h = 0; h < num_histo; h++) {
833
62.7k
    float best_cost = std::numeric_limits<float>::max();
834
460k
    for (HybridUintConfig cfg : configs) {
835
460k
      uint32_t max_v = max_value_per_histo[h];
836
460k
      size_t capacity;
837
460k
      {
838
460k
        uint32_t tok, nbits, bits;
839
460k
        cfg.Encode(max_v, &tok, &nbits, &bits);
840
460k
        tok |= cfg.LsbMask();
841
460k
        if (tok >= max_alpha || (lz77.enabled && tok >= lz77.min_symbol)) {
842
11.8k
          continue;  // Not valid config for this context
843
11.8k
        }
844
449k
        capacity = tok + 1;
845
449k
      }
846
847
0
      Histogram histo;
848
449k
      histo.EnsureCapacity(capacity);
849
449k
      size_t len = histo_volume[h];
850
449k
      uint32_t* data = transposed.data() + histo_offset[h];
851
449k
      size_t extra_bits = EstimateTokenCost(data, len, cfg, tmp);
852
449k
      uint32_t* tmp_tokens = tmp.address<uint32_t>();
853
308M
      for (size_t i = 0; i < len; ++i) {
854
308M
        histo.FastAdd(tmp_tokens[i]);
855
308M
      }
856
449k
      histo.Condition();
857
449k
      JXL_ASSIGN_OR_RETURN(float cost, histo.ANSPopulationCost());
858
449k
      cost += extra_bits;
859
      // Add signaling cost of the hybriduintconfig itself.
860
449k
      cost += CeilLog2Nonzero(cfg.split_exponent + 1);
861
449k
      cost += CeilLog2Nonzero(cfg.split_exponent - cfg.msb_in_token + 1);
862
449k
      if (cost < best_cost) {
863
135k
        uint_config[h] = cfg;
864
135k
        best_cost = cost;
865
135k
        clustered_histograms[h].swap(histo);
866
135k
      }
867
449k
    }
868
62.7k
  }
869
870
9.47k
  size_t max_tok = 0;
871
72.1k
  for (size_t h = 0; h < num_histo; ++h) {
872
62.7k
    Histogram& histo = clustered_histograms[h];
873
62.7k
    max_tok = std::max(max_tok, histo.MaxSymbol());
874
62.7k
    size_t len = histo_volume[num_histo + h];
875
62.7k
    if (len == 0) continue;  // E.g. when lz77 not enabled
876
767
    size_t max_histo_tok = max_value_per_histo[num_histo + h];
877
767
    uint32_t tok, nbits, bits;
878
767
    lz77.length_uint_config.Encode(max_histo_tok, &tok, &nbits, &bits);
879
767
    tok |= lz77.length_uint_config.LsbMask();
880
767
    tok += lz77.min_symbol;
881
767
    histo.EnsureCapacity(tok + 1);
882
767
    uint32_t* data = transposed.data() + histo_offset[num_histo + h];
883
767
    uint32_t unused =
884
767
        EstimateTokenCost(data, len, lz77.length_uint_config, tmp);
885
767
    (void)unused;
886
767
    uint32_t* tmp_tokens = tmp.address<uint32_t>();
887
9.25k
    for (size_t i = 0; i < len; ++i) {
888
8.48k
      histo.FastAdd(tmp_tokens[i] + lz77.min_symbol);
889
8.48k
    }
890
767
    histo.Condition();
891
767
    max_tok = std::max(max_tok, histo.MaxSymbol());
892
767
  }
893
894
  // `log_alpha_size - 5` is encoded in the header, so min is 5.
895
9.47k
  size_t log_size = 5;
896
15.5k
  while (max_tok >= (1u << log_size)) ++log_size;
897
898
9.47k
  size_t max_log_alpha_size = use_prefix_code ? PREFIX_MAX_BITS : 8;
899
9.47k
  JXL_ENSURE(log_size <= max_log_alpha_size);
900
901
9.47k
  if (use_prefix_code) {
902
2.48k
    log_alpha_size = PREFIX_MAX_BITS;
903
6.99k
  } else {
904
6.99k
    log_alpha_size = log_size;
905
6.99k
  }
906
907
9.47k
  return true;
908
9.47k
}
909
910
// NOTE: `layer` is only for clustered_entropy; caller does ReclaimAndCharge.
911
// Returns cost (in bits).
912
StatusOr<size_t> EntropyEncodingData::BuildAndStoreEntropyCodes(
913
    JxlMemoryManager* memory_manager, const HistogramParams& params,
914
    const std::vector<std::vector<Token>>& tokens,
915
    const std::vector<Histogram>& builder, BitWriter* writer, LayerType layer,
916
37.7k
    AuxOut* aux_out) {
917
37.7k
  const size_t prev_histograms = encoding_info.size();
918
37.7k
  std::vector<Histogram> clustered_histograms;
919
37.7k
  for (size_t i = 0; i < prev_histograms; ++i) {
920
0
    clustered_histograms.push_back(
921
0
        HistogramFromSymbolInfo(encoding_info[i], use_prefix_code));
922
0
  }
923
37.7k
  size_t context_offset = context_map.size();
924
37.7k
  context_map.resize(context_offset + builder.size());
925
37.7k
  if (builder.size() > 1) {
926
14.3k
    if (!ans_fuzzer_friendly_) {
927
14.3k
      std::vector<uint32_t> histogram_symbols;
928
14.3k
      JXL_RETURN_IF_ERROR(ClusterHistograms(params, builder, kClustersLimit,
929
14.3k
                                            &clustered_histograms,
930
14.3k
                                            &histogram_symbols));
931
13.1M
      for (size_t c = 0; c < builder.size(); ++c) {
932
13.1M
        context_map[context_offset + c] =
933
13.1M
            static_cast<uint8_t>(histogram_symbols[c]);
934
13.1M
      }
935
14.3k
    } else {
936
0
      JXL_ENSURE(encoding_info.empty());
937
0
      std::fill(context_map.begin(), context_map.end(), 0);
938
0
      size_t max_symbol = 0;
939
0
      for (const Histogram& h : builder) {
940
0
        max_symbol = std::max(h.counts.size(), max_symbol);
941
0
      }
942
0
      size_t num_symbols = 1 << CeilLog2Nonzero(max_symbol + 1);
943
0
      clustered_histograms.resize(1);
944
0
      clustered_histograms[0].Clear();
945
0
      for (size_t i = 0; i < num_symbols; i++) {
946
0
        clustered_histograms[0].Add(i);
947
0
      }
948
0
    }
949
14.3k
    if (writer != nullptr) {
950
12.5k
      JXL_RETURN_IF_ERROR(EncodeContextMap(
951
12.5k
          context_map, clustered_histograms.size(), writer, layer, aux_out));
952
12.5k
    }
953
23.4k
  } else {
954
23.4k
    JXL_ENSURE(encoding_info.empty());
955
23.4k
    clustered_histograms.push_back(builder[0]);
956
23.4k
  }
957
37.7k
  if (aux_out != nullptr) {
958
0
    for (size_t i = prev_histograms; i < clustered_histograms.size(); ++i) {
959
0
      aux_out->layer(layer).clustered_entropy +=
960
0
          clustered_histograms[i].ShannonEntropy();
961
0
    }
962
0
  }
963
964
37.7k
  JXL_RETURN_IF_ERROR(
965
37.7k
      ChooseUintConfigs(memory_manager, params, tokens, clustered_histograms));
966
967
37.7k
  SizeWriter size_writer;  // Used if writer == nullptr to estimate costs.
968
37.7k
  size_t cost = use_prefix_code ? 1 : 3;
969
970
37.7k
  if (writer) writer->Write(1, TO_JXL_BOOL(use_prefix_code));
971
37.7k
  if (writer == nullptr) {
972
20.6k
    EncodeUintConfigs(uint_config, &size_writer, log_alpha_size);
973
20.6k
  } else {
974
17.0k
    if (!use_prefix_code) writer->Write(2, log_alpha_size - 5);
975
17.0k
    EncodeUintConfigs(uint_config, writer, log_alpha_size);
976
17.0k
  }
977
37.7k
  if (use_prefix_code) {
978
24.4k
    for (const auto& histo : clustered_histograms) {
979
24.4k
      size_t alphabet_size = std::max<size_t>(1, histo.alphabet_size());
980
24.4k
      if (writer) {
981
6.90k
        StoreVarLenUint16(alphabet_size - 1, writer);
982
17.5k
      } else {
983
17.5k
        StoreVarLenUint16(alphabet_size - 1, &size_writer);
984
17.5k
      }
985
24.4k
    }
986
24.3k
  }
987
37.7k
  cost += size_writer.size;
988
181k
  for (size_t c = prev_histograms; c < clustered_histograms.size(); ++c) {
989
144k
    size_t alphabet_size = clustered_histograms[c].alphabet_size();
990
144k
    encoding_info.emplace_back();
991
144k
    encoding_info.back().resize(alphabet_size);
992
144k
    BitWriter* histo_writer = writer;
993
144k
    if (params.streaming_mode) {
994
0
      encoded_histograms.emplace_back(memory_manager);
995
0
      histo_writer = &encoded_histograms.back();
996
0
    }
997
144k
    const auto& body = [&]() -> Status {
998
144k
      JXL_ASSIGN_OR_RETURN(size_t ans_cost,
999
144k
                           BuildAndStoreANSEncodingData(
1000
144k
                               memory_manager, params.ans_histogram_strategy,
1001
144k
                               clustered_histograms[c], histo_writer));
1002
144k
      cost += ans_cost;
1003
144k
      return true;
1004
144k
    };
1005
144k
    if (histo_writer) {
1006
122k
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1007
122k
          256 + alphabet_size * 24, layer, aux_out, body,
1008
122k
          /*finished_histogram=*/true));
1009
122k
    } else {
1010
22.1k
      JXL_RETURN_IF_ERROR(body());
1011
22.1k
    }
1012
144k
    if (params.streaming_mode) {
1013
0
      JXL_RETURN_IF_ERROR(writer->AppendUnaligned(*histo_writer));
1014
0
    }
1015
144k
  }
1016
37.7k
  return cost;
1017
37.7k
}
1018
1019
template <typename Writer>
1020
void EncodeUintConfig(const HybridUintConfig uint_config, Writer* writer,
1021
147k
                      size_t log_alpha_size) {
1022
147k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1023
147k
                uint_config.split_exponent);
1024
147k
  if (uint_config.split_exponent == log_alpha_size) {
1025
97
    return;  // msb/lsb don't matter.
1026
97
  }
1027
147k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1028
147k
  writer->Write(nbits, uint_config.msb_in_token);
1029
147k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1030
147k
                          uint_config.msb_in_token + 1);
1031
147k
  writer->Write(nbits, uint_config.lsb_in_token);
1032
147k
}
void jxl::EncodeUintConfig<jxl::SizeWriter>(jxl::HybridUintConfig, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1021
23.9k
                      size_t log_alpha_size) {
1022
23.9k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1023
23.9k
                uint_config.split_exponent);
1024
23.9k
  if (uint_config.split_exponent == log_alpha_size) {
1025
0
    return;  // msb/lsb don't matter.
1026
0
  }
1027
23.9k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1028
23.9k
  writer->Write(nbits, uint_config.msb_in_token);
1029
23.9k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1030
23.9k
                          uint_config.msb_in_token + 1);
1031
23.9k
  writer->Write(nbits, uint_config.lsb_in_token);
1032
23.9k
}
void jxl::EncodeUintConfig<jxl::BitWriter>(jxl::HybridUintConfig, jxl::BitWriter*, unsigned long)
Line
Count
Source
1021
123k
                      size_t log_alpha_size) {
1022
123k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1023
123k
                uint_config.split_exponent);
1024
123k
  if (uint_config.split_exponent == log_alpha_size) {
1025
97
    return;  // msb/lsb don't matter.
1026
97
  }
1027
123k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1028
123k
  writer->Write(nbits, uint_config.msb_in_token);
1029
123k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1030
123k
                          uint_config.msb_in_token + 1);
1031
123k
  writer->Write(nbits, uint_config.lsb_in_token);
1032
123k
}
1033
template <typename Writer>
1034
void EncodeUintConfigs(const std::vector<HybridUintConfig>& uint_config,
1035
37.7k
                       Writer* writer, size_t log_alpha_size) {
1036
  // TODO(veluca): RLE?
1037
144k
  for (const auto& cfg : uint_config) {
1038
144k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1039
144k
  }
1040
37.7k
}
void jxl::EncodeUintConfigs<jxl::BitWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::BitWriter*, unsigned long)
Line
Count
Source
1035
17.0k
                       Writer* writer, size_t log_alpha_size) {
1036
  // TODO(veluca): RLE?
1037
122k
  for (const auto& cfg : uint_config) {
1038
122k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1039
122k
  }
1040
17.0k
}
void jxl::EncodeUintConfigs<jxl::SizeWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1035
20.6k
                       Writer* writer, size_t log_alpha_size) {
1036
  // TODO(veluca): RLE?
1037
22.1k
  for (const auto& cfg : uint_config) {
1038
22.1k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1039
22.1k
  }
1040
20.6k
}
1041
template void EncodeUintConfigs(const std::vector<HybridUintConfig>&,
1042
                                BitWriter*, size_t);
1043
1044
Status EncodeHistograms(const EntropyEncodingData& codes, BitWriter* writer,
1045
0
                        LayerType layer, AuxOut* aux_out) {
1046
0
  return writer->WithMaxBits(
1047
0
      128 + kClustersLimit * 136, layer, aux_out,
1048
0
      [&]() -> Status {
1049
0
        JXL_RETURN_IF_ERROR(Bundle::Write(codes.lz77, writer, layer, aux_out));
1050
0
        if (codes.lz77.enabled) {
1051
0
          EncodeUintConfig(codes.lz77.length_uint_config, writer,
1052
0
                           /*log_alpha_size=*/8);
1053
0
        }
1054
0
        JXL_RETURN_IF_ERROR(EncodeContextMap(codes.context_map,
1055
0
                                             codes.encoding_info.size(), writer,
1056
0
                                             layer, aux_out));
1057
0
        writer->Write(1, TO_JXL_BOOL(codes.use_prefix_code));
1058
0
        size_t log_alpha_size = 8;
1059
0
        if (codes.use_prefix_code) {
1060
0
          log_alpha_size = PREFIX_MAX_BITS;
1061
0
        } else {
1062
0
          log_alpha_size = 8;  // streaming_mode
1063
0
          writer->Write(2, log_alpha_size - 5);
1064
0
        }
1065
0
        EncodeUintConfigs(codes.uint_config, writer, log_alpha_size);
1066
0
        if (codes.use_prefix_code) {
1067
0
          for (const auto& info : codes.encoding_info) {
1068
0
            StoreVarLenUint16(info.size() - 1, writer);
1069
0
          }
1070
0
        }
1071
0
        for (const auto& histo_writer : codes.encoded_histograms) {
1072
0
          JXL_RETURN_IF_ERROR(writer->AppendUnaligned(histo_writer));
1073
0
        }
1074
0
        return true;
1075
0
      },
1076
0
      /*finished_histogram=*/true);
1077
0
}
1078
1079
StatusOr<size_t> BuildAndEncodeHistograms(
1080
    JxlMemoryManager* memory_manager, const HistogramParams& params,
1081
    size_t num_contexts, std::vector<std::vector<Token>>& tokens,
1082
    EntropyEncodingData* codes, BitWriter* writer, LayerType layer,
1083
37.7k
    AuxOut* aux_out) {
1084
  // TODO(Ivan): presumably not needed - default
1085
  // if (params.initialize_global_state) codes->lz77.enabled = false;
1086
37.7k
  codes->lz77.nonserialized_distance_context = num_contexts;
1087
37.7k
  codes->lz77.min_symbol = params.force_huffman ? 512 : 224;
1088
37.7k
  std::vector<std::vector<Token>> tokens_lz77 =
1089
37.7k
      ApplyLZ77(params, num_contexts, tokens, codes->lz77);
1090
37.7k
  if (!tokens_lz77.empty()) codes->lz77.enabled = true;
1091
37.7k
  if (ans_fuzzer_friendly_) {
1092
0
    codes->lz77.length_uint_config = HybridUintConfig(10, 0, 0);
1093
0
    codes->lz77.min_symbol = 2048;
1094
0
  }
1095
1096
37.7k
  size_t cost = 0;
1097
37.7k
  const size_t max_contexts = std::min(num_contexts, kClustersLimit);
1098
37.7k
  const auto& body = [&]() -> Status {
1099
37.7k
    if (writer) {
1100
17.0k
      JXL_RETURN_IF_ERROR(Bundle::Write(codes->lz77, writer, layer, aux_out));
1101
20.6k
    } else {
1102
20.6k
      size_t ebits, bits;
1103
20.6k
      JXL_RETURN_IF_ERROR(Bundle::CanEncode(codes->lz77, &ebits, &bits));
1104
20.6k
      cost += bits;
1105
20.6k
    }
1106
37.7k
    if (codes->lz77.enabled) {
1107
2.93k
      if (writer) {
1108
1.18k
        size_t b = writer->BitsWritten();
1109
1.18k
        EncodeUintConfig(codes->lz77.length_uint_config, writer,
1110
1.18k
                         /*log_alpha_size=*/8);
1111
1.18k
        cost += writer->BitsWritten() - b;
1112
1.75k
      } else {
1113
1.75k
        SizeWriter size_writer;
1114
1.75k
        EncodeUintConfig(codes->lz77.length_uint_config, &size_writer,
1115
1.75k
                         /*log_alpha_size=*/8);
1116
1.75k
        cost += size_writer.size;
1117
1.75k
      }
1118
2.93k
      num_contexts += 1;
1119
2.93k
      tokens = std::move(tokens_lz77);
1120
2.93k
    }
1121
37.7k
    size_t total_tokens = 0;
1122
    // Build histograms.
1123
37.7k
    std::vector<Histogram> builder(num_contexts);
1124
37.7k
    HybridUintConfig uint_config = params.UintConfig();
1125
37.7k
    if (ans_fuzzer_friendly_) {
1126
0
      uint_config = HybridUintConfig(10, 0, 0);
1127
0
    }
1128
115k
    for (const auto& stream : tokens) {
1129
115k
      if (codes->lz77.enabled) {
1130
4.31M
        for (const auto& token : stream) {
1131
4.31M
          total_tokens++;
1132
4.31M
          uint32_t tok, nbits, bits;
1133
4.31M
          (token.is_lz77_length ? codes->lz77.length_uint_config : uint_config)
1134
4.31M
              .Encode(token.value, &tok, &nbits, &bits);
1135
4.31M
          tok += token.is_lz77_length ? codes->lz77.min_symbol : 0;
1136
4.31M
          JXL_DASSERT(token.context < num_contexts);
1137
4.31M
          builder[token.context].Add(tok);
1138
4.31M
        }
1139
112k
      } else if (num_contexts == 1) {
1140
11.0M
        for (const auto& token : stream) {
1141
11.0M
          total_tokens++;
1142
11.0M
          uint32_t tok, nbits, bits;
1143
11.0M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1144
11.0M
          builder[0].Add(tok);
1145
11.0M
        }
1146
87.8k
      } else {
1147
219M
        for (const auto& token : stream) {
1148
219M
          total_tokens++;
1149
219M
          uint32_t tok, nbits, bits;
1150
219M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1151
219M
          JXL_DASSERT(token.context < num_contexts);
1152
219M
          builder[token.context].Add(tok);
1153
219M
        }
1154
87.8k
      }
1155
115k
    }
1156
1157
37.7k
    if (params.add_missing_symbols) {
1158
0
      for (size_t c = 0; c < num_contexts; ++c) {
1159
0
        for (int symbol = 0; symbol < ANS_MAX_ALPHABET_SIZE; ++symbol) {
1160
0
          builder[c].Add(symbol);
1161
0
        }
1162
0
      }
1163
0
    }
1164
1165
37.7k
    if (params.initialize_global_state) {
1166
37.7k
      bool use_prefix_code =
1167
37.7k
          params.force_huffman || total_tokens < 100 ||
1168
37.7k
          params.clustering == HistogramParams::ClusteringType::kFastest ||
1169
37.7k
          ans_fuzzer_friendly_;
1170
37.7k
      if (!use_prefix_code) {
1171
13.4k
        bool all_singleton = true;
1172
9.93M
        for (size_t i = 0; i < num_contexts; i++) {
1173
9.91M
          if (builder[i].ShannonEntropy() >= 1e-5) {
1174
1.41M
            all_singleton = false;
1175
1.41M
          }
1176
9.91M
        }
1177
13.4k
        if (all_singleton) {
1178
68
          use_prefix_code = true;
1179
68
        }
1180
13.4k
      }
1181
37.7k
      codes->use_prefix_code = use_prefix_code;
1182
37.7k
    }
1183
1184
37.7k
    if (params.add_fixed_histograms) {
1185
      // TODO(szabadka) Add more fixed histograms.
1186
      // TODO(szabadka) Reduce alphabet size by choosing a non-default
1187
      // uint_config.
1188
0
      const size_t alphabet_size = ANS_MAX_ALPHABET_SIZE;
1189
0
      codes->log_alpha_size = 8;
1190
0
      JXL_ENSURE(alphabet_size == 1u << codes->log_alpha_size);
1191
0
      static_assert(ANS_MAX_ALPHABET_SIZE <= ANS_TAB_SIZE,
1192
0
                    "Alphabet does not fit table");
1193
0
      codes->encoding_info.emplace_back();
1194
0
      codes->encoding_info.back().resize(alphabet_size);
1195
0
      codes->encoded_histograms.emplace_back(memory_manager);
1196
0
      BitWriter* histo_writer = &codes->encoded_histograms.back();
1197
0
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1198
0
          256 + alphabet_size * 24, LayerType::Header, nullptr,
1199
0
          [&]() -> Status {
1200
0
            JXL_ASSIGN_OR_RETURN(
1201
0
                size_t ans_cost,
1202
0
                codes->BuildAndStoreANSEncodingData(
1203
0
                    memory_manager, params.ans_histogram_strategy,
1204
0
                    Histogram::Flat(alphabet_size, ANS_TAB_SIZE),
1205
0
                    histo_writer));
1206
0
            (void)ans_cost;
1207
0
            return true;
1208
0
          }));
1209
0
    }
1210
1211
    // Encode histograms.
1212
37.7k
    JXL_ASSIGN_OR_RETURN(
1213
37.7k
        size_t entropy_bits,
1214
37.7k
        codes->BuildAndStoreEntropyCodes(memory_manager, params, tokens,
1215
37.7k
                                         builder, writer, layer, aux_out));
1216
37.7k
    cost += entropy_bits;
1217
37.7k
    return true;
1218
37.7k
  };
1219
37.7k
  if (writer) {
1220
17.0k
    JXL_RETURN_IF_ERROR(writer->WithMaxBits(
1221
17.0k
        128 + num_contexts * 40 + max_contexts * 96, layer, aux_out, body,
1222
17.0k
        /*finished_histogram=*/true));
1223
20.6k
  } else {
1224
20.6k
    JXL_RETURN_IF_ERROR(body());
1225
20.6k
  }
1226
1227
37.7k
  if (aux_out != nullptr) {
1228
0
    aux_out->layer(layer).num_clustered_histograms +=
1229
0
        codes->encoding_info.size();
1230
0
  }
1231
37.7k
  return cost;
1232
37.7k
}
1233
1234
size_t WriteTokens(const std::vector<Token>& tokens,
1235
                   const EntropyEncodingData& codes, size_t context_offset,
1236
22.8k
                   BitWriter* writer) {
1237
22.8k
  size_t num_extra_bits = 0;
1238
22.8k
  if (codes.use_prefix_code) {
1239
291k
    for (const auto& token : tokens) {
1240
291k
      uint32_t tok, nbits, bits;
1241
291k
      size_t histo = codes.context_map[context_offset + token.context];
1242
291k
      (token.is_lz77_length ? codes.lz77.length_uint_config
1243
291k
                            : codes.uint_config[histo])
1244
291k
          .Encode(token.value, &tok, &nbits, &bits);
1245
291k
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1246
      // Combine two calls to the BitWriter. Equivalent to:
1247
      // writer->Write(codes.encoding_info[histo][tok].depth,
1248
      //               codes.encoding_info[histo][tok].bits);
1249
      // writer->Write(nbits, bits);
1250
291k
      uint64_t data = codes.encoding_info[histo][tok].bits;
1251
291k
      data |= static_cast<uint64_t>(bits)
1252
291k
              << codes.encoding_info[histo][tok].depth;
1253
291k
      writer->Write(codes.encoding_info[histo][tok].depth + nbits, data);
1254
291k
      num_extra_bits += nbits;
1255
291k
    }
1256
7.53k
    return num_extra_bits;
1257
7.53k
  }
1258
15.2k
  std::vector<uint64_t> out;
1259
15.2k
  std::vector<uint8_t> out_nbits;
1260
15.2k
  out.reserve(tokens.size());
1261
15.2k
  out_nbits.reserve(tokens.size());
1262
15.2k
  uint64_t allbits = 0;
1263
15.2k
  size_t numallbits = 0;
1264
  // Writes in *reversed* order.
1265
448M
  auto addbits = [&](size_t bits, size_t nbits) {
1266
448M
    if (JXL_UNLIKELY(nbits)) {
1267
41.9M
      JXL_DASSERT(bits >> nbits == 0);
1268
41.9M
      if (JXL_UNLIKELY(numallbits + nbits > BitWriter::kMaxBitsPerCall)) {
1269
8.70M
        out.push_back(allbits);
1270
8.70M
        out_nbits.push_back(numallbits);
1271
8.70M
        numallbits = allbits = 0;
1272
8.70M
      }
1273
41.9M
      allbits <<= nbits;
1274
41.9M
      allbits |= bits;
1275
41.9M
      numallbits += nbits;
1276
41.9M
    }
1277
448M
  };
1278
15.2k
  const int end = tokens.size();
1279
15.2k
  ANSCoder ans;
1280
15.2k
  if (codes.lz77.enabled || codes.context_map.size() > 1) {
1281
221M
    for (int i = end - 1; i >= 0; --i) {
1282
221M
      const Token token = tokens[i];
1283
221M
      const uint8_t histo = codes.context_map[context_offset + token.context];
1284
221M
      uint32_t tok, nbits, bits;
1285
221M
      (token.is_lz77_length ? codes.lz77.length_uint_config
1286
221M
                            : codes.uint_config[histo])
1287
221M
          .Encode(tokens[i].value, &tok, &nbits, &bits);
1288
221M
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1289
221M
      const ANSEncSymbolInfo& info = codes.encoding_info[histo][tok];
1290
221M
      JXL_DASSERT(info.freq_ > 0);
1291
      // Extra bits first as this is reversed.
1292
221M
      addbits(bits, nbits);
1293
221M
      num_extra_bits += nbits;
1294
221M
      uint8_t ans_nbits = 0;
1295
221M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1296
221M
      addbits(ans_bits, ans_nbits);
1297
221M
    }
1298
14.5k
  } else {
1299
3.30M
    for (int i = end - 1; i >= 0; --i) {
1300
3.30M
      uint32_t tok, nbits, bits;
1301
3.30M
      codes.uint_config[0].Encode(tokens[i].value, &tok, &nbits, &bits);
1302
3.30M
      const ANSEncSymbolInfo& info = codes.encoding_info[0][tok];
1303
      // Extra bits first as this is reversed.
1304
3.30M
      addbits(bits, nbits);
1305
3.30M
      num_extra_bits += nbits;
1306
3.30M
      uint8_t ans_nbits = 0;
1307
3.30M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1308
3.30M
      addbits(ans_bits, ans_nbits);
1309
3.30M
    }
1310
725
  }
1311
15.2k
  const uint32_t state = ans.GetState();
1312
15.2k
  writer->Write(32, state);
1313
15.2k
  writer->Write(numallbits, allbits);
1314
8.72M
  for (int i = out.size(); i > 0; --i) {
1315
8.70M
    writer->Write(out_nbits[i - 1], out[i - 1]);
1316
8.70M
  }
1317
15.2k
  return num_extra_bits;
1318
15.2k
}
1319
1320
Status WriteTokens(const std::vector<Token>& tokens,
1321
                   const EntropyEncodingData& codes, size_t context_offset,
1322
17.4k
                   BitWriter* writer, LayerType layer, AuxOut* aux_out) {
1323
  // Theoretically, we could have 15 prefix code bits + 31 extra bits.
1324
17.4k
  return writer->WithMaxBits(
1325
17.4k
      46 * tokens.size() + 32 * 1024 * 4, layer, aux_out, [&] {
1326
17.4k
        size_t num_extra_bits =
1327
17.4k
            WriteTokens(tokens, codes, context_offset, writer);
1328
17.4k
        if (aux_out != nullptr) {
1329
0
          aux_out->layer(layer).extra_bits += num_extra_bits;
1330
0
        }
1331
17.4k
        return true;
1332
17.4k
      });
1333
17.4k
}
1334
1335
0
void SetANSFuzzerFriendly(bool ans_fuzzer_friendly) {
1336
#if JXL_IS_DEBUG_BUILD  // Guard against accidental / malicious changes.
1337
0
  ans_fuzzer_friendly_ = ans_fuzzer_friendly;
1338
0
#endif
1339
0
}
1340
1341
HistogramParams HistogramParams::ForModular(
1342
    const CompressParams& cparams,
1343
6.75k
    const std::vector<uint8_t>& extra_dc_precision, bool streaming_mode) {
1344
6.75k
  HistogramParams params;
1345
6.75k
  params.streaming_mode = streaming_mode;
1346
6.75k
  if (cparams.speed_tier > SpeedTier::kKitten) {
1347
6.75k
    params.clustering = HistogramParams::ClusteringType::kFast;
1348
6.75k
    params.ans_histogram_strategy =
1349
6.75k
        cparams.speed_tier > SpeedTier::kThunder
1350
6.75k
            ? HistogramParams::ANSHistogramStrategy::kFast
1351
6.75k
            : HistogramParams::ANSHistogramStrategy::kApproximate;
1352
6.75k
    params.lz77_method =
1353
6.75k
        cparams.modular_mode && cparams.speed_tier <= SpeedTier::kHare
1354
6.75k
            ? HistogramParams::LZ77Method::kRLE
1355
6.75k
            : HistogramParams::LZ77Method::kNone;
1356
    // Near-lossless DC, as well as modular mode, require choosing hybrid uint
1357
    // more carefully.
1358
6.75k
    if ((!extra_dc_precision.empty() && extra_dc_precision[0] != 0) ||
1359
6.75k
        (cparams.modular_mode && cparams.speed_tier < SpeedTier::kCheetah)) {
1360
4.45k
      params.uint_method = HistogramParams::HybridUintMethod::kFast;
1361
4.45k
    } else {
1362
2.29k
      params.uint_method = HistogramParams::HybridUintMethod::kNone;
1363
2.29k
    }
1364
6.75k
  } else if (cparams.speed_tier <= SpeedTier::kTortoise) {
1365
0
    params.lz77_method = HistogramParams::LZ77Method::kOptimal;
1366
0
  } else {
1367
0
    params.lz77_method = HistogramParams::LZ77Method::kLZ77;
1368
0
  }
1369
6.75k
  if (cparams.decoding_speed_tier >= 2) {
1370
0
    params.max_histograms = 12;
1371
0
  }
1372
    // No predictor requires LZ77 to compress residuals.
1373
    // Effort 3 and lower have forced predictors, so kNone is set.
1374
6.75k
    if (cparams.options.predictor == Predictor::Zero && cparams.modular_mode) {
1375
0
        params.lz77_method = cparams.speed_tier >= SpeedTier::kFalcon
1376
0
            ? HistogramParams::LZ77Method::kNone
1377
0
            : cparams.speed_tier >= SpeedTier::kHare
1378
0
            ? HistogramParams::LZ77Method::kRLE
1379
0
            : cparams.speed_tier >= SpeedTier::kKitten
1380
0
            ? HistogramParams::LZ77Method::kLZ77
1381
0
            : HistogramParams::LZ77Method::kOptimal;
1382
0
    }
1383
6.75k
  return params;
1384
6.75k
}
1385
}  // namespace jxl