Coverage Report

Created: 2025-11-16 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/enc_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/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
9.95k
void StoreVarLenUint8(size_t n, Writer* writer) {
55
9.95k
  JXL_DASSERT(n <= 255);
56
9.95k
  if (n == 0) {
57
1.57k
    writer->Write(1, 0);
58
8.38k
  } else {
59
8.38k
    writer->Write(1, 1);
60
8.38k
    size_t nbits = FloorLog2Nonzero(n);
61
8.38k
    writer->Write(3, nbits);
62
8.38k
    writer->Write(nbits, n - (1ULL << nbits));
63
8.38k
  }
64
9.95k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
54
9.95k
void StoreVarLenUint8(size_t n, Writer* writer) {
55
9.95k
  JXL_DASSERT(n <= 255);
56
9.95k
  if (n == 0) {
57
1.57k
    writer->Write(1, 0);
58
8.38k
  } else {
59
8.38k
    writer->Write(1, 1);
60
8.38k
    size_t nbits = FloorLog2Nonzero(n);
61
8.38k
    writer->Write(3, nbits);
62
8.38k
    writer->Write(nbits, n - (1ULL << nbits));
63
8.38k
  }
64
9.95k
}
Unexecuted instantiation: enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
65
66
template <typename Writer>
67
1.57k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
1.57k
  JXL_DASSERT(n <= 65535);
69
1.57k
  if (n == 0) {
70
262
    writer->Write(1, 0);
71
1.31k
  } else {
72
1.31k
    writer->Write(1, 1);
73
1.31k
    size_t nbits = FloorLog2Nonzero(n);
74
1.31k
    writer->Write(4, nbits);
75
1.31k
    writer->Write(nbits, n - (1ULL << nbits));
76
1.31k
  }
77
1.57k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
67
1.04k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
1.04k
  JXL_DASSERT(n <= 65535);
69
1.04k
  if (n == 0) {
70
262
    writer->Write(1, 0);
71
786
  } else {
72
786
    writer->Write(1, 1);
73
786
    size_t nbits = FloorLog2Nonzero(n);
74
786
    writer->Write(4, nbits);
75
786
    writer->Write(nbits, n - (1ULL << nbits));
76
786
  }
77
1.04k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
67
524
void StoreVarLenUint16(size_t n, Writer* writer) {
68
524
  JXL_DASSERT(n <= 65535);
69
524
  if (n == 0) {
70
0
    writer->Write(1, 0);
71
524
  } else {
72
524
    writer->Write(1, 1);
73
524
    size_t nbits = FloorLog2Nonzero(n);
74
524
    writer->Write(4, nbits);
75
524
    writer->Write(nbits, n - (1ULL << nbits));
76
524
  }
77
524
}
78
79
class ANSEncodingHistogram {
80
 public:
81
0
  const std::vector<ANSHistBin>& Counts() const { return counts_; }
82
2.09k
  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
2.09k
      HistogramParams::ANSHistogramStrategy ans_histogram_strategy) {
87
2.09k
    ANSEncodingHistogram result;
88
89
2.09k
    result.alphabet_size_ = histo.alphabet_size();
90
2.09k
    if (result.alphabet_size_ > ANS_MAX_ALPHABET_SIZE)
91
0
      return JXL_FAILURE("Too many entries in an ANS histogram");
92
93
2.09k
    if (result.alphabet_size_ > 0) {
94
      // Flat code
95
2.09k
      result.method_ = 0;
96
2.09k
      result.num_symbols_ = result.alphabet_size_;
97
2.09k
      result.counts_ = CreateFlatHistogram(result.alphabet_size_, ANS_TAB_SIZE);
98
      // in this case length can be non-suitable for SIMD - fix it
99
2.09k
      result.counts_.resize(histo.counts.size());
100
2.09k
      SizeWriter writer;
101
2.09k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
102
2.09k
      result.cost_ = writer.size + EstimateDataBitsFlat(histo);
103
2.09k
    } 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
2.09k
    size_t symbol_count = 0;
112
17.0k
    for (size_t n = 0; n < result.alphabet_size_; ++n) {
113
14.9k
      if (histo.counts[n] > 0) {
114
7.86k
        if (symbol_count < kMaxNumSymbolsForSmallCode) {
115
4.19k
          result.symbols_[symbol_count] = n;
116
4.19k
        }
117
7.86k
        ++symbol_count;
118
7.86k
      }
119
14.9k
    }
120
2.09k
    result.num_symbols_ = symbol_count;
121
2.09k
    if (symbol_count == 1) {
122
      // Single-bin histogram
123
0
      result.method_ = 1;
124
0
      result.counts_ = histo.counts;
125
0
      result.counts_[result.symbols_[0]] = ANS_TAB_SIZE;
126
0
      SizeWriter writer;
127
0
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
128
0
      result.cost_ = writer.size;
129
0
      return result;
130
0
    }
131
132
    // Here min 2 symbols
133
2.09k
    ANSEncodingHistogram normalized = result;
134
6.28k
    auto try_shift = [&](uint32_t shift) -> Status {
135
      // `shift = 12` and `shift = 11` are the same
136
6.28k
      normalized.method_ = std::min(shift, ANS_LOG_TAB_SIZE - 1) + 1;
137
138
6.28k
      if (!normalized.RebalanceHistogram(histo)) {
139
0
        return JXL_FAILURE("Logic error: couldn't rebalance a histogram");
140
0
      }
141
6.28k
      SizeWriter writer;
142
6.28k
      JXL_RETURN_IF_ERROR(normalized.Encode(&writer));
143
6.28k
      normalized.cost_ = writer.size + normalized.EstimateDataBits(histo);
144
6.28k
      if (normalized.cost_ < result.cost_) {
145
0
        result = normalized;
146
0
      }
147
6.28k
      return true;
148
6.28k
    };
149
150
2.09k
    switch (ans_histogram_strategy) {
151
0
      case HistogramParams::ANSHistogramStrategy::kPrecise:
152
0
        for (uint32_t shift = 0; shift < ANS_LOG_TAB_SIZE; shift++) {
153
0
          JXL_RETURN_IF_ERROR(try_shift(shift));
154
0
        }
155
0
        break;
156
0
      case HistogramParams::ANSHistogramStrategy::kApproximate:
157
0
        for (uint32_t shift = 0; shift <= ANS_LOG_TAB_SIZE; shift += 2) {
158
0
          JXL_RETURN_IF_ERROR(try_shift(shift));
159
0
        }
160
0
        break;
161
2.09k
      case HistogramParams::ANSHistogramStrategy::kFast:
162
2.09k
        JXL_RETURN_IF_ERROR(try_shift(0));
163
2.09k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE / 2));
164
2.09k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE));
165
2.09k
        break;
166
2.09k
    }
167
168
      // Sanity check
169
2.09k
#if JXL_IS_DEBUG_BUILD
170
2.09k
    JXL_ENSURE(histo.counts.size() == result.counts_.size());
171
2.09k
    ANSHistBin total = 0;  // Used only in assert.
172
17.0k
    for (size_t i = 0; i < result.alphabet_size_; ++i) {
173
14.9k
      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
14.9k
      JXL_ENSURE(result.method_ == 0 ||
177
14.9k
                 (histo.counts[i] > 0) == (result.counts_[i] > 0));
178
      // Check accuracy of the histogram values
179
14.9k
      if (result.method_ > 0 && result.counts_[i] > 0 &&
180
0
          i != result.omit_pos_) {
181
0
        int logcounts = FloorLog2Nonzero<uint32_t>(result.counts_[i]);
182
0
        int bitcount =
183
0
            GetPopulationCountPrecision(logcounts, result.method_ - 1);
184
0
        int drop_bits = logcounts - bitcount;
185
        // Check that the value is divisible by 2^drop_bits
186
0
        JXL_ENSURE((result.counts_[i] & ((1 << drop_bits) - 1)) == 0);
187
0
      }
188
14.9k
      total += result.counts_[i];
189
14.9k
    }
190
8.12k
    for (size_t i = result.alphabet_size_; i < result.counts_.size(); ++i) {
191
6.02k
      JXL_ENSURE(histo.counts[i] == 0);
192
6.02k
      JXL_ENSURE(result.counts_[i] == 0);
193
6.02k
    }
194
2.09k
    JXL_ENSURE((histo.total_count == 0) || (total == ANS_TAB_SIZE));
195
2.09k
#endif
196
2.09k
    return result;
197
2.09k
  }
198
199
  template <typename Writer>
200
8.38k
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
8.38k
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
8.38k
    if (method_ == 0) {
207
      // Mark non-small tree.
208
2.09k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
2.09k
      writer->Write(1, 1);
211
2.09k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
2.09k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
2.09k
      return true;
216
2.09k
    }
217
218
    /// Small tree.
219
6.28k
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
0
      writer->Write(1, 1);
222
0
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
0
      } else {
226
0
        writer->Write(1, num_symbols_ - 1);
227
0
        for (size_t i = 0; i < num_symbols_; ++i) {
228
0
          StoreVarLenUint8(symbols_[i], writer);
229
0
        }
230
0
      }
231
0
      if (num_symbols_ == 2) {
232
0
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
0
      }
234
235
0
      return true;
236
0
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
6.28k
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
6.28k
    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
6.28k
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
6.28k
    int log = FloorLog2Nonzero(method_);
249
6.28k
    writer->Write(log, (1 << log) - 1);
250
6.28k
    if (log != upper_bound_log) writer->Write(1, 0);
251
6.28k
    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
6.28k
    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
6.28k
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
6.28k
    size_t last = 0;
262
51.0k
    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
44.8k
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
32.2k
          counts_[i] != counts_[last]) {
270
29.0k
        same[last] = i - last;
271
29.0k
        last = i;
272
29.0k
      }
273
44.8k
    }
274
275
6.28k
    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
6.28k
    int omit_width = 10;
281
51.0k
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
44.8k
      if (i != omit_pos_ && counts_[i] > 0) {
283
17.2k
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
17.2k
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
17.2k
      }
286
44.8k
    }
287
6.28k
    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
6.28k
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
6.28k
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
6.28k
    };
294
6.28k
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
6.28k
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
6.28k
    };
297
6.28k
    constexpr uint8_t kMinReps = 5;
298
6.28k
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
44.8k
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
38.5k
      writer->Write(kBitWidthLengths[bit_width[i]],
302
38.5k
                    kBitWidthSymbols[bit_width[i]]);
303
38.5k
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.57k
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.57k
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.57k
        i += same[i] - 1;
308
1.57k
      }
309
38.5k
    }
310
    // Encode additional bits of accuracy
311
6.28k
    uint32_t shift = method_ - 1;
312
6.28k
    if (shift != 0) {  // otherwise `bitcount = 0`
313
29.8k
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
25.6k
        if (bit_width[i] > 1 && i != omit_pos_) {
315
11.5k
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
11.5k
          int drop_bits = bit_width[i] - 1 - bitcount;
317
11.5k
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
11.5k
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
11.5k
        }
320
25.6k
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.04k
          i += same[i] - 1;
323
1.04k
        }
324
25.6k
      }
325
4.19k
    }
326
6.28k
    return true;
327
6.28k
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::SizeWriter>(jxl::SizeWriter*)
Line
Count
Source
200
8.38k
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
8.38k
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
8.38k
    if (method_ == 0) {
207
      // Mark non-small tree.
208
2.09k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
2.09k
      writer->Write(1, 1);
211
2.09k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
2.09k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
2.09k
      return true;
216
2.09k
    }
217
218
    /// Small tree.
219
6.28k
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
0
      writer->Write(1, 1);
222
0
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
0
      } else {
226
0
        writer->Write(1, num_symbols_ - 1);
227
0
        for (size_t i = 0; i < num_symbols_; ++i) {
228
0
          StoreVarLenUint8(symbols_[i], writer);
229
0
        }
230
0
      }
231
0
      if (num_symbols_ == 2) {
232
0
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
0
      }
234
235
0
      return true;
236
0
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
6.28k
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
6.28k
    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
6.28k
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
6.28k
    int log = FloorLog2Nonzero(method_);
249
6.28k
    writer->Write(log, (1 << log) - 1);
250
6.28k
    if (log != upper_bound_log) writer->Write(1, 0);
251
6.28k
    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
6.28k
    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
6.28k
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
6.28k
    size_t last = 0;
262
51.0k
    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
44.8k
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
32.2k
          counts_[i] != counts_[last]) {
270
29.0k
        same[last] = i - last;
271
29.0k
        last = i;
272
29.0k
      }
273
44.8k
    }
274
275
6.28k
    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
6.28k
    int omit_width = 10;
281
51.0k
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
44.8k
      if (i != omit_pos_ && counts_[i] > 0) {
283
17.2k
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
17.2k
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
17.2k
      }
286
44.8k
    }
287
6.28k
    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
6.28k
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
6.28k
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
6.28k
    };
294
6.28k
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
6.28k
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
6.28k
    };
297
6.28k
    constexpr uint8_t kMinReps = 5;
298
6.28k
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
44.8k
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
38.5k
      writer->Write(kBitWidthLengths[bit_width[i]],
302
38.5k
                    kBitWidthSymbols[bit_width[i]]);
303
38.5k
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.57k
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.57k
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.57k
        i += same[i] - 1;
308
1.57k
      }
309
38.5k
    }
310
    // Encode additional bits of accuracy
311
6.28k
    uint32_t shift = method_ - 1;
312
6.28k
    if (shift != 0) {  // otherwise `bitcount = 0`
313
29.8k
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
25.6k
        if (bit_width[i] > 1 && i != omit_pos_) {
315
11.5k
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
11.5k
          int drop_bits = bit_width[i] - 1 - bitcount;
317
11.5k
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
11.5k
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
11.5k
        }
320
25.6k
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.04k
          i += same[i] - 1;
323
1.04k
        }
324
25.6k
      }
325
4.19k
    }
326
6.28k
    return true;
327
6.28k
  }
Unexecuted instantiation: enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::BitWriter>(jxl::BitWriter*)
328
329
  void ANSBuildInfoTable(const AliasTable::Entry* table, size_t log_alpha_size,
330
0
                         ANSEncSymbolInfo* info) {
331
    // Create valid alias table for empty streams
332
0
    for (size_t s = 0; s < std::max(size_t{1}, alphabet_size_); ++s) {
333
0
      const ANSHistBin freq = s == alphabet_size_ ? ANS_TAB_SIZE : counts_[s];
334
0
      info[s].freq_ = static_cast<uint16_t>(freq);
335
0
#ifdef USE_MULT_BY_RECIPROCAL
336
0
      if (freq != 0) {
337
0
        info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) /
338
0
                         info[s].freq_;
339
0
      } else {
340
0
        info[s].ifreq_ =
341
0
            1;  // Shouldn't matter (symbol shouldn't occur), but...
342
0
      }
343
0
#endif
344
0
      info[s].reverse_map_.resize(freq);
345
0
    }
346
0
    size_t log_entry_size = ANS_LOG_TAB_SIZE - log_alpha_size;
347
0
    size_t entry_size_minus_1 = (1 << log_entry_size) - 1;
348
0
    for (int i = 0; i < ANS_TAB_SIZE; i++) {
349
0
      AliasTable::Symbol s =
350
0
          AliasTable::Lookup(table, i, log_entry_size, entry_size_minus_1);
351
0
      info[s.value].reverse_map_[s.offset] = i;
352
0
    }
353
0
  }
354
355
 private:
356
2.09k
  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
6.28k
  float EstimateDataBits(const Histogram& histo) {
363
6.28k
    int64_t sum = 0;
364
51.0k
    for (size_t i = 0; i < alphabet_size_; ++i) {
365
      // += histogram[i] * -log(counts[i]/total_counts)
366
44.8k
      sum += histo.counts[i] * int64_t{lg2[counts_[i]]};
367
44.8k
    }
368
6.28k
    return (histo.total_count - ldexpf(sum, -31)) * ANS_LOG_TAB_SIZE;
369
6.28k
  }
370
371
2.09k
  static float EstimateDataBitsFlat(const Histogram& histo) {
372
2.09k
    size_t len = histo.alphabet_size();
373
2.09k
    int64_t flat_bits = int64_t{lg2[len]} * ANS_LOG_TAB_SIZE;
374
2.09k
    return ldexpf(histo.total_count * flat_bits, -31);
375
2.09k
  }
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
339k
  static uint32_t SmallestIncrementLog(uint32_t count, uint32_t shift) {
400
339k
    if (count == 0) return 0;
401
318k
    uint32_t bits = FloorLog2Nonzero(count);
402
318k
    uint32_t drop_bits = bits - GetPopulationCountPrecision(bits, shift);
403
318k
    return drop_bits;
404
339k
  }
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
6.28k
  bool RebalanceHistogram(const Histogram& histo) {
417
6.28k
    constexpr ANSHistBin table_size = ANS_TAB_SIZE;
418
6.28k
    uint32_t shift = method_ - 1;
419
420
6.28k
    struct EntropyDelta {
421
6.28k
      ANSHistBin freq;   // initial count
422
6.28k
      size_t count_ind;  // index of current bin value in `allowed_counts`
423
6.28k
      size_t bin_ind;    // index of current bin in `counts`
424
6.28k
    };
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
6.28k
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_inc = {};
428
6.28k
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_dec = {};
429
6.28k
    const auto& ac = allowed_counts.array[shift];
430
6.28k
    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
30.9k
    const auto delta_entropy_inc = [&](const EntropyDelta& a) {
437
30.9k
      return a.freq * int64_t{ac[a.count_ind].delta_lg2} -
438
30.9k
             balance_inc[ac[a.count_ind].step_log];
439
30.9k
    };
440
28.2k
    const auto delta_entropy_dec = [&](const EntropyDelta& a) {
441
28.2k
      return a.freq * int64_t{ac[a.count_ind + 1].delta_lg2} -
442
28.2k
             balance_dec[ac[a.count_ind + 1].step_log];
443
28.2k
    };
444
    // Compare steps by entropy increase per unit of histogram bin change.
445
    // Truncation is OK here, accuracy is anyway better than float
446
12.0k
    const auto IncLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
447
12.0k
      return delta_entropy_inc(a) >> ac[a.count_ind].step_log <
448
12.0k
             delta_entropy_inc(b) >> ac[b.count_ind].step_log;
449
12.0k
    };
450
11.0k
    const auto DecLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
451
11.0k
      return delta_entropy_dec(a) >> ac[a.count_ind + 1].step_log <
452
11.0k
             delta_entropy_dec(b) >> ac[b.count_ind + 1].step_log;
453
11.0k
    };
454
    // Vector of adjustable bins from `allowed_counts`
455
6.28k
    std::vector<EntropyDelta> bins;
456
6.28k
    bins.reserve(256);
457
458
6.28k
    double norm = double{table_size} / histo.total_count;
459
460
6.28k
    size_t remainder_pos = 0;  // highest balancing bin in the histogram
461
6.28k
    int64_t max_freq = 0;
462
6.28k
    ANSHistBin rest = table_size;  // reserve of histogram counts to distribute
463
51.0k
    for (size_t n = 0; n < alphabet_size_; ++n) {
464
44.8k
      ANSHistBin freq = histo.counts[n];
465
44.8k
      if (freq > max_freq) {
466
6.28k
        remainder_pos = n;
467
6.28k
        max_freq = freq;
468
6.28k
      }
469
470
44.8k
      double target = freq * norm;  // rounding
471
      // Keep zeros and clamp nonzero freq counts to [1, table_size)
472
44.8k
      ANSHistBin count = std::max<ANSHistBin>(round(target), freq > 0);
473
44.8k
      count = std::min<ANSHistBin>(count, table_size - 1);
474
44.8k
      uint32_t step_log = SmallestIncrementLog(count, shift);
475
44.8k
      ANSHistBin inc = 1 << step_log;
476
44.8k
      count &= ~(inc - 1);
477
478
44.8k
      counts_[n] = count;
479
44.8k
      rest -= count;
480
44.8k
      if (target > 1.0) {
481
23.5k
        bins.push_back({freq, ai[count], n});
482
23.5k
      }
483
44.8k
    }
484
485
    // Delete the highest balancing bin from adjustable by `allowed_counts`
486
6.28k
    bins.erase(std::find_if(
487
6.28k
        bins.begin(), bins.end(),
488
6.28k
        [&](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
6.28k
    rest += counts_[remainder_pos];
492
493
6.28k
    if (!bins.empty()) {
494
6.28k
      const uint32_t max_log = ac[1].step_log;
495
6.81k
      while (true) {
496
        // Update balancing bin penalties setting guards and tractors
497
47.6k
        for (uint32_t log = 0; log <= max_log; ++log) {
498
40.8k
          ANSHistBin delta = 1 << log;
499
40.8k
          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
40.8k
          } else if (rest > 1) {
504
            // `rest` is OK, put guards against non-possible steps
505
40.8k
            balance_inc[log] =
506
40.8k
                rest > delta  // possible step
507
40.8k
                    ? max_freq * int64_t{lg2[rest] - lg2[rest - delta]}
508
40.8k
                    : std::numeric_limits<int64_t>::max();  // forbidden
509
40.8k
            balance_dec[log] =
510
40.8k
                rest + delta < table_size  // possible step
511
40.8k
                    ? max_freq * int64_t{lg2[rest + delta] - lg2[rest]}
512
40.8k
                    : 0;  // forbidden
513
40.8k
          } else {
514
            // Tract negative or zero `rest` into positive:
515
            // forbid all inc steps
516
0
            balance_inc[log] = std::numeric_limits<int64_t>::max();
517
            // permit all dec steps
518
0
            balance_dec[log] = std::numeric_limits<int64_t>::max();
519
0
          }
520
40.8k
        }
521
        // Try to increase entropy
522
6.81k
        auto best_bin_inc = std::max_element(bins.begin(), bins.end(), IncLess);
523
6.81k
        if (delta_entropy_inc(*best_bin_inc) > 0) {
524
          // Grow the bin with the best histogram entropy increase
525
524
          rest -= 1 << ac[best_bin_inc->count_ind--].step_log;
526
6.28k
        } 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
6.28k
          auto best_bin_dec =
531
6.28k
              std::min_element(bins.begin(), bins.end(), DecLess);
532
          // Break if no reverse steps can grow entropy (or valid)
533
6.28k
          if (delta_entropy_dec(*best_bin_dec) >= 0) break;
534
          // Decrease the bin with the best histogram entropy increase
535
0
          rest += 1 << ac[++best_bin_dec->count_ind].step_log;
536
0
        }
537
6.81k
      }
538
      // Set counts besides the balancing bin
539
17.2k
      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
6.28k
      for (size_t n = 0; n < remainder_pos; ++n) {
547
0
        if (counts_[n] >= 2048) {
548
0
          counts_[remainder_pos] = counts_[n];
549
0
          remainder_pos = n;
550
0
          break;
551
0
        }
552
0
      }
553
6.28k
    }
554
    // Set balancing bin
555
6.28k
    counts_[remainder_pos] = rest;
556
6.28k
    omit_pos_ = remainder_pos;
557
558
6.28k
    return counts_[remainder_pos] > 0;
559
6.28k
  }
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
6
const AEH::Lg2LUT AEH::lg2 = [] {
573
6
  Lg2LUT lg2;
574
6
  lg2[0] = 0;  // for entropy calculations it is OK
575
24.5k
  for (size_t i = 1; i < lg2.size(); ++i) {
576
24.5k
    lg2[i] = round(ldexp(log2(i) / ANS_LOG_TAB_SIZE, 31));
577
24.5k
  }
578
6
  return lg2;
579
6
}();
580
581
6
const AEH::AllowedCounts AEH::allowed_counts = [] {
582
6
  AllowedCounts result;
583
584
78
  for (uint32_t shift = 0; shift < result.array.size(); ++shift) {
585
72
    auto& ac = result.array[shift];
586
72
    auto& ai = result.index[shift];
587
72
    ANSHistBin last = ~0;
588
72
    size_t slot = 0;
589
    // TODO(eustas): are those "default" values relevant?
590
72
    ac[0].delta_lg2 = 0;
591
72
    ac[0].step_log = 0;
592
294k
    for (int32_t i = ac.size() - 1; i >= 0; --i) {
593
294k
      int32_t curr = i & ~((1 << SmallestIncrementLog(i, shift)) - 1);
594
294k
      if (curr == last) continue;
595
57.5k
      last = curr;
596
57.5k
      ac[slot].count = curr;
597
57.5k
      ai[curr] = slot;
598
57.5k
      if (curr == 0) {
599
        // Guards against non-possible steps:
600
        // at max value [0] - 0 (by init), at min value - max
601
72
        ac[slot].delta_lg2 = std::numeric_limits<int32_t>::max();
602
72
        ac[slot].step_log = 0;
603
57.4k
      } else if (slot > 0) {
604
57.3k
        ANSHistBin prev = ac[slot - 1].count;
605
57.3k
        ac[slot].delta_lg2 = round(ldexp(
606
57.3k
            log2(static_cast<double>(prev) / curr) / ANS_LOG_TAB_SIZE, 31));
607
57.3k
        ac[slot].step_log = FloorLog2Nonzero<uint32_t>(prev - curr);
608
57.3k
        prev = curr;
609
57.3k
      }
610
57.5k
      slot++;
611
57.5k
    }
612
72
  }
613
614
6
  return result;
615
6
}();
616
617
}  // namespace
618
619
2.09k
StatusOr<float> Histogram::ANSPopulationCost() const {
620
2.09k
  if (counts.size() > ANS_MAX_ALPHABET_SIZE) {
621
0
    return std::numeric_limits<float>::max();
622
0
  }
623
2.09k
  JXL_ASSIGN_OR_RETURN(
624
2.09k
      ANSEncodingHistogram normalized,
625
2.09k
      ANSEncodingHistogram::ComputeBest(
626
2.09k
          *this, HistogramParams::ANSHistogramStrategy::kFast));
627
2.09k
  return normalized.Cost();
628
2.09k
}
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
1.57k
    const Histogram& histogram, BitWriter* writer) {
636
1.57k
  ANSEncSymbolInfo* info = encoding_info.back().data();
637
1.57k
  size_t size = histogram.alphabet_size();
638
1.57k
  if (use_prefix_code) {
639
1.57k
    size_t cost = 0;
640
1.57k
    if (size <= 1) return 0;
641
1.31k
    std::vector<uint32_t> histo(size);
642
9.95k
    for (size_t i = 0; i < size; i++) {
643
8.64k
      JXL_ENSURE(histogram.counts[i] >= 0);
644
8.64k
      histo[i] = histogram.counts[i];
645
8.64k
    }
646
1.31k
    std::vector<uint8_t> depths(size);
647
1.31k
    std::vector<uint16_t> bits(size);
648
1.31k
    if (writer == nullptr) {
649
524
      BitWriter tmp_writer{memory_manager};
650
524
      JXL_RETURN_IF_ERROR(tmp_writer.WithMaxBits(
651
524
          8 * size + 8,  // safe upper bound
652
524
          LayerType::Header, /*aux_out=*/nullptr, [&] {
653
524
            return BuildAndStoreHuffmanTree(histo.data(), size, depths.data(),
654
524
                                            bits.data(), &tmp_writer);
655
524
          }));
656
524
      cost = tmp_writer.BitsWritten();
657
786
    } else {
658
786
      size_t start = writer->BitsWritten();
659
786
      JXL_RETURN_IF_ERROR(BuildAndStoreHuffmanTree(
660
786
          histo.data(), size, depths.data(), bits.data(), writer));
661
786
      cost = writer->BitsWritten() - start;
662
786
    }
663
9.95k
    for (size_t i = 0; i < size; i++) {
664
8.64k
      info[i].bits = depths[i] == 0 ? 0 : bits[i];
665
8.64k
      info[i].depth = depths[i];
666
8.64k
    }
667
    // Estimate data cost.
668
9.95k
    for (size_t i = 0; i < size; i++) {
669
8.64k
      cost += histo[i] * info[i].depth;
670
8.64k
    }
671
1.31k
    return cost;
672
1.31k
  }
673
0
  JXL_ASSIGN_OR_RETURN(
674
0
      ANSEncodingHistogram normalized,
675
0
      ANSEncodingHistogram::ComputeBest(histogram, ans_histogram_strategy));
676
677
  // TODO(eustas): fix: 2KiB on stack
678
0
  AliasTable::Entry a[ANS_MAX_ALPHABET_SIZE];
679
680
0
  JXL_RETURN_IF_ERROR(
681
0
      InitAliasTable(normalized.Counts(), ANS_LOG_TAB_SIZE, log_alpha_size, a));
682
0
  normalized.ANSBuildInfoTable(a, log_alpha_size, info);
683
0
  if (writer != nullptr) {
684
    // size_t start = writer->BitsWritten();
685
0
    JXL_RETURN_IF_ERROR(normalized.Encode(writer));
686
    // return writer->BitsWritten() - start;
687
0
  }
688
0
  return static_cast<size_t>(ceilf(normalized.Cost()));
689
0
}
690
691
namespace {
692
693
Histogram HistogramFromSymbolInfo(
694
0
    const std::vector<ANSEncSymbolInfo>& encoding_info, bool use_prefix_code) {
695
0
  Histogram histo;
696
0
  histo.counts.resize(DivCeil(encoding_info.size(), Histogram::kRounding) *
697
0
                      Histogram::kRounding);
698
0
  histo.total_count = 0;
699
0
  for (size_t i = 0; i < encoding_info.size(); ++i) {
700
0
    const ANSEncSymbolInfo& info = encoding_info[i];
701
0
    int count = use_prefix_code
702
0
                    ? (info.depth ? (1u << (PREFIX_MAX_BITS - info.depth)) : 0)
703
0
                    : info.freq_;
704
0
    histo.counts[i] = count;
705
0
    histo.total_count += count;
706
0
  }
707
0
  return histo;
708
0
}
709
710
}  // namespace
711
712
Status EntropyEncodingData::ChooseUintConfigs(
713
    JxlMemoryManager* memory_manager, const HistogramParams& params,
714
    const std::vector<std::vector<Token>>& tokens,
715
1.57k
    std::vector<Histogram>& clustered_histograms) {
716
  // Set sane default `log_alpha_size`.
717
1.57k
  if (use_prefix_code) {
718
1.57k
    log_alpha_size = PREFIX_MAX_BITS;
719
1.57k
  } else if (params.streaming_mode) {
720
    // TODO(szabadka) Figure out if we can use lower values here.
721
0
    log_alpha_size = 8;
722
0
  } else if (lz77.enabled) {
723
0
    log_alpha_size = 8;
724
0
  } else {
725
0
    log_alpha_size = 7;
726
0
  }
727
728
1.57k
  if (ans_fuzzer_friendly_) {
729
0
    uint_config.assign(1, HybridUintConfig(7, 0, 0));
730
0
    return true;
731
0
  }
732
733
1.57k
  uint_config.assign(clustered_histograms.size(), params.UintConfig());
734
  // If the uint config is fixed, just use it.
735
1.57k
  if (params.uint_method != HistogramParams::HybridUintMethod::kBest &&
736
1.57k
      params.uint_method != HistogramParams::HybridUintMethod::kFast) {
737
1.04k
    return true;
738
1.04k
  }
739
  // Even if the uint config is adaptive, just stick with the default in
740
  // streaming mode.
741
524
  if (params.streaming_mode) {
742
0
    return true;
743
0
  }
744
745
  // Brute-force method that tries a few options.
746
524
  std::vector<HybridUintConfig> configs;
747
524
  if (params.uint_method == HistogramParams::HybridUintMethod::kBest) {
748
0
    configs = {
749
0
        HybridUintConfig(4, 2, 0),  // default
750
0
        HybridUintConfig(4, 1, 0),  // less precise
751
0
        HybridUintConfig(4, 2, 1),  // add sign
752
0
        HybridUintConfig(4, 2, 2),  // add sign+parity
753
0
        HybridUintConfig(4, 1, 2),  // add parity but less msb
754
        // Same as above, but more direct coding.
755
0
        HybridUintConfig(5, 2, 0), HybridUintConfig(5, 1, 0),
756
0
        HybridUintConfig(5, 2, 1), HybridUintConfig(5, 2, 2),
757
0
        HybridUintConfig(5, 1, 2),
758
        // Same as above, but less direct coding.
759
0
        HybridUintConfig(3, 2, 0), HybridUintConfig(3, 1, 0),
760
0
        HybridUintConfig(3, 2, 1), HybridUintConfig(3, 1, 2),
761
        // For near-lossless.
762
0
        HybridUintConfig(4, 1, 3), HybridUintConfig(5, 1, 4),
763
0
        HybridUintConfig(5, 2, 3), HybridUintConfig(6, 1, 5),
764
0
        HybridUintConfig(6, 2, 4), HybridUintConfig(6, 0, 0),
765
        // Other
766
0
        HybridUintConfig(0, 0, 0),   // varlenuint
767
0
        HybridUintConfig(2, 0, 1),   // works well for ctx map
768
0
        HybridUintConfig(7, 0, 0),   // direct coding
769
0
        HybridUintConfig(8, 0, 0),   // direct coding
770
0
        HybridUintConfig(9, 0, 0),   // direct coding
771
0
        HybridUintConfig(10, 0, 0),  // direct coding
772
0
        HybridUintConfig(11, 0, 0),  // direct coding
773
0
        HybridUintConfig(12, 0, 0),  // direct coding
774
0
    };
775
524
  } else {
776
524
    JXL_DASSERT(params.uint_method == HistogramParams::HybridUintMethod::kFast);
777
524
    configs = {
778
524
        HybridUintConfig(4, 2, 0),  // default
779
524
        HybridUintConfig(4, 1, 2),  // add parity but less msb
780
524
        HybridUintConfig(0, 0, 0),  // smallest histograms
781
524
        HybridUintConfig(2, 0, 1),  // works well for ctx map
782
524
    };
783
524
  }
784
785
524
  size_t num_histo = clustered_histograms.size();
786
524
  std::vector<uint8_t> is_valid(num_histo);
787
524
  std::vector<size_t> histo_volume(2 * num_histo);
788
524
  std::vector<size_t> histo_offset(2 * num_histo + 1);
789
524
  std::vector<uint32_t> max_value_per_histo(2 * num_histo);
790
791
  // TODO(veluca): do not ignore lz77 commands.
792
793
6.02k
  for (const auto& stream : tokens) {
794
6.02k
    for (const auto& token : stream) {
795
5.24k
      size_t histo = context_map[token.context];
796
5.24k
      histo_volume[histo + (token.is_lz77_length ? num_histo : 0)]++;
797
5.24k
    }
798
6.02k
  }
799
524
  size_t max_histo_volume = 0;
800
1.57k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
801
1.04k
    max_histo_volume = std::max(max_histo_volume, histo_volume[h]);
802
1.04k
    histo_offset[h + 1] = histo_offset[h] + histo_volume[h];
803
1.04k
  }
804
805
524
  const size_t max_vec_size = MaxVectorSize();
806
524
  std::vector<uint32_t> transposed(histo_offset[num_histo * 2] + max_vec_size);
807
524
  {
808
524
    std::vector<size_t> next_offset = histo_offset;  // copy
809
6.02k
    for (const auto& stream : tokens) {
810
6.02k
      for (const auto& token : stream) {
811
5.24k
        size_t histo =
812
5.24k
            context_map[token.context] + (token.is_lz77_length ? num_histo : 0);
813
5.24k
        transposed[next_offset[histo]++] = token.value;
814
5.24k
      }
815
6.02k
    }
816
524
  }
817
1.57k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
818
1.04k
    max_value_per_histo[h] =
819
1.04k
        MaxValue(transposed.data() + histo_offset[h], histo_volume[h]);
820
1.04k
  }
821
524
  uint32_t max_lz77 = 0;
822
1.04k
  for (size_t h = num_histo; h < 2 * num_histo; ++h) {
823
524
    max_lz77 = std::max(max_lz77, MaxValue(transposed.data() + histo_offset[h],
824
524
                                           histo_volume[h]));
825
524
  }
826
827
  // Wider histograms are assigned max cost in PopulationCost anyway
828
  // and therefore will not be used
829
524
  size_t max_alpha = ANS_MAX_ALPHABET_SIZE;
830
831
524
  JXL_ASSIGN_OR_RETURN(
832
524
      AlignedMemory tmp,
833
524
      AlignedMemory::Create(memory_manager, (max_histo_volume + max_vec_size) *
834
524
                                                sizeof(uint32_t)));
835
1.04k
  for (size_t h = 0; h < num_histo; h++) {
836
524
    float best_cost = std::numeric_limits<float>::max();
837
2.09k
    for (HybridUintConfig cfg : configs) {
838
2.09k
      uint32_t max_v = max_value_per_histo[h];
839
2.09k
      size_t capacity;
840
2.09k
      {
841
2.09k
        uint32_t tok, nbits, bits;
842
2.09k
        cfg.Encode(max_v, &tok, &nbits, &bits);
843
2.09k
        tok |= cfg.LsbMask();
844
2.09k
        if (tok >= max_alpha || (lz77.enabled && tok >= lz77.min_symbol)) {
845
0
          continue;  // Not valid config for this context
846
0
        }
847
2.09k
        capacity = tok + 1;
848
2.09k
      }
849
850
0
      Histogram histo;
851
2.09k
      histo.EnsureCapacity(capacity);
852
2.09k
      size_t len = histo_volume[h];
853
2.09k
      uint32_t* data = transposed.data() + histo_offset[h];
854
2.09k
      size_t extra_bits = EstimateTokenCost(data, len, cfg, tmp);
855
2.09k
      uint32_t* tmp_tokens = tmp.address<uint32_t>();
856
23.0k
      for (size_t i = 0; i < len; ++i) {
857
20.9k
        histo.FastAdd(tmp_tokens[i]);
858
20.9k
      }
859
2.09k
      histo.Condition();
860
2.09k
      JXL_ASSIGN_OR_RETURN(float cost, histo.ANSPopulationCost());
861
2.09k
      cost += extra_bits;
862
      // Add signaling cost of the hybriduintconfig itself.
863
2.09k
      cost += CeilLog2Nonzero(cfg.split_exponent + 1);
864
2.09k
      cost += CeilLog2Nonzero(cfg.split_exponent - cfg.msb_in_token + 1);
865
2.09k
      if (cost < best_cost) {
866
1.04k
        uint_config[h] = cfg;
867
1.04k
        best_cost = cost;
868
1.04k
        clustered_histograms[h].swap(histo);
869
1.04k
      }
870
2.09k
    }
871
524
  }
872
873
524
  size_t max_tok = 0;
874
1.04k
  for (size_t h = 0; h < num_histo; ++h) {
875
524
    Histogram& histo = clustered_histograms[h];
876
524
    max_tok = std::max(max_tok, histo.MaxSymbol());
877
524
    size_t len = histo_volume[num_histo + h];
878
524
    if (len == 0) continue;  // E.g. when lz77 not enabled
879
0
    size_t max_histo_tok = max_value_per_histo[num_histo + h];
880
0
    uint32_t tok, nbits, bits;
881
0
    lz77.length_uint_config.Encode(max_histo_tok, &tok, &nbits, &bits);
882
0
    tok |= lz77.length_uint_config.LsbMask();
883
0
    tok += lz77.min_symbol;
884
0
    histo.EnsureCapacity(tok + 1);
885
0
    uint32_t* data = transposed.data() + histo_offset[num_histo + h];
886
0
    uint32_t unused =
887
0
        EstimateTokenCost(data, len, lz77.length_uint_config, tmp);
888
0
    (void)unused;
889
0
    uint32_t* tmp_tokens = tmp.address<uint32_t>();
890
0
    for (size_t i = 0; i < len; ++i) {
891
0
      histo.FastAdd(tmp_tokens[i] + lz77.min_symbol);
892
0
    }
893
0
    histo.Condition();
894
0
    max_tok = std::max(max_tok, histo.MaxSymbol());
895
0
  }
896
897
  // `log_alpha_size - 5` is encoded in the header, so min is 5.
898
524
  size_t log_size = 5;
899
524
  while (max_tok >= (1u << log_size)) ++log_size;
900
901
524
  size_t max_log_alpha_size = use_prefix_code ? PREFIX_MAX_BITS : 8;
902
524
  JXL_ENSURE(log_size <= max_log_alpha_size);
903
904
524
  if (use_prefix_code) {
905
524
    log_alpha_size = PREFIX_MAX_BITS;
906
524
  } else {
907
0
    log_alpha_size = log_size;
908
0
  }
909
910
524
  return true;
911
524
}
912
913
// NOTE: `layer` is only for clustered_entropy; caller does ReclaimAndCharge.
914
// Returns cost (in bits).
915
StatusOr<size_t> EntropyEncodingData::BuildAndStoreEntropyCodes(
916
    JxlMemoryManager* memory_manager, const HistogramParams& params,
917
    const std::vector<std::vector<Token>>& tokens,
918
    const std::vector<Histogram>& builder, BitWriter* writer, LayerType layer,
919
1.57k
    AuxOut* aux_out) {
920
1.57k
  const size_t prev_histograms = encoding_info.size();
921
1.57k
  std::vector<Histogram> clustered_histograms;
922
1.57k
  for (size_t i = 0; i < prev_histograms; ++i) {
923
0
    clustered_histograms.push_back(
924
0
        HistogramFromSymbolInfo(encoding_info[i], use_prefix_code));
925
0
  }
926
1.57k
  size_t context_offset = context_map.size();
927
1.57k
  context_map.resize(context_offset + builder.size());
928
1.57k
  if (builder.size() > 1) {
929
786
    if (!ans_fuzzer_friendly_) {
930
786
      std::vector<uint32_t> histogram_symbols;
931
786
      JXL_RETURN_IF_ERROR(ClusterHistograms(params, builder, kClustersLimit,
932
786
                                            &clustered_histograms,
933
786
                                            &histogram_symbols));
934
1.94M
      for (size_t c = 0; c < builder.size(); ++c) {
935
1.94M
        context_map[context_offset + c] =
936
1.94M
            static_cast<uint8_t>(histogram_symbols[c]);
937
1.94M
      }
938
786
    } else {
939
0
      JXL_ENSURE(encoding_info.empty());
940
0
      std::fill(context_map.begin(), context_map.end(), 0);
941
0
      size_t max_symbol = 0;
942
0
      for (const Histogram& h : builder) {
943
0
        max_symbol = std::max(h.counts.size(), max_symbol);
944
0
      }
945
0
      size_t num_symbols = 1 << CeilLog2Nonzero(max_symbol + 1);
946
0
      clustered_histograms.resize(1);
947
0
      clustered_histograms[0].Clear();
948
0
      for (size_t i = 0; i < num_symbols; i++) {
949
0
        clustered_histograms[0].Add(i);
950
0
      }
951
0
    }
952
786
    if (writer != nullptr) {
953
786
      JXL_RETURN_IF_ERROR(EncodeContextMap(
954
786
          context_map, clustered_histograms.size(), writer, layer, aux_out));
955
786
    }
956
786
  } else {
957
786
    JXL_ENSURE(encoding_info.empty());
958
786
    clustered_histograms.push_back(builder[0]);
959
786
  }
960
1.57k
  if (aux_out != nullptr) {
961
0
    for (size_t i = prev_histograms; i < clustered_histograms.size(); ++i) {
962
0
      aux_out->layer(layer).clustered_entropy +=
963
0
          clustered_histograms[i].ShannonEntropy();
964
0
    }
965
0
  }
966
967
1.57k
  JXL_RETURN_IF_ERROR(
968
1.57k
      ChooseUintConfigs(memory_manager, params, tokens, clustered_histograms));
969
970
1.57k
  SizeWriter size_writer;  // Used if writer == nullptr to estimate costs.
971
1.57k
  size_t cost = use_prefix_code ? 1 : 3;
972
973
1.57k
  if (writer) writer->Write(1, TO_JXL_BOOL(use_prefix_code));
974
1.57k
  if (writer == nullptr) {
975
524
    EncodeUintConfigs(uint_config, &size_writer, log_alpha_size);
976
1.04k
  } else {
977
1.04k
    if (!use_prefix_code) writer->Write(2, log_alpha_size - 5);
978
1.04k
    EncodeUintConfigs(uint_config, writer, log_alpha_size);
979
1.04k
  }
980
1.57k
  if (use_prefix_code) {
981
1.57k
    for (const auto& histo : clustered_histograms) {
982
1.57k
      size_t alphabet_size = std::max<size_t>(1, histo.alphabet_size());
983
1.57k
      if (writer) {
984
1.04k
        StoreVarLenUint16(alphabet_size - 1, writer);
985
1.04k
      } else {
986
524
        StoreVarLenUint16(alphabet_size - 1, &size_writer);
987
524
      }
988
1.57k
    }
989
1.57k
  }
990
1.57k
  cost += size_writer.size;
991
3.14k
  for (size_t c = prev_histograms; c < clustered_histograms.size(); ++c) {
992
1.57k
    size_t alphabet_size = clustered_histograms[c].alphabet_size();
993
1.57k
    encoding_info.emplace_back();
994
1.57k
    encoding_info.back().resize(alphabet_size);
995
1.57k
    BitWriter* histo_writer = writer;
996
1.57k
    if (params.streaming_mode) {
997
0
      encoded_histograms.emplace_back(memory_manager);
998
0
      histo_writer = &encoded_histograms.back();
999
0
    }
1000
1.57k
    const auto& body = [&]() -> Status {
1001
1.57k
      JXL_ASSIGN_OR_RETURN(size_t ans_cost,
1002
1.57k
                           BuildAndStoreANSEncodingData(
1003
1.57k
                               memory_manager, params.ans_histogram_strategy,
1004
1.57k
                               clustered_histograms[c], histo_writer));
1005
1.57k
      cost += ans_cost;
1006
1.57k
      return true;
1007
1.57k
    };
1008
1.57k
    if (histo_writer) {
1009
1.04k
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1010
1.04k
          256 + alphabet_size * 24, layer, aux_out, body,
1011
1.04k
          /*finished_histogram=*/true));
1012
1.04k
    } else {
1013
524
      JXL_RETURN_IF_ERROR(body());
1014
524
    }
1015
1.57k
    if (params.streaming_mode) {
1016
0
      JXL_RETURN_IF_ERROR(writer->AppendUnaligned(*histo_writer));
1017
0
    }
1018
1.57k
  }
1019
1.57k
  return cost;
1020
1.57k
}
1021
1022
template <typename Writer>
1023
void EncodeUintConfig(const HybridUintConfig uint_config, Writer* writer,
1024
1.57k
                      size_t log_alpha_size) {
1025
1.57k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
1.57k
                uint_config.split_exponent);
1027
1.57k
  if (uint_config.split_exponent == log_alpha_size) {
1028
0
    return;  // msb/lsb don't matter.
1029
0
  }
1030
1.57k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
1.57k
  writer->Write(nbits, uint_config.msb_in_token);
1032
1.57k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
1.57k
                          uint_config.msb_in_token + 1);
1034
1.57k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
1.57k
}
void jxl::EncodeUintConfig<jxl::SizeWriter>(jxl::HybridUintConfig, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1024
524
                      size_t log_alpha_size) {
1025
524
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
524
                uint_config.split_exponent);
1027
524
  if (uint_config.split_exponent == log_alpha_size) {
1028
0
    return;  // msb/lsb don't matter.
1029
0
  }
1030
524
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
524
  writer->Write(nbits, uint_config.msb_in_token);
1032
524
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
524
                          uint_config.msb_in_token + 1);
1034
524
  writer->Write(nbits, uint_config.lsb_in_token);
1035
524
}
void jxl::EncodeUintConfig<jxl::BitWriter>(jxl::HybridUintConfig, jxl::BitWriter*, unsigned long)
Line
Count
Source
1024
1.04k
                      size_t log_alpha_size) {
1025
1.04k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
1.04k
                uint_config.split_exponent);
1027
1.04k
  if (uint_config.split_exponent == log_alpha_size) {
1028
0
    return;  // msb/lsb don't matter.
1029
0
  }
1030
1.04k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
1.04k
  writer->Write(nbits, uint_config.msb_in_token);
1032
1.04k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
1.04k
                          uint_config.msb_in_token + 1);
1034
1.04k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
1.04k
}
1036
template <typename Writer>
1037
void EncodeUintConfigs(const std::vector<HybridUintConfig>& uint_config,
1038
1.57k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
1.57k
  for (const auto& cfg : uint_config) {
1041
1.57k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
1.57k
  }
1043
1.57k
}
void jxl::EncodeUintConfigs<jxl::BitWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::BitWriter*, unsigned long)
Line
Count
Source
1038
1.04k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
1.04k
  for (const auto& cfg : uint_config) {
1041
1.04k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
1.04k
  }
1043
1.04k
}
void jxl::EncodeUintConfigs<jxl::SizeWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1038
524
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
524
  for (const auto& cfg : uint_config) {
1041
524
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
524
  }
1043
524
}
1044
template void EncodeUintConfigs(const std::vector<HybridUintConfig>&,
1045
                                BitWriter*, size_t);
1046
1047
Status EncodeHistograms(const EntropyEncodingData& codes, BitWriter* writer,
1048
0
                        LayerType layer, AuxOut* aux_out) {
1049
0
  return writer->WithMaxBits(
1050
0
      128 + kClustersLimit * 136, layer, aux_out,
1051
0
      [&]() -> Status {
1052
0
        JXL_RETURN_IF_ERROR(Bundle::Write(codes.lz77, writer, layer, aux_out));
1053
0
        if (codes.lz77.enabled) {
1054
0
          EncodeUintConfig(codes.lz77.length_uint_config, writer,
1055
0
                           /*log_alpha_size=*/8);
1056
0
        }
1057
0
        JXL_RETURN_IF_ERROR(EncodeContextMap(codes.context_map,
1058
0
                                             codes.encoding_info.size(), writer,
1059
0
                                             layer, aux_out));
1060
0
        writer->Write(1, TO_JXL_BOOL(codes.use_prefix_code));
1061
0
        size_t log_alpha_size = 8;
1062
0
        if (codes.use_prefix_code) {
1063
0
          log_alpha_size = PREFIX_MAX_BITS;
1064
0
        } else {
1065
0
          log_alpha_size = 8;  // streaming_mode
1066
0
          writer->Write(2, log_alpha_size - 5);
1067
0
        }
1068
0
        EncodeUintConfigs(codes.uint_config, writer, log_alpha_size);
1069
0
        if (codes.use_prefix_code) {
1070
0
          for (const auto& info : codes.encoding_info) {
1071
0
            StoreVarLenUint16(info.size() - 1, writer);
1072
0
          }
1073
0
        }
1074
0
        for (const auto& histo_writer : codes.encoded_histograms) {
1075
0
          JXL_RETURN_IF_ERROR(writer->AppendUnaligned(histo_writer));
1076
0
        }
1077
0
        return true;
1078
0
      },
1079
0
      /*finished_histogram=*/true);
1080
0
}
1081
1082
StatusOr<size_t> BuildAndEncodeHistograms(
1083
    JxlMemoryManager* memory_manager, const HistogramParams& params,
1084
    size_t num_contexts, std::vector<std::vector<Token>>& tokens,
1085
    EntropyEncodingData* codes, BitWriter* writer, LayerType layer,
1086
1.57k
    AuxOut* aux_out) {
1087
  // TODO(Ivan): presumably not needed - default
1088
  // if (params.initialize_global_state) codes->lz77.enabled = false;
1089
1.57k
  codes->lz77.nonserialized_distance_context = num_contexts;
1090
1.57k
  codes->lz77.min_symbol = params.force_huffman ? 512 : 224;
1091
1.57k
  std::vector<std::vector<Token>> tokens_lz77 =
1092
1.57k
      ApplyLZ77(params, num_contexts, tokens, codes->lz77);
1093
1.57k
  if (!tokens_lz77.empty()) codes->lz77.enabled = true;
1094
1.57k
  if (ans_fuzzer_friendly_) {
1095
0
    codes->lz77.length_uint_config = HybridUintConfig(10, 0, 0);
1096
0
    codes->lz77.min_symbol = 2048;
1097
0
  }
1098
1099
1.57k
  size_t cost = 0;
1100
1.57k
  const size_t max_contexts = std::min(num_contexts, kClustersLimit);
1101
1.57k
  const auto& body = [&]() -> Status {
1102
1.57k
    if (writer) {
1103
1.04k
      JXL_RETURN_IF_ERROR(Bundle::Write(codes->lz77, writer, layer, aux_out));
1104
1.04k
    } else {
1105
524
      size_t ebits, bits;
1106
524
      JXL_RETURN_IF_ERROR(Bundle::CanEncode(codes->lz77, &ebits, &bits));
1107
524
      cost += bits;
1108
524
    }
1109
1.57k
    if (codes->lz77.enabled) {
1110
0
      if (writer) {
1111
0
        size_t b = writer->BitsWritten();
1112
0
        EncodeUintConfig(codes->lz77.length_uint_config, writer,
1113
0
                         /*log_alpha_size=*/8);
1114
0
        cost += writer->BitsWritten() - b;
1115
0
      } else {
1116
0
        SizeWriter size_writer;
1117
0
        EncodeUintConfig(codes->lz77.length_uint_config, &size_writer,
1118
0
                         /*log_alpha_size=*/8);
1119
0
        cost += size_writer.size;
1120
0
      }
1121
0
      num_contexts += 1;
1122
0
      tokens = std::move(tokens_lz77);
1123
0
    }
1124
1.57k
    size_t total_tokens = 0;
1125
    // Build histograms.
1126
1.57k
    std::vector<Histogram> builder(num_contexts);
1127
1.57k
    HybridUintConfig uint_config = params.UintConfig();
1128
1.57k
    if (ans_fuzzer_friendly_) {
1129
0
      uint_config = HybridUintConfig(10, 0, 0);
1130
0
    }
1131
7.07k
    for (const auto& stream : tokens) {
1132
7.07k
      if (codes->lz77.enabled) {
1133
0
        for (const auto& token : stream) {
1134
0
          total_tokens++;
1135
0
          uint32_t tok, nbits, bits;
1136
0
          (token.is_lz77_length ? codes->lz77.length_uint_config : uint_config)
1137
0
              .Encode(token.value, &tok, &nbits, &bits);
1138
0
          tok += token.is_lz77_length ? codes->lz77.min_symbol : 0;
1139
0
          JXL_DASSERT(token.context < num_contexts);
1140
0
          builder[token.context].Add(tok);
1141
0
        }
1142
7.07k
      } else if (num_contexts == 1) {
1143
30.6k
        for (const auto& token : stream) {
1144
30.6k
          total_tokens++;
1145
30.6k
          uint32_t tok, nbits, bits;
1146
30.6k
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1147
30.6k
          builder[0].Add(tok);
1148
30.6k
        }
1149
6.28k
      } else {
1150
6.28k
        for (const auto& token : stream) {
1151
6.02k
          total_tokens++;
1152
6.02k
          uint32_t tok, nbits, bits;
1153
6.02k
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1154
6.02k
          JXL_DASSERT(token.context < num_contexts);
1155
6.02k
          builder[token.context].Add(tok);
1156
6.02k
        }
1157
6.28k
      }
1158
7.07k
    }
1159
1160
1.57k
    if (params.add_missing_symbols) {
1161
0
      for (size_t c = 0; c < num_contexts; ++c) {
1162
0
        for (int symbol = 0; symbol < ANS_MAX_ALPHABET_SIZE; ++symbol) {
1163
0
          builder[c].Add(symbol);
1164
0
        }
1165
0
      }
1166
0
    }
1167
1168
1.57k
    if (params.initialize_global_state) {
1169
1.57k
      bool use_prefix_code =
1170
1.57k
          params.force_huffman || total_tokens < 100 ||
1171
0
          params.clustering == HistogramParams::ClusteringType::kFastest ||
1172
0
          ans_fuzzer_friendly_;
1173
1.57k
      if (!use_prefix_code) {
1174
0
        bool all_singleton = true;
1175
0
        for (size_t i = 0; i < num_contexts; i++) {
1176
0
          if (builder[i].ShannonEntropy() >= 1e-5) {
1177
0
            all_singleton = false;
1178
0
          }
1179
0
        }
1180
0
        if (all_singleton) {
1181
0
          use_prefix_code = true;
1182
0
        }
1183
0
      }
1184
1.57k
      codes->use_prefix_code = use_prefix_code;
1185
1.57k
    }
1186
1187
1.57k
    if (params.add_fixed_histograms) {
1188
      // TODO(szabadka) Add more fixed histograms.
1189
      // TODO(szabadka) Reduce alphabet size by choosing a non-default
1190
      // uint_config.
1191
0
      const size_t alphabet_size = ANS_MAX_ALPHABET_SIZE;
1192
0
      codes->log_alpha_size = 8;
1193
0
      JXL_ENSURE(alphabet_size == 1u << codes->log_alpha_size);
1194
0
      static_assert(ANS_MAX_ALPHABET_SIZE <= ANS_TAB_SIZE,
1195
0
                    "Alphabet does not fit table");
1196
0
      codes->encoding_info.emplace_back();
1197
0
      codes->encoding_info.back().resize(alphabet_size);
1198
0
      codes->encoded_histograms.emplace_back(memory_manager);
1199
0
      BitWriter* histo_writer = &codes->encoded_histograms.back();
1200
0
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1201
0
          256 + alphabet_size * 24, LayerType::Header, nullptr,
1202
0
          [&]() -> Status {
1203
0
            JXL_ASSIGN_OR_RETURN(
1204
0
                size_t ans_cost,
1205
0
                codes->BuildAndStoreANSEncodingData(
1206
0
                    memory_manager, params.ans_histogram_strategy,
1207
0
                    Histogram::Flat(alphabet_size, ANS_TAB_SIZE),
1208
0
                    histo_writer));
1209
0
            (void)ans_cost;
1210
0
            return true;
1211
0
          }));
1212
0
    }
1213
1214
    // Encode histograms.
1215
1.57k
    JXL_ASSIGN_OR_RETURN(
1216
1.57k
        size_t entropy_bits,
1217
1.57k
        codes->BuildAndStoreEntropyCodes(memory_manager, params, tokens,
1218
1.57k
                                         builder, writer, layer, aux_out));
1219
1.57k
    cost += entropy_bits;
1220
1.57k
    return true;
1221
1.57k
  };
1222
1.57k
  if (writer) {
1223
1.04k
    JXL_RETURN_IF_ERROR(writer->WithMaxBits(
1224
1.04k
        128 + num_contexts * 40 + max_contexts * 96, layer, aux_out, body,
1225
1.04k
        /*finished_histogram=*/true));
1226
1.04k
  } else {
1227
524
    JXL_RETURN_IF_ERROR(body());
1228
524
  }
1229
1230
1.57k
  if (aux_out != nullptr) {
1231
0
    aux_out->layer(layer).num_clustered_histograms +=
1232
0
        codes->encoding_info.size();
1233
0
  }
1234
1.57k
  return cost;
1235
1.57k
}
1236
1237
size_t WriteTokens(const std::vector<Token>& tokens,
1238
                   const EntropyEncodingData& codes, size_t context_offset,
1239
1.31k
                   BitWriter* writer) {
1240
1.31k
  size_t num_extra_bits = 0;
1241
1.31k
  if (codes.use_prefix_code) {
1242
16.2k
    for (const auto& token : tokens) {
1243
16.2k
      uint32_t tok, nbits, bits;
1244
16.2k
      size_t histo = codes.context_map[context_offset + token.context];
1245
16.2k
      (token.is_lz77_length ? codes.lz77.length_uint_config
1246
16.2k
                            : codes.uint_config[histo])
1247
16.2k
          .Encode(token.value, &tok, &nbits, &bits);
1248
16.2k
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1249
      // Combine two calls to the BitWriter. Equivalent to:
1250
      // writer->Write(codes.encoding_info[histo][tok].depth,
1251
      //               codes.encoding_info[histo][tok].bits);
1252
      // writer->Write(nbits, bits);
1253
16.2k
      uint64_t data = codes.encoding_info[histo][tok].bits;
1254
16.2k
      data |= static_cast<uint64_t>(bits)
1255
16.2k
              << codes.encoding_info[histo][tok].depth;
1256
16.2k
      writer->Write(codes.encoding_info[histo][tok].depth + nbits, data);
1257
16.2k
      num_extra_bits += nbits;
1258
16.2k
    }
1259
1.31k
    return num_extra_bits;
1260
1.31k
  }
1261
0
  std::vector<uint64_t> out;
1262
0
  std::vector<uint8_t> out_nbits;
1263
0
  out.reserve(tokens.size());
1264
0
  out_nbits.reserve(tokens.size());
1265
0
  uint64_t allbits = 0;
1266
0
  size_t numallbits = 0;
1267
  // Writes in *reversed* order.
1268
0
  auto addbits = [&](size_t bits, size_t nbits) {
1269
0
    if (JXL_UNLIKELY(nbits)) {
1270
0
      JXL_DASSERT(bits >> nbits == 0);
1271
0
      if (JXL_UNLIKELY(numallbits + nbits > BitWriter::kMaxBitsPerCall)) {
1272
0
        out.push_back(allbits);
1273
0
        out_nbits.push_back(numallbits);
1274
0
        numallbits = allbits = 0;
1275
0
      }
1276
0
      allbits <<= nbits;
1277
0
      allbits |= bits;
1278
0
      numallbits += nbits;
1279
0
    }
1280
0
  };
1281
0
  const int end = tokens.size();
1282
0
  ANSCoder ans;
1283
0
  if (codes.lz77.enabled || codes.context_map.size() > 1) {
1284
0
    for (int i = end - 1; i >= 0; --i) {
1285
0
      const Token token = tokens[i];
1286
0
      const uint8_t histo = codes.context_map[context_offset + token.context];
1287
0
      uint32_t tok, nbits, bits;
1288
0
      (token.is_lz77_length ? codes.lz77.length_uint_config
1289
0
                            : codes.uint_config[histo])
1290
0
          .Encode(tokens[i].value, &tok, &nbits, &bits);
1291
0
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1292
0
      const ANSEncSymbolInfo& info = codes.encoding_info[histo][tok];
1293
0
      JXL_DASSERT(info.freq_ > 0);
1294
      // Extra bits first as this is reversed.
1295
0
      addbits(bits, nbits);
1296
0
      num_extra_bits += nbits;
1297
0
      uint8_t ans_nbits = 0;
1298
0
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1299
0
      addbits(ans_bits, ans_nbits);
1300
0
    }
1301
0
  } else {
1302
0
    for (int i = end - 1; i >= 0; --i) {
1303
0
      uint32_t tok, nbits, bits;
1304
0
      codes.uint_config[0].Encode(tokens[i].value, &tok, &nbits, &bits);
1305
0
      const ANSEncSymbolInfo& info = codes.encoding_info[0][tok];
1306
      // Extra bits first as this is reversed.
1307
0
      addbits(bits, nbits);
1308
0
      num_extra_bits += nbits;
1309
0
      uint8_t ans_nbits = 0;
1310
0
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1311
0
      addbits(ans_bits, ans_nbits);
1312
0
    }
1313
0
  }
1314
0
  const uint32_t state = ans.GetState();
1315
0
  writer->Write(32, state);
1316
0
  writer->Write(numallbits, allbits);
1317
0
  for (int i = out.size(); i > 0; --i) {
1318
0
    writer->Write(out_nbits[i - 1], out[i - 1]);
1319
0
  }
1320
0
  return num_extra_bits;
1321
0
}
1322
1323
Status WriteTokens(const std::vector<Token>& tokens,
1324
                   const EntropyEncodingData& codes, size_t context_offset,
1325
1.04k
                   BitWriter* writer, LayerType layer, AuxOut* aux_out) {
1326
  // Theoretically, we could have 15 prefix code bits + 31 extra bits.
1327
1.04k
  return writer->WithMaxBits(
1328
1.04k
      46 * tokens.size() + 32 * 1024 * 4, layer, aux_out, [&] {
1329
1.04k
        size_t num_extra_bits =
1330
1.04k
            WriteTokens(tokens, codes, context_offset, writer);
1331
1.04k
        if (aux_out != nullptr) {
1332
0
          aux_out->layer(layer).extra_bits += num_extra_bits;
1333
0
        }
1334
1.04k
        return true;
1335
1.04k
      });
1336
1.04k
}
1337
1338
0
void SetANSFuzzerFriendly(bool ans_fuzzer_friendly) {
1339
#if JXL_IS_DEBUG_BUILD  // Guard against accidental / malicious changes.
1340
0
  ans_fuzzer_friendly_ = ans_fuzzer_friendly;
1341
0
#endif
1342
0
}
1343
1344
HistogramParams HistogramParams::ForModular(
1345
    const CompressParams& cparams,
1346
524
    const std::vector<uint8_t>& extra_dc_precision, bool streaming_mode) {
1347
524
  HistogramParams params;
1348
524
  params.streaming_mode = streaming_mode;
1349
524
  if (cparams.speed_tier > SpeedTier::kKitten) {
1350
524
    params.clustering = HistogramParams::ClusteringType::kFast;
1351
524
    params.ans_histogram_strategy =
1352
524
        cparams.speed_tier > SpeedTier::kThunder
1353
524
            ? HistogramParams::ANSHistogramStrategy::kFast
1354
524
            : HistogramParams::ANSHistogramStrategy::kApproximate;
1355
524
    params.lz77_method =
1356
524
        cparams.modular_mode && cparams.speed_tier <= SpeedTier::kHare
1357
524
            ? HistogramParams::LZ77Method::kRLE
1358
524
            : HistogramParams::LZ77Method::kNone;
1359
    // Near-lossless DC, as well as modular mode, require choosing hybrid uint
1360
    // more carefully.
1361
524
    if ((!extra_dc_precision.empty() && extra_dc_precision[0] != 0) ||
1362
262
        (cparams.modular_mode && cparams.speed_tier < SpeedTier::kCheetah)) {
1363
262
      params.uint_method = HistogramParams::HybridUintMethod::kFast;
1364
262
    } else {
1365
262
      params.uint_method = HistogramParams::HybridUintMethod::kNone;
1366
262
    }
1367
524
  } else if (cparams.speed_tier <= SpeedTier::kTortoise) {
1368
0
    params.lz77_method = HistogramParams::LZ77Method::kOptimal;
1369
0
  } else {
1370
0
    params.lz77_method = HistogramParams::LZ77Method::kLZ77;
1371
0
  }
1372
524
  if (cparams.decoding_speed_tier >= 2) {
1373
0
    params.max_histograms = 12;
1374
0
  }
1375
    // No predictor requires LZ77 to compress residuals.
1376
    // Effort 3 and lower have forced predictors, so kNone is set.
1377
524
    if (cparams.options.predictor == Predictor::Zero && cparams.modular_mode) {
1378
0
        params.lz77_method = cparams.speed_tier >= SpeedTier::kFalcon
1379
0
            ? HistogramParams::LZ77Method::kNone
1380
0
            : cparams.speed_tier >= SpeedTier::kHare
1381
0
            ? HistogramParams::LZ77Method::kRLE
1382
0
            : cparams.speed_tier >= SpeedTier::kKitten
1383
0
            ? HistogramParams::LZ77Method::kLZ77
1384
0
            : HistogramParams::LZ77Method::kOptimal;
1385
0
    }
1386
524
  return params;
1387
524
}
1388
}  // namespace jxl