Coverage Report

Created: 2026-09-13 07:02

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