Coverage Report

Created: 2025-11-16 07:22

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.31M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
6.31M
  JXL_DASSERT(n <= 255);
56
6.31M
  if (n == 0) {
57
511k
    writer->Write(1, 0);
58
5.80M
  } else {
59
5.80M
    writer->Write(1, 1);
60
5.80M
    size_t nbits = FloorLog2Nonzero(n);
61
5.80M
    writer->Write(3, nbits);
62
5.80M
    writer->Write(nbits, n - (1ULL << nbits));
63
5.80M
  }
64
6.31M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
54
6.10M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
6.10M
  JXL_DASSERT(n <= 255);
56
6.10M
  if (n == 0) {
57
495k
    writer->Write(1, 0);
58
5.61M
  } else {
59
5.61M
    writer->Write(1, 1);
60
5.61M
    size_t nbits = FloorLog2Nonzero(n);
61
5.61M
    writer->Write(3, nbits);
62
5.61M
    writer->Write(nbits, n - (1ULL << nbits));
63
5.61M
  }
64
6.10M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
54
204k
void StoreVarLenUint8(size_t n, Writer* writer) {
55
204k
  JXL_DASSERT(n <= 255);
56
204k
  if (n == 0) {
57
16.2k
    writer->Write(1, 0);
58
187k
  } else {
59
187k
    writer->Write(1, 1);
60
187k
    size_t nbits = FloorLog2Nonzero(n);
61
187k
    writer->Write(3, nbits);
62
187k
    writer->Write(nbits, n - (1ULL << nbits));
63
187k
  }
64
204k
}
65
66
template <typename Writer>
67
35.5k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
35.5k
  JXL_DASSERT(n <= 65535);
69
35.5k
  if (n == 0) {
70
455
    writer->Write(1, 0);
71
35.0k
  } else {
72
35.0k
    writer->Write(1, 1);
73
35.0k
    size_t nbits = FloorLog2Nonzero(n);
74
35.0k
    writer->Write(4, nbits);
75
35.0k
    writer->Write(nbits, n - (1ULL << nbits));
76
35.0k
  }
77
35.5k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
67
9.52k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
9.52k
  JXL_DASSERT(n <= 65535);
69
9.52k
  if (n == 0) {
70
455
    writer->Write(1, 0);
71
9.06k
  } else {
72
9.06k
    writer->Write(1, 1);
73
9.06k
    size_t nbits = FloorLog2Nonzero(n);
74
9.06k
    writer->Write(4, nbits);
75
9.06k
    writer->Write(nbits, n - (1ULL << nbits));
76
9.06k
  }
77
9.52k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
67
26.0k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
26.0k
  JXL_DASSERT(n <= 65535);
69
26.0k
  if (n == 0) {
70
0
    writer->Write(1, 0);
71
26.0k
  } else {
72
26.0k
    writer->Write(1, 1);
73
26.0k
    size_t nbits = FloorLog2Nonzero(n);
74
26.0k
    writer->Write(4, nbits);
75
26.0k
    writer->Write(nbits, n - (1ULL << nbits));
76
26.0k
  }
77
26.0k
}
78
79
class ANSEncodingHistogram {
80
 public:
81
155k
  const std::vector<ANSHistBin>& Counts() const { return counts_; }
82
839k
  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
839k
      HistogramParams::ANSHistogramStrategy ans_histogram_strategy) {
87
839k
    ANSEncodingHistogram result;
88
89
839k
    result.alphabet_size_ = histo.alphabet_size();
90
839k
    if (result.alphabet_size_ > ANS_MAX_ALPHABET_SIZE)
91
0
      return JXL_FAILURE("Too many entries in an ANS histogram");
92
93
839k
    if (result.alphabet_size_ > 0) {
94
      // Flat code
95
839k
      result.method_ = 0;
96
839k
      result.num_symbols_ = result.alphabet_size_;
97
839k
      result.counts_ = CreateFlatHistogram(result.alphabet_size_, ANS_TAB_SIZE);
98
      // in this case length can be non-suitable for SIMD - fix it
99
839k
      result.counts_.resize(histo.counts.size());
100
839k
      SizeWriter writer;
101
839k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
102
839k
      result.cost_ = writer.size + EstimateDataBitsFlat(histo);
103
839k
    } 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
839k
    size_t symbol_count = 0;
112
30.5M
    for (size_t n = 0; n < result.alphabet_size_; ++n) {
113
29.6M
      if (histo.counts[n] > 0) {
114
13.0M
        if (symbol_count < kMaxNumSymbolsForSmallCode) {
115
1.60M
          result.symbols_[symbol_count] = n;
116
1.60M
        }
117
13.0M
        ++symbol_count;
118
13.0M
      }
119
29.6M
    }
120
839k
    result.num_symbols_ = symbol_count;
121
839k
    if (symbol_count == 1) {
122
      // Single-bin histogram
123
74.9k
      result.method_ = 1;
124
74.9k
      result.counts_ = histo.counts;
125
74.9k
      result.counts_[result.symbols_[0]] = ANS_TAB_SIZE;
126
74.9k
      SizeWriter writer;
127
74.9k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
128
74.9k
      result.cost_ = writer.size;
129
74.9k
      return result;
130
74.9k
    }
131
132
    // Here min 2 symbols
133
764k
    ANSEncodingHistogram normalized = result;
134
2.98M
    auto try_shift = [&](uint32_t shift) -> Status {
135
      // `shift = 12` and `shift = 11` are the same
136
2.98M
      normalized.method_ = std::min(shift, ANS_LOG_TAB_SIZE - 1) + 1;
137
138
2.98M
      if (!normalized.RebalanceHistogram(histo)) {
139
0
        return JXL_FAILURE("Logic error: couldn't rebalance a histogram");
140
0
      }
141
2.98M
      SizeWriter writer;
142
2.98M
      JXL_RETURN_IF_ERROR(normalized.Encode(&writer));
143
2.98M
      normalized.cost_ = writer.size + normalized.EstimateDataBits(histo);
144
2.98M
      if (normalized.cost_ < result.cost_) {
145
756k
        result = normalized;
146
756k
      }
147
2.98M
      return true;
148
2.98M
    };
149
150
764k
    switch (ans_histogram_strategy) {
151
18.3k
      case HistogramParams::ANSHistogramStrategy::kPrecise:
152
237k
        for (uint32_t shift = 0; shift < ANS_LOG_TAB_SIZE; shift++) {
153
219k
          JXL_RETURN_IF_ERROR(try_shift(shift));
154
219k
        }
155
18.3k
        break;
156
130k
      case HistogramParams::ANSHistogramStrategy::kApproximate:
157
1.04M
        for (uint32_t shift = 0; shift <= ANS_LOG_TAB_SIZE; shift += 2) {
158
913k
          JXL_RETURN_IF_ERROR(try_shift(shift));
159
913k
        }
160
130k
        break;
161
616k
      case HistogramParams::ANSHistogramStrategy::kFast:
162
616k
        JXL_RETURN_IF_ERROR(try_shift(0));
163
616k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE / 2));
164
616k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE));
165
616k
        break;
166
764k
    }
167
168
      // Sanity check
169
764k
#if JXL_IS_DEBUG_BUILD
170
764k
    JXL_ENSURE(histo.counts.size() == result.counts_.size());
171
764k
    ANSHistBin total = 0;  // Used only in assert.
172
30.1M
    for (size_t i = 0; i < result.alphabet_size_; ++i) {
173
29.4M
      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
29.4M
      JXL_ENSURE(result.method_ == 0 ||
177
29.4M
                 (histo.counts[i] > 0) == (result.counts_[i] > 0));
178
      // Check accuracy of the histogram values
179
29.4M
      if (result.method_ > 0 && result.counts_[i] > 0 &&
180
9.86M
          i != result.omit_pos_) {
181
9.22M
        int logcounts = FloorLog2Nonzero<uint32_t>(result.counts_[i]);
182
9.22M
        int bitcount =
183
9.22M
            GetPopulationCountPrecision(logcounts, result.method_ - 1);
184
9.22M
        int drop_bits = logcounts - bitcount;
185
        // Check that the value is divisible by 2^drop_bits
186
9.22M
        JXL_ENSURE((result.counts_[i] & ((1 << drop_bits) - 1)) == 0);
187
9.22M
      }
188
29.4M
      total += result.counts_[i];
189
29.4M
    }
190
3.35M
    for (size_t i = result.alphabet_size_; i < result.counts_.size(); ++i) {
191
2.58M
      JXL_ENSURE(histo.counts[i] == 0);
192
2.58M
      JXL_ENSURE(result.counts_[i] == 0);
193
2.58M
    }
194
764k
    JXL_ENSURE((histo.total_count == 0) || (total == ANS_TAB_SIZE));
195
764k
#endif
196
764k
    return result;
197
764k
  }
198
199
  template <typename Writer>
200
4.04M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
4.04M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
4.04M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
845k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
845k
      writer->Write(1, 1);
211
845k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
845k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
845k
      return true;
216
845k
    }
217
218
    /// Small tree.
219
3.19M
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
112k
      writer->Write(1, 1);
222
112k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
112k
      } else {
226
112k
        writer->Write(1, num_symbols_ - 1);
227
258k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
146k
          StoreVarLenUint8(symbols_[i], writer);
229
146k
        }
230
112k
      }
231
112k
      if (num_symbols_ == 2) {
232
33.2k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
33.2k
      }
234
235
112k
      return true;
236
112k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
3.08M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
3.08M
    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.08M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
3.08M
    int log = FloorLog2Nonzero(method_);
249
3.08M
    writer->Write(log, (1 << log) - 1);
250
3.08M
    if (log != upper_bound_log) writer->Write(1, 0);
251
3.08M
    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.08M
    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.08M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
3.08M
    size_t last = 0;
262
123M
    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
120M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
112M
          counts_[i] != counts_[last]) {
270
57.4M
        same[last] = i - last;
271
57.4M
        last = i;
272
57.4M
      }
273
120M
    }
274
275
3.08M
    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.08M
    int omit_width = 10;
281
123M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
120M
      if (i != omit_pos_ && counts_[i] > 0) {
283
48.5M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
48.5M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
48.5M
      }
286
120M
    }
287
3.08M
    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.08M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
3.08M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
3.08M
    };
294
3.08M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
3.08M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
3.08M
    };
297
3.08M
    constexpr uint8_t kMinReps = 5;
298
3.08M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
72.5M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
69.4M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
69.4M
                    kBitWidthSymbols[bit_width[i]]);
303
69.4M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
2.23M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
2.23M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
2.23M
        i += same[i] - 1;
308
2.23M
      }
309
69.4M
    }
310
    // Encode additional bits of accuracy
311
3.08M
    uint32_t shift = method_ - 1;
312
3.08M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
52.6M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
50.3M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
34.5M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
34.5M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
34.5M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
34.5M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
34.5M
        }
320
50.3M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.55M
          i += same[i] - 1;
323
1.55M
        }
324
50.3M
      }
325
2.24M
    }
326
3.08M
    return true;
327
3.08M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::SizeWriter>(jxl::SizeWriter*)
Line
Count
Source
200
3.89M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
3.89M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
3.89M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
839k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
839k
      writer->Write(1, 1);
211
839k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
839k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
839k
      return true;
216
839k
    }
217
218
    /// Small tree.
219
3.05M
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
107k
      writer->Write(1, 1);
222
107k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
107k
      } else {
226
107k
        writer->Write(1, num_symbols_ - 1);
227
246k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
139k
          StoreVarLenUint8(symbols_[i], writer);
229
139k
        }
230
107k
      }
231
107k
      if (num_symbols_ == 2) {
232
32.1k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
32.1k
      }
234
235
107k
      return true;
236
107k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
2.94M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
2.94M
    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.94M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
2.94M
    int log = FloorLog2Nonzero(method_);
249
2.94M
    writer->Write(log, (1 << log) - 1);
250
2.94M
    if (log != upper_bound_log) writer->Write(1, 0);
251
2.94M
    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.94M
    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.94M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
2.94M
    size_t last = 0;
262
119M
    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
116M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
108M
          counts_[i] != counts_[last]) {
270
55.2M
        same[last] = i - last;
271
55.2M
        last = i;
272
55.2M
      }
273
116M
    }
274
275
2.94M
    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.94M
    int omit_width = 10;
281
119M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
116M
      if (i != omit_pos_ && counts_[i] > 0) {
283
46.6M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
46.6M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
46.6M
      }
286
116M
    }
287
2.94M
    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.94M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
2.94M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
2.94M
    };
294
2.94M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
2.94M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
2.94M
    };
297
2.94M
    constexpr uint8_t kMinReps = 5;
298
2.94M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
69.7M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
66.7M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
66.7M
                    kBitWidthSymbols[bit_width[i]]);
303
66.7M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
2.18M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
2.18M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
2.18M
        i += same[i] - 1;
308
2.18M
      }
309
66.7M
    }
310
    // Encode additional bits of accuracy
311
2.94M
    uint32_t shift = method_ - 1;
312
2.94M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
51.5M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
49.3M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
33.7M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
33.7M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
33.7M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
33.7M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
33.7M
        }
320
49.3M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.53M
          i += same[i] - 1;
323
1.53M
        }
324
49.3M
      }
325
2.19M
    }
326
2.94M
    return true;
327
2.94M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::BitWriter>(jxl::BitWriter*)
Line
Count
Source
200
148k
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
148k
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
148k
    if (method_ == 0) {
207
      // Mark non-small tree.
208
5.31k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
5.31k
      writer->Write(1, 1);
211
5.31k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
5.31k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
5.31k
      return true;
216
5.31k
    }
217
218
    /// Small tree.
219
142k
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
5.63k
      writer->Write(1, 1);
222
5.63k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
5.63k
      } else {
226
5.63k
        writer->Write(1, num_symbols_ - 1);
227
12.3k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
6.72k
          StoreVarLenUint8(symbols_[i], writer);
229
6.72k
        }
230
5.63k
      }
231
5.63k
      if (num_symbols_ == 2) {
232
1.08k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
1.08k
      }
234
235
5.63k
      return true;
236
5.63k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
137k
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
137k
    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
137k
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
137k
    int log = FloorLog2Nonzero(method_);
249
137k
    writer->Write(log, (1 << log) - 1);
250
137k
    if (log != upper_bound_log) writer->Write(1, 0);
251
137k
    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
137k
    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
137k
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
137k
    size_t last = 0;
262
3.99M
    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
3.85M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
3.52M
          counts_[i] != counts_[last]) {
270
2.19M
        same[last] = i - last;
271
2.19M
        last = i;
272
2.19M
      }
273
3.85M
    }
274
275
137k
    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
137k
    int omit_width = 10;
281
3.99M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
3.85M
      if (i != omit_pos_ && counts_[i] > 0) {
283
1.92M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
1.92M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
1.92M
      }
286
3.85M
    }
287
137k
    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
137k
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
137k
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
137k
    };
294
137k
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
137k
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
137k
    };
297
137k
    constexpr uint8_t kMinReps = 5;
298
137k
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
2.82M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
2.68M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
2.68M
                    kBitWidthSymbols[bit_width[i]]);
303
2.68M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
54.7k
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
54.7k
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
54.7k
        i += same[i] - 1;
308
54.7k
      }
309
2.68M
    }
310
    // Encode additional bits of accuracy
311
137k
    uint32_t shift = method_ - 1;
312
137k
    if (shift != 0) {  // otherwise `bitcount = 0`
313
1.13M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
1.07M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
741k
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
741k
          int drop_bits = bit_width[i] - 1 - bitcount;
317
741k
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
741k
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
741k
        }
320
1.07M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
20.2k
          i += same[i] - 1;
323
20.2k
        }
324
1.07M
      }
325
54.7k
    }
326
137k
    return true;
327
137k
  }
328
329
  void ANSBuildInfoTable(const AliasTable::Entry* table, size_t log_alpha_size,
330
155k
                         ANSEncSymbolInfo* info) {
331
    // Create valid alias table for empty streams
332
4.89M
    for (size_t s = 0; s < std::max(size_t{1}, alphabet_size_); ++s) {
333
4.74M
      const ANSHistBin freq = s == alphabet_size_ ? ANS_TAB_SIZE : counts_[s];
334
4.74M
      info[s].freq_ = static_cast<uint16_t>(freq);
335
4.74M
#ifdef USE_MULT_BY_RECIPROCAL
336
4.74M
      if (freq != 0) {
337
2.39M
        info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) /
338
2.39M
                         info[s].freq_;
339
2.39M
      } else {
340
2.34M
        info[s].ifreq_ =
341
2.34M
            1;  // Shouldn't matter (symbol shouldn't occur), but...
342
2.34M
      }
343
4.74M
#endif
344
4.74M
      info[s].reverse_map_.resize(freq);
345
4.74M
    }
346
155k
    size_t log_entry_size = ANS_LOG_TAB_SIZE - log_alpha_size;
347
155k
    size_t entry_size_minus_1 = (1 << log_entry_size) - 1;
348
637M
    for (int i = 0; i < ANS_TAB_SIZE; i++) {
349
637M
      AliasTable::Symbol s =
350
637M
          AliasTable::Lookup(table, i, log_entry_size, entry_size_minus_1);
351
637M
      info[s.value].reverse_map_[s.offset] = i;
352
637M
    }
353
155k
  }
354
355
 private:
356
839k
  ANSEncodingHistogram() {}
357
358
  // Fixed-point log2 LUT for values of [0,4096]
359
  using Lg2LUT = std::array<uint32_t, ANS_TAB_SIZE + 1>;
360
  static const Lg2LUT lg2;
361
362
2.98M
  float EstimateDataBits(const Histogram& histo) {
363
2.98M
    int64_t sum = 0;
364
119M
    for (size_t i = 0; i < alphabet_size_; ++i) {
365
      // += histogram[i] * -log(counts[i]/total_counts)
366
116M
      sum += histo.counts[i] * int64_t{lg2[counts_[i]]};
367
116M
    }
368
2.98M
    return (histo.total_count - ldexpf(sum, -31)) * ANS_LOG_TAB_SIZE;
369
2.98M
  }
370
371
839k
  static float EstimateDataBitsFlat(const Histogram& histo) {
372
839k
    size_t len = histo.alphabet_size();
373
839k
    int64_t flat_bits = int64_t{lg2[len]} * ANS_LOG_TAB_SIZE;
374
839k
    return ldexpf(histo.total_count * flat_bits, -31);
375
839k
  }
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
128M
  static uint32_t SmallestIncrementLog(uint32_t count, uint32_t shift) {
400
128M
    if (count == 0) return 0;
401
62.0M
    uint32_t bits = FloorLog2Nonzero(count);
402
62.0M
    uint32_t drop_bits = bits - GetPopulationCountPrecision(bits, shift);
403
62.0M
    return drop_bits;
404
128M
  }
405
  // We are growing/reducing histogram step by step trying to maximize total
406
  // entropy i.e. sum of `freq[n] * log[counts[n]]` with a given sum of
407
  // `counts[n]` chosen from `allowed_counts[shift]`. This sum is balanced by
408
  // the `counts[omit_pos_]` in the highest bin of histogram. We start from
409
  // close to correct solution and each time a step with maximum entropy
410
  // increase per unit of bin change is chosen. This greedy scheme is not
411
  // guaranteed to achieve the global maximum, but cannot produce invalid
412
  // histogram. We use a fixed-point approximation for logarithms and all
413
  // arithmetic is integer besides initial approximation. Sum of `freq` and each
414
  // of `lg2[counts]` are supposed to be limited to `int32_t` range, so that the
415
  // sum of their products should not exceed `int64_t`.
416
2.98M
  bool RebalanceHistogram(const Histogram& histo) {
417
2.98M
    constexpr ANSHistBin table_size = ANS_TAB_SIZE;
418
2.98M
    uint32_t shift = method_ - 1;
419
420
2.98M
    struct EntropyDelta {
421
2.98M
      ANSHistBin freq;   // initial count
422
2.98M
      size_t count_ind;  // index of current bin value in `allowed_counts`
423
2.98M
      size_t bin_ind;    // index of current bin in `counts`
424
2.98M
    };
425
    // Penalties corresponding to different step sizes - entropy decrease in
426
    // balancing bin, step of size (1 << ANS_LOG_TAB_SIZE - 1) is not possible
427
2.98M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_inc = {};
428
2.98M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_dec = {};
429
2.98M
    const auto& ac = allowed_counts.array[shift];
430
2.98M
    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
880M
    const auto delta_entropy_inc = [&](const EntropyDelta& a) {
437
880M
      return a.freq * int64_t{ac[a.count_ind].delta_lg2} -
438
880M
             balance_inc[ac[a.count_ind].step_log];
439
880M
    };
440
134M
    const auto delta_entropy_dec = [&](const EntropyDelta& a) {
441
134M
      return a.freq * int64_t{ac[a.count_ind + 1].delta_lg2} -
442
134M
             balance_dec[ac[a.count_ind + 1].step_log];
443
134M
    };
444
    // Compare steps by entropy increase per unit of histogram bin change.
445
    // Truncation is OK here, accuracy is anyway better than float
446
431M
    const auto IncLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
447
431M
      return delta_entropy_inc(a) >> ac[a.count_ind].step_log <
448
431M
             delta_entropy_inc(b) >> ac[b.count_ind].step_log;
449
431M
    };
450
65.2M
    const auto DecLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
451
65.2M
      return delta_entropy_dec(a) >> ac[a.count_ind + 1].step_log <
452
65.2M
             delta_entropy_dec(b) >> ac[b.count_ind + 1].step_log;
453
65.2M
    };
454
    // Vector of adjustable bins from `allowed_counts`
455
2.98M
    std::vector<EntropyDelta> bins;
456
2.98M
    bins.reserve(256);
457
458
2.98M
    double norm = double{table_size} / histo.total_count;
459
460
2.98M
    size_t remainder_pos = 0;  // highest balancing bin in the histogram
461
2.98M
    int64_t max_freq = 0;
462
2.98M
    ANSHistBin rest = table_size;  // reserve of histogram counts to distribute
463
119M
    for (size_t n = 0; n < alphabet_size_; ++n) {
464
116M
      ANSHistBin freq = histo.counts[n];
465
116M
      if (freq > max_freq) {
466
6.12M
        remainder_pos = n;
467
6.12M
        max_freq = freq;
468
6.12M
      }
469
470
116M
      double target = freq * norm;  // rounding
471
      // Keep zeros and clamp nonzero freq counts to [1, table_size)
472
116M
      ANSHistBin count = std::max<ANSHistBin>(round(target), freq > 0);
473
116M
      count = std::min<ANSHistBin>(count, table_size - 1);
474
116M
      uint32_t step_log = SmallestIncrementLog(count, shift);
475
116M
      ANSHistBin inc = 1 << step_log;
476
116M
      count &= ~(inc - 1);
477
478
116M
      counts_[n] = count;
479
116M
      rest -= count;
480
116M
      if (target > 1.0) {
481
49.2M
        bins.push_back({freq, ai[count], n});
482
49.2M
      }
483
116M
    }
484
485
    // Delete the highest balancing bin from adjustable by `allowed_counts`
486
2.98M
    bins.erase(std::find_if(
487
2.98M
        bins.begin(), bins.end(),
488
14.8M
        [&](const EntropyDelta& a) { return a.bin_ind == remainder_pos; }));
489
    // From now on `rest` is the height of balancing bin,
490
    // here it can be negative, but will be tracted into positive domain later
491
2.98M
    rest += counts_[remainder_pos];
492
493
2.98M
    if (!bins.empty()) {
494
2.98M
      const uint32_t max_log = ac[1].step_log;
495
17.9M
      while (true) {
496
        // Update balancing bin penalties setting guards and tractors
497
158M
        for (uint32_t log = 0; log <= max_log; ++log) {
498
140M
          ANSHistBin delta = 1 << log;
499
140M
          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
140M
          } else if (rest > 1) {
504
            // `rest` is OK, put guards against non-possible steps
505
140M
            balance_inc[log] =
506
140M
                rest > delta  // possible step
507
140M
                    ? max_freq * int64_t{lg2[rest] - lg2[rest - delta]}
508
140M
                    : std::numeric_limits<int64_t>::max();  // forbidden
509
140M
            balance_dec[log] =
510
140M
                rest + delta < table_size  // possible step
511
140M
                    ? max_freq * int64_t{lg2[rest + delta] - lg2[rest]}
512
140M
                    : 0;  // forbidden
513
140M
          } else {
514
            // Tract negative or zero `rest` into positive:
515
            // forbid all inc steps
516
276
            balance_inc[log] = std::numeric_limits<int64_t>::max();
517
            // permit all dec steps
518
276
            balance_dec[log] = std::numeric_limits<int64_t>::max();
519
276
          }
520
140M
        }
521
        // Try to increase entropy
522
17.9M
        auto best_bin_inc = std::max_element(bins.begin(), bins.end(), IncLess);
523
17.9M
        if (delta_entropy_inc(*best_bin_inc) > 0) {
524
          // Grow the bin with the best histogram entropy increase
525
14.1M
          rest -= 1 << ac[best_bin_inc->count_ind--].step_log;
526
14.1M
        } 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.80M
          auto best_bin_dec =
531
3.80M
              std::min_element(bins.begin(), bins.end(), DecLess);
532
          // Break if no reverse steps can grow entropy (or valid)
533
3.80M
          if (delta_entropy_dec(*best_bin_dec) >= 0) break;
534
          // Decrease the bin with the best histogram entropy increase
535
829k
          rest += 1 << ac[++best_bin_dec->count_ind].step_log;
536
829k
        }
537
17.9M
      }
538
      // Set counts besides the balancing bin
539
46.2M
      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
25.2M
      for (size_t n = 0; n < remainder_pos; ++n) {
547
22.3M
        if (counts_[n] >= 2048) {
548
7.98k
          counts_[remainder_pos] = counts_[n];
549
7.98k
          remainder_pos = n;
550
7.98k
          break;
551
7.98k
        }
552
22.3M
      }
553
2.98M
    }
554
    // Set balancing bin
555
2.98M
    counts_[remainder_pos] = rest;
556
2.98M
    omit_pos_ = remainder_pos;
557
558
2.98M
    return counts_[remainder_pos] > 0;
559
2.98M
  }
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
252
const AEH::Lg2LUT AEH::lg2 = [] {
573
252
  Lg2LUT lg2;
574
252
  lg2[0] = 0;  // for entropy calculations it is OK
575
1.03M
  for (size_t i = 1; i < lg2.size(); ++i) {
576
1.03M
    lg2[i] = round(ldexp(log2(i) / ANS_LOG_TAB_SIZE, 31));
577
1.03M
  }
578
252
  return lg2;
579
252
}();
580
581
252
const AEH::AllowedCounts AEH::allowed_counts = [] {
582
252
  AllowedCounts result;
583
584
3.27k
  for (uint32_t shift = 0; shift < result.array.size(); ++shift) {
585
3.02k
    auto& ac = result.array[shift];
586
3.02k
    auto& ai = result.index[shift];
587
3.02k
    ANSHistBin last = ~0;
588
3.02k
    size_t slot = 0;
589
    // TODO(eustas): are those "default" values relevant?
590
3.02k
    ac[0].delta_lg2 = 0;
591
3.02k
    ac[0].step_log = 0;
592
12.3M
    for (int32_t i = ac.size() - 1; i >= 0; --i) {
593
12.3M
      int32_t curr = i & ~((1 << SmallestIncrementLog(i, shift)) - 1);
594
12.3M
      if (curr == last) continue;
595
2.41M
      last = curr;
596
2.41M
      ac[slot].count = curr;
597
2.41M
      ai[curr] = slot;
598
2.41M
      if (curr == 0) {
599
        // Guards against non-possible steps:
600
        // at max value [0] - 0 (by init), at min value - max
601
3.02k
        ac[slot].delta_lg2 = std::numeric_limits<int32_t>::max();
602
3.02k
        ac[slot].step_log = 0;
603
2.41M
      } else if (slot > 0) {
604
2.40M
        ANSHistBin prev = ac[slot - 1].count;
605
2.40M
        ac[slot].delta_lg2 = round(ldexp(
606
2.40M
            log2(static_cast<double>(prev) / curr) / ANS_LOG_TAB_SIZE, 31));
607
2.40M
        ac[slot].step_log = FloorLog2Nonzero<uint32_t>(prev - curr);
608
2.40M
        prev = curr;
609
2.40M
      }
610
2.41M
      slot++;
611
2.41M
    }
612
3.02k
  }
613
614
252
  return result;
615
252
}();
616
617
}  // namespace
618
619
684k
StatusOr<float> Histogram::ANSPopulationCost() const {
620
684k
  if (counts.size() > ANS_MAX_ALPHABET_SIZE) {
621
0
    return std::numeric_limits<float>::max();
622
0
  }
623
684k
  JXL_ASSIGN_OR_RETURN(
624
684k
      ANSEncodingHistogram normalized,
625
684k
      ANSEncodingHistogram::ComputeBest(
626
684k
          *this, HistogramParams::ANSHistogramStrategy::kFast));
627
684k
  return normalized.Cost();
628
684k
}
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
191k
    const Histogram& histogram, BitWriter* writer) {
636
191k
  ANSEncSymbolInfo* info = encoding_info.back().data();
637
191k
  size_t size = histogram.alphabet_size();
638
191k
  if (use_prefix_code) {
639
35.5k
    size_t cost = 0;
640
35.5k
    if (size <= 1) return 0;
641
35.0k
    std::vector<uint32_t> histo(size);
642
296k
    for (size_t i = 0; i < size; i++) {
643
261k
      JXL_ENSURE(histogram.counts[i] >= 0);
644
261k
      histo[i] = histogram.counts[i];
645
261k
    }
646
35.0k
    std::vector<uint8_t> depths(size);
647
35.0k
    std::vector<uint16_t> bits(size);
648
35.0k
    if (writer == nullptr) {
649
26.0k
      BitWriter tmp_writer{memory_manager};
650
26.0k
      JXL_RETURN_IF_ERROR(tmp_writer.WithMaxBits(
651
26.0k
          8 * size + 8,  // safe upper bound
652
26.0k
          LayerType::Header, /*aux_out=*/nullptr, [&] {
653
26.0k
            return BuildAndStoreHuffmanTree(histo.data(), size, depths.data(),
654
26.0k
                                            bits.data(), &tmp_writer);
655
26.0k
          }));
656
26.0k
      cost = tmp_writer.BitsWritten();
657
26.0k
    } else {
658
9.06k
      size_t start = writer->BitsWritten();
659
9.06k
      JXL_RETURN_IF_ERROR(BuildAndStoreHuffmanTree(
660
9.06k
          histo.data(), size, depths.data(), bits.data(), writer));
661
9.06k
      cost = writer->BitsWritten() - start;
662
9.06k
    }
663
296k
    for (size_t i = 0; i < size; i++) {
664
261k
      info[i].bits = depths[i] == 0 ? 0 : bits[i];
665
261k
      info[i].depth = depths[i];
666
261k
    }
667
    // Estimate data cost.
668
296k
    for (size_t i = 0; i < size; i++) {
669
261k
      cost += histo[i] * info[i].depth;
670
261k
    }
671
35.0k
    return cost;
672
35.0k
  }
673
311k
  JXL_ASSIGN_OR_RETURN(
674
311k
      ANSEncodingHistogram normalized,
675
311k
      ANSEncodingHistogram::ComputeBest(histogram, ans_histogram_strategy));
676
677
  // TODO(eustas): fix: 2KiB on stack
678
311k
  AliasTable::Entry a[ANS_MAX_ALPHABET_SIZE];
679
680
311k
  JXL_RETURN_IF_ERROR(
681
311k
      InitAliasTable(normalized.Counts(), ANS_LOG_TAB_SIZE, log_alpha_size, a));
682
155k
  normalized.ANSBuildInfoTable(a, log_alpha_size, info);
683
155k
  if (writer != nullptr) {
684
    // size_t start = writer->BitsWritten();
685
148k
    JXL_RETURN_IF_ERROR(normalized.Encode(writer));
686
    // return writer->BitsWritten() - start;
687
148k
  }
688
155k
  return static_cast<size_t>(ceilf(normalized.Cost()));
689
155k
}
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
56.5k
    std::vector<Histogram>& clustered_histograms) {
716
  // Set sane default `log_alpha_size`.
717
56.5k
  if (use_prefix_code) {
718
35.3k
    log_alpha_size = PREFIX_MAX_BITS;
719
35.3k
  } else if (params.streaming_mode) {
720
    // TODO(szabadka) Figure out if we can use lower values here.
721
0
    log_alpha_size = 8;
722
21.1k
  } else if (lz77.enabled) {
723
4.57k
    log_alpha_size = 8;
724
16.6k
  } else {
725
16.6k
    log_alpha_size = 7;
726
16.6k
  }
727
728
56.5k
  if (ans_fuzzer_friendly_) {
729
0
    uint_config.assign(1, HybridUintConfig(7, 0, 0));
730
0
    return true;
731
0
  }
732
733
56.5k
  uint_config.assign(clustered_histograms.size(), params.UintConfig());
734
  // If the uint config is fixed, just use it.
735
56.5k
  if (params.uint_method != HistogramParams::HybridUintMethod::kBest &&
736
52.4k
      params.uint_method != HistogramParams::HybridUintMethod::kFast) {
737
42.5k
    return true;
738
42.5k
  }
739
  // Even if the uint config is adaptive, just stick with the default in
740
  // streaming mode.
741
13.9k
  if (params.streaming_mode) {
742
0
    return true;
743
0
  }
744
745
  // Brute-force method that tries a few options.
746
13.9k
  std::vector<HybridUintConfig> configs;
747
13.9k
  if (params.uint_method == HistogramParams::HybridUintMethod::kBest) {
748
4.11k
    configs = {
749
4.11k
        HybridUintConfig(4, 2, 0),  // default
750
4.11k
        HybridUintConfig(4, 1, 0),  // less precise
751
4.11k
        HybridUintConfig(4, 2, 1),  // add sign
752
4.11k
        HybridUintConfig(4, 2, 2),  // add sign+parity
753
4.11k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
754
        // Same as above, but more direct coding.
755
4.11k
        HybridUintConfig(5, 2, 0), HybridUintConfig(5, 1, 0),
756
4.11k
        HybridUintConfig(5, 2, 1), HybridUintConfig(5, 2, 2),
757
4.11k
        HybridUintConfig(5, 1, 2),
758
        // Same as above, but less direct coding.
759
4.11k
        HybridUintConfig(3, 2, 0), HybridUintConfig(3, 1, 0),
760
4.11k
        HybridUintConfig(3, 2, 1), HybridUintConfig(3, 1, 2),
761
        // For near-lossless.
762
4.11k
        HybridUintConfig(4, 1, 3), HybridUintConfig(5, 1, 4),
763
4.11k
        HybridUintConfig(5, 2, 3), HybridUintConfig(6, 1, 5),
764
4.11k
        HybridUintConfig(6, 2, 4), HybridUintConfig(6, 0, 0),
765
        // Other
766
4.11k
        HybridUintConfig(0, 0, 0),   // varlenuint
767
4.11k
        HybridUintConfig(2, 0, 1),   // works well for ctx map
768
4.11k
        HybridUintConfig(7, 0, 0),   // direct coding
769
4.11k
        HybridUintConfig(8, 0, 0),   // direct coding
770
4.11k
        HybridUintConfig(9, 0, 0),   // direct coding
771
4.11k
        HybridUintConfig(10, 0, 0),  // direct coding
772
4.11k
        HybridUintConfig(11, 0, 0),  // direct coding
773
4.11k
        HybridUintConfig(12, 0, 0),  // direct coding
774
4.11k
    };
775
9.86k
  } else {
776
9.86k
    JXL_DASSERT(params.uint_method == HistogramParams::HybridUintMethod::kFast);
777
9.86k
    configs = {
778
9.86k
        HybridUintConfig(4, 2, 0),  // default
779
9.86k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
780
9.86k
        HybridUintConfig(0, 0, 0),  // smallest histograms
781
9.86k
        HybridUintConfig(2, 0, 1),  // works well for ctx map
782
9.86k
    };
783
9.86k
  }
784
785
13.9k
  size_t num_histo = clustered_histograms.size();
786
13.9k
  std::vector<uint8_t> is_valid(num_histo);
787
13.9k
  std::vector<size_t> histo_volume(2 * num_histo);
788
13.9k
  std::vector<size_t> histo_offset(2 * num_histo + 1);
789
13.9k
  std::vector<uint32_t> max_value_per_histo(2 * num_histo);
790
791
  // TODO(veluca): do not ignore lz77 commands.
792
793
122k
  for (const auto& stream : tokens) {
794
60.1M
    for (const auto& token : stream) {
795
60.1M
      size_t histo = context_map[token.context];
796
60.1M
      histo_volume[histo + (token.is_lz77_length ? num_histo : 0)]++;
797
60.1M
    }
798
122k
  }
799
13.9k
  size_t max_histo_volume = 0;
800
172k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
801
158k
    max_histo_volume = std::max(max_histo_volume, histo_volume[h]);
802
158k
    histo_offset[h + 1] = histo_offset[h] + histo_volume[h];
803
158k
  }
804
805
13.9k
  const size_t max_vec_size = MaxVectorSize();
806
13.9k
  std::vector<uint32_t> transposed(histo_offset[num_histo * 2] + max_vec_size);
807
13.9k
  {
808
13.9k
    std::vector<size_t> next_offset = histo_offset;  // copy
809
122k
    for (const auto& stream : tokens) {
810
60.1M
      for (const auto& token : stream) {
811
60.1M
        size_t histo =
812
60.1M
            context_map[token.context] + (token.is_lz77_length ? num_histo : 0);
813
60.1M
        transposed[next_offset[histo]++] = token.value;
814
60.1M
      }
815
122k
    }
816
13.9k
  }
817
172k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
818
158k
    max_value_per_histo[h] =
819
158k
        MaxValue(transposed.data() + histo_offset[h], histo_volume[h]);
820
158k
  }
821
13.9k
  uint32_t max_lz77 = 0;
822
93.2k
  for (size_t h = num_histo; h < 2 * num_histo; ++h) {
823
79.2k
    max_lz77 = std::max(max_lz77, MaxValue(transposed.data() + histo_offset[h],
824
79.2k
                                           histo_volume[h]));
825
79.2k
  }
826
827
  // Wider histograms are assigned max cost in PopulationCost anyway
828
  // and therefore will not be used
829
13.9k
  size_t max_alpha = ANS_MAX_ALPHABET_SIZE;
830
831
13.9k
  JXL_ASSIGN_OR_RETURN(
832
13.9k
      AlignedMemory tmp,
833
13.9k
      AlignedMemory::Create(memory_manager, (max_histo_volume + max_vec_size) *
834
13.9k
                                                sizeof(uint32_t)));
835
93.2k
  for (size_t h = 0; h < num_histo; h++) {
836
79.2k
    float best_cost = std::numeric_limits<float>::max();
837
640k
    for (HybridUintConfig cfg : configs) {
838
640k
      uint32_t max_v = max_value_per_histo[h];
839
640k
      size_t capacity;
840
640k
      {
841
640k
        uint32_t tok, nbits, bits;
842
640k
        cfg.Encode(max_v, &tok, &nbits, &bits);
843
640k
        tok |= cfg.LsbMask();
844
640k
        if (tok >= max_alpha || (lz77.enabled && tok >= lz77.min_symbol)) {
845
17.1k
          continue;  // Not valid config for this context
846
17.1k
        }
847
623k
        capacity = tok + 1;
848
623k
      }
849
850
0
      Histogram histo;
851
623k
      histo.EnsureCapacity(capacity);
852
623k
      size_t len = histo_volume[h];
853
623k
      uint32_t* data = transposed.data() + histo_offset[h];
854
623k
      size_t extra_bits = EstimateTokenCost(data, len, cfg, tmp);
855
623k
      uint32_t* tmp_tokens = tmp.address<uint32_t>();
856
374M
      for (size_t i = 0; i < len; ++i) {
857
373M
        histo.FastAdd(tmp_tokens[i]);
858
373M
      }
859
623k
      histo.Condition();
860
623k
      JXL_ASSIGN_OR_RETURN(float cost, histo.ANSPopulationCost());
861
623k
      cost += extra_bits;
862
      // Add signaling cost of the hybriduintconfig itself.
863
623k
      cost += CeilLog2Nonzero(cfg.split_exponent + 1);
864
623k
      cost += CeilLog2Nonzero(cfg.split_exponent - cfg.msb_in_token + 1);
865
623k
      if (cost < best_cost) {
866
174k
        uint_config[h] = cfg;
867
174k
        best_cost = cost;
868
174k
        clustered_histograms[h].swap(histo);
869
174k
      }
870
623k
    }
871
79.2k
  }
872
873
13.9k
  size_t max_tok = 0;
874
93.2k
  for (size_t h = 0; h < num_histo; ++h) {
875
79.2k
    Histogram& histo = clustered_histograms[h];
876
79.2k
    max_tok = std::max(max_tok, histo.MaxSymbol());
877
79.2k
    size_t len = histo_volume[num_histo + h];
878
79.2k
    if (len == 0) continue;  // E.g. when lz77 not enabled
879
1.94k
    size_t max_histo_tok = max_value_per_histo[num_histo + h];
880
1.94k
    uint32_t tok, nbits, bits;
881
1.94k
    lz77.length_uint_config.Encode(max_histo_tok, &tok, &nbits, &bits);
882
1.94k
    tok |= lz77.length_uint_config.LsbMask();
883
1.94k
    tok += lz77.min_symbol;
884
1.94k
    histo.EnsureCapacity(tok + 1);
885
1.94k
    uint32_t* data = transposed.data() + histo_offset[num_histo + h];
886
1.94k
    uint32_t unused =
887
1.94k
        EstimateTokenCost(data, len, lz77.length_uint_config, tmp);
888
1.94k
    (void)unused;
889
1.94k
    uint32_t* tmp_tokens = tmp.address<uint32_t>();
890
21.3k
    for (size_t i = 0; i < len; ++i) {
891
19.4k
      histo.FastAdd(tmp_tokens[i] + lz77.min_symbol);
892
19.4k
    }
893
1.94k
    histo.Condition();
894
1.94k
    max_tok = std::max(max_tok, histo.MaxSymbol());
895
1.94k
  }
896
897
  // `log_alpha_size - 5` is encoded in the header, so min is 5.
898
13.9k
  size_t log_size = 5;
899
23.3k
  while (max_tok >= (1u << log_size)) ++log_size;
900
901
13.9k
  size_t max_log_alpha_size = use_prefix_code ? PREFIX_MAX_BITS : 8;
902
13.9k
  JXL_ENSURE(log_size <= max_log_alpha_size);
903
904
13.9k
  if (use_prefix_code) {
905
3.30k
    log_alpha_size = PREFIX_MAX_BITS;
906
10.6k
  } else {
907
10.6k
    log_alpha_size = log_size;
908
10.6k
  }
909
910
13.9k
  return true;
911
13.9k
}
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
56.5k
    AuxOut* aux_out) {
920
56.5k
  const size_t prev_histograms = encoding_info.size();
921
56.5k
  std::vector<Histogram> clustered_histograms;
922
56.5k
  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
56.5k
  size_t context_offset = context_map.size();
927
56.5k
  context_map.resize(context_offset + builder.size());
928
56.5k
  if (builder.size() > 1) {
929
21.5k
    if (!ans_fuzzer_friendly_) {
930
21.5k
      std::vector<uint32_t> histogram_symbols;
931
21.5k
      JXL_RETURN_IF_ERROR(ClusterHistograms(params, builder, kClustersLimit,
932
21.5k
                                            &clustered_histograms,
933
21.5k
                                            &histogram_symbols));
934
20.1M
      for (size_t c = 0; c < builder.size(); ++c) {
935
20.1M
        context_map[context_offset + c] =
936
20.1M
            static_cast<uint8_t>(histogram_symbols[c]);
937
20.1M
      }
938
21.5k
    } 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
21.5k
    if (writer != nullptr) {
953
18.8k
      JXL_RETURN_IF_ERROR(EncodeContextMap(
954
18.8k
          context_map, clustered_histograms.size(), writer, layer, aux_out));
955
18.8k
    }
956
35.0k
  } else {
957
35.0k
    JXL_ENSURE(encoding_info.empty());
958
35.0k
    clustered_histograms.push_back(builder[0]);
959
35.0k
  }
960
56.5k
  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
56.5k
  JXL_RETURN_IF_ERROR(
968
56.5k
      ChooseUintConfigs(memory_manager, params, tokens, clustered_histograms));
969
970
56.5k
  SizeWriter size_writer;  // Used if writer == nullptr to estimate costs.
971
56.5k
  size_t cost = use_prefix_code ? 1 : 3;
972
973
56.5k
  if (writer) writer->Write(1, TO_JXL_BOOL(use_prefix_code));
974
56.5k
  if (writer == nullptr) {
975
31.0k
    EncodeUintConfigs(uint_config, &size_writer, log_alpha_size);
976
31.0k
  } else {
977
25.4k
    if (!use_prefix_code) writer->Write(2, log_alpha_size - 5);
978
25.4k
    EncodeUintConfigs(uint_config, writer, log_alpha_size);
979
25.4k
  }
980
56.5k
  if (use_prefix_code) {
981
35.5k
    for (const auto& histo : clustered_histograms) {
982
35.5k
      size_t alphabet_size = std::max<size_t>(1, histo.alphabet_size());
983
35.5k
      if (writer) {
984
9.52k
        StoreVarLenUint16(alphabet_size - 1, writer);
985
26.0k
      } else {
986
26.0k
        StoreVarLenUint16(alphabet_size - 1, &size_writer);
987
26.0k
      }
988
35.5k
    }
989
35.3k
  }
990
56.5k
  cost += size_writer.size;
991
247k
  for (size_t c = prev_histograms; c < clustered_histograms.size(); ++c) {
992
191k
    size_t alphabet_size = clustered_histograms[c].alphabet_size();
993
191k
    encoding_info.emplace_back();
994
191k
    encoding_info.back().resize(alphabet_size);
995
191k
    BitWriter* histo_writer = writer;
996
191k
    if (params.streaming_mode) {
997
0
      encoded_histograms.emplace_back(memory_manager);
998
0
      histo_writer = &encoded_histograms.back();
999
0
    }
1000
191k
    const auto& body = [&]() -> Status {
1001
191k
      JXL_ASSIGN_OR_RETURN(size_t ans_cost,
1002
191k
                           BuildAndStoreANSEncodingData(
1003
191k
                               memory_manager, params.ans_histogram_strategy,
1004
191k
                               clustered_histograms[c], histo_writer));
1005
191k
      cost += ans_cost;
1006
191k
      return true;
1007
191k
    };
1008
191k
    if (histo_writer) {
1009
157k
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1010
157k
          256 + alphabet_size * 24, layer, aux_out, body,
1011
157k
          /*finished_histogram=*/true));
1012
157k
    } else {
1013
33.2k
      JXL_RETURN_IF_ERROR(body());
1014
33.2k
    }
1015
191k
    if (params.streaming_mode) {
1016
0
      JXL_RETURN_IF_ERROR(writer->AppendUnaligned(*histo_writer));
1017
0
    }
1018
191k
  }
1019
56.5k
  return cost;
1020
56.5k
}
1021
1022
template <typename Writer>
1023
void EncodeUintConfig(const HybridUintConfig uint_config, Writer* writer,
1024
195k
                      size_t log_alpha_size) {
1025
195k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
195k
                uint_config.split_exponent);
1027
195k
  if (uint_config.split_exponent == log_alpha_size) {
1028
204
    return;  // msb/lsb don't matter.
1029
204
  }
1030
195k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
195k
  writer->Write(nbits, uint_config.msb_in_token);
1032
195k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
195k
                          uint_config.msb_in_token + 1);
1034
195k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
195k
}
void jxl::EncodeUintConfig<jxl::SizeWriter>(jxl::HybridUintConfig, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1024
35.9k
                      size_t log_alpha_size) {
1025
35.9k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
35.9k
                uint_config.split_exponent);
1027
35.9k
  if (uint_config.split_exponent == log_alpha_size) {
1028
0
    return;  // msb/lsb don't matter.
1029
0
  }
1030
35.9k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
35.9k
  writer->Write(nbits, uint_config.msb_in_token);
1032
35.9k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
35.9k
                          uint_config.msb_in_token + 1);
1034
35.9k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
35.9k
}
void jxl::EncodeUintConfig<jxl::BitWriter>(jxl::HybridUintConfig, jxl::BitWriter*, unsigned long)
Line
Count
Source
1024
159k
                      size_t log_alpha_size) {
1025
159k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
159k
                uint_config.split_exponent);
1027
159k
  if (uint_config.split_exponent == log_alpha_size) {
1028
204
    return;  // msb/lsb don't matter.
1029
204
  }
1030
159k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
159k
  writer->Write(nbits, uint_config.msb_in_token);
1032
159k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
159k
                          uint_config.msb_in_token + 1);
1034
159k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
159k
}
1036
template <typename Writer>
1037
void EncodeUintConfigs(const std::vector<HybridUintConfig>& uint_config,
1038
56.5k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
191k
  for (const auto& cfg : uint_config) {
1041
191k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
191k
  }
1043
56.5k
}
void jxl::EncodeUintConfigs<jxl::BitWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::BitWriter*, unsigned long)
Line
Count
Source
1038
25.4k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
157k
  for (const auto& cfg : uint_config) {
1041
157k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
157k
  }
1043
25.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
31.0k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
33.2k
  for (const auto& cfg : uint_config) {
1041
33.2k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
33.2k
  }
1043
31.0k
}
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
56.5k
    AuxOut* aux_out) {
1087
  // TODO(Ivan): presumably not needed - default
1088
  // if (params.initialize_global_state) codes->lz77.enabled = false;
1089
56.5k
  codes->lz77.nonserialized_distance_context = num_contexts;
1090
56.5k
  codes->lz77.min_symbol = params.force_huffman ? 512 : 224;
1091
56.5k
  std::vector<std::vector<Token>> tokens_lz77 =
1092
56.5k
      ApplyLZ77(params, num_contexts, tokens, codes->lz77);
1093
56.5k
  if (!tokens_lz77.empty()) codes->lz77.enabled = true;
1094
56.5k
  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
56.5k
  size_t cost = 0;
1100
56.5k
  const size_t max_contexts = std::min(num_contexts, kClustersLimit);
1101
56.5k
  const auto& body = [&]() -> Status {
1102
56.5k
    if (writer) {
1103
25.4k
      JXL_RETURN_IF_ERROR(Bundle::Write(codes->lz77, writer, layer, aux_out));
1104
31.0k
    } else {
1105
31.0k
      size_t ebits, bits;
1106
31.0k
      JXL_RETURN_IF_ERROR(Bundle::CanEncode(codes->lz77, &ebits, &bits));
1107
31.0k
      cost += bits;
1108
31.0k
    }
1109
56.5k
    if (codes->lz77.enabled) {
1110
4.84k
      if (writer) {
1111
2.15k
        size_t b = writer->BitsWritten();
1112
2.15k
        EncodeUintConfig(codes->lz77.length_uint_config, writer,
1113
2.15k
                         /*log_alpha_size=*/8);
1114
2.15k
        cost += writer->BitsWritten() - b;
1115
2.68k
      } else {
1116
2.68k
        SizeWriter size_writer;
1117
2.68k
        EncodeUintConfig(codes->lz77.length_uint_config, &size_writer,
1118
2.68k
                         /*log_alpha_size=*/8);
1119
2.68k
        cost += size_writer.size;
1120
2.68k
      }
1121
4.84k
      num_contexts += 1;
1122
4.84k
      tokens = std::move(tokens_lz77);
1123
4.84k
    }
1124
56.5k
    size_t total_tokens = 0;
1125
    // Build histograms.
1126
56.5k
    std::vector<Histogram> builder(num_contexts);
1127
56.5k
    HybridUintConfig uint_config = params.UintConfig();
1128
56.5k
    if (ans_fuzzer_friendly_) {
1129
0
      uint_config = HybridUintConfig(10, 0, 0);
1130
0
    }
1131
170k
    for (const auto& stream : tokens) {
1132
170k
      if (codes->lz77.enabled) {
1133
6.71M
        for (const auto& token : stream) {
1134
6.71M
          total_tokens++;
1135
6.71M
          uint32_t tok, nbits, bits;
1136
6.71M
          (token.is_lz77_length ? codes->lz77.length_uint_config : uint_config)
1137
6.71M
              .Encode(token.value, &tok, &nbits, &bits);
1138
6.71M
          tok += token.is_lz77_length ? codes->lz77.min_symbol : 0;
1139
6.71M
          JXL_DASSERT(token.context < num_contexts);
1140
6.71M
          builder[token.context].Add(tok);
1141
6.71M
        }
1142
165k
      } else if (num_contexts == 1) {
1143
21.4M
        for (const auto& token : stream) {
1144
21.4M
          total_tokens++;
1145
21.4M
          uint32_t tok, nbits, bits;
1146
21.4M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1147
21.4M
          builder[0].Add(tok);
1148
21.4M
        }
1149
129k
      } else {
1150
323M
        for (const auto& token : stream) {
1151
323M
          total_tokens++;
1152
323M
          uint32_t tok, nbits, bits;
1153
323M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1154
323M
          JXL_DASSERT(token.context < num_contexts);
1155
323M
          builder[token.context].Add(tok);
1156
323M
        }
1157
129k
      }
1158
170k
    }
1159
1160
56.5k
    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
56.5k
    if (params.initialize_global_state) {
1169
56.5k
      bool use_prefix_code =
1170
56.5k
          params.force_huffman || total_tokens < 100 ||
1171
21.3k
          params.clustering == HistogramParams::ClusteringType::kFastest ||
1172
21.3k
          ans_fuzzer_friendly_;
1173
56.5k
      if (!use_prefix_code) {
1174
21.3k
        bool all_singleton = true;
1175
16.5M
        for (size_t i = 0; i < num_contexts; i++) {
1176
16.5M
          if (builder[i].ShannonEntropy() >= 1e-5) {
1177
2.26M
            all_singleton = false;
1178
2.26M
          }
1179
16.5M
        }
1180
21.3k
        if (all_singleton) {
1181
119
          use_prefix_code = true;
1182
119
        }
1183
21.3k
      }
1184
56.5k
      codes->use_prefix_code = use_prefix_code;
1185
56.5k
    }
1186
1187
56.5k
    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
56.5k
    JXL_ASSIGN_OR_RETURN(
1216
56.5k
        size_t entropy_bits,
1217
56.5k
        codes->BuildAndStoreEntropyCodes(memory_manager, params, tokens,
1218
56.5k
                                         builder, writer, layer, aux_out));
1219
56.5k
    cost += entropy_bits;
1220
56.5k
    return true;
1221
56.5k
  };
1222
56.5k
  if (writer) {
1223
25.4k
    JXL_RETURN_IF_ERROR(writer->WithMaxBits(
1224
25.4k
        128 + num_contexts * 40 + max_contexts * 96, layer, aux_out, body,
1225
25.4k
        /*finished_histogram=*/true));
1226
31.0k
  } else {
1227
31.0k
    JXL_RETURN_IF_ERROR(body());
1228
31.0k
  }
1229
1230
56.5k
  if (aux_out != nullptr) {
1231
0
    aux_out->layer(layer).num_clustered_histograms +=
1232
0
        codes->encoding_info.size();
1233
0
  }
1234
56.5k
  return cost;
1235
56.5k
}
1236
1237
size_t WriteTokens(const std::vector<Token>& tokens,
1238
                   const EntropyEncodingData& codes, size_t context_offset,
1239
34.3k
                   BitWriter* writer) {
1240
34.3k
  size_t num_extra_bits = 0;
1241
34.3k
  if (codes.use_prefix_code) {
1242
414k
    for (const auto& token : tokens) {
1243
414k
      uint32_t tok, nbits, bits;
1244
414k
      size_t histo = codes.context_map[context_offset + token.context];
1245
414k
      (token.is_lz77_length ? codes.lz77.length_uint_config
1246
414k
                            : codes.uint_config[histo])
1247
414k
          .Encode(token.value, &tok, &nbits, &bits);
1248
414k
      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
414k
      uint64_t data = codes.encoding_info[histo][tok].bits;
1254
414k
      data |= static_cast<uint64_t>(bits)
1255
414k
              << codes.encoding_info[histo][tok].depth;
1256
414k
      writer->Write(codes.encoding_info[histo][tok].depth + nbits, data);
1257
414k
      num_extra_bits += nbits;
1258
414k
    }
1259
10.4k
    return num_extra_bits;
1260
10.4k
  }
1261
23.9k
  std::vector<uint64_t> out;
1262
23.9k
  std::vector<uint8_t> out_nbits;
1263
23.9k
  out.reserve(tokens.size());
1264
23.9k
  out_nbits.reserve(tokens.size());
1265
23.9k
  uint64_t allbits = 0;
1266
23.9k
  size_t numallbits = 0;
1267
  // Writes in *reversed* order.
1268
664M
  auto addbits = [&](size_t bits, size_t nbits) {
1269
664M
    if (JXL_UNLIKELY(nbits)) {
1270
56.7M
      JXL_DASSERT(bits >> nbits == 0);
1271
56.7M
      if (JXL_UNLIKELY(numallbits + nbits > BitWriter::kMaxBitsPerCall)) {
1272
12.5M
        out.push_back(allbits);
1273
12.5M
        out_nbits.push_back(numallbits);
1274
12.5M
        numallbits = allbits = 0;
1275
12.5M
      }
1276
56.7M
      allbits <<= nbits;
1277
56.7M
      allbits |= bits;
1278
56.7M
      numallbits += nbits;
1279
56.7M
    }
1280
664M
  };
1281
23.9k
  const int end = tokens.size();
1282
23.9k
  ANSCoder ans;
1283
23.9k
  if (codes.lz77.enabled || codes.context_map.size() > 1) {
1284
326M
    for (int i = end - 1; i >= 0; --i) {
1285
326M
      const Token token = tokens[i];
1286
326M
      const uint8_t histo = codes.context_map[context_offset + token.context];
1287
326M
      uint32_t tok, nbits, bits;
1288
326M
      (token.is_lz77_length ? codes.lz77.length_uint_config
1289
326M
                            : codes.uint_config[histo])
1290
326M
          .Encode(tokens[i].value, &tok, &nbits, &bits);
1291
326M
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1292
326M
      const ANSEncSymbolInfo& info = codes.encoding_info[histo][tok];
1293
326M
      JXL_DASSERT(info.freq_ > 0);
1294
      // Extra bits first as this is reversed.
1295
326M
      addbits(bits, nbits);
1296
326M
      num_extra_bits += nbits;
1297
326M
      uint8_t ans_nbits = 0;
1298
326M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1299
326M
      addbits(ans_bits, ans_nbits);
1300
326M
    }
1301
22.8k
  } else {
1302
6.08M
    for (int i = end - 1; i >= 0; --i) {
1303
6.08M
      uint32_t tok, nbits, bits;
1304
6.08M
      codes.uint_config[0].Encode(tokens[i].value, &tok, &nbits, &bits);
1305
6.08M
      const ANSEncSymbolInfo& info = codes.encoding_info[0][tok];
1306
      // Extra bits first as this is reversed.
1307
6.08M
      addbits(bits, nbits);
1308
6.08M
      num_extra_bits += nbits;
1309
6.08M
      uint8_t ans_nbits = 0;
1310
6.08M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1311
6.08M
      addbits(ans_bits, ans_nbits);
1312
6.08M
    }
1313
1.13k
  }
1314
23.9k
  const uint32_t state = ans.GetState();
1315
23.9k
  writer->Write(32, state);
1316
23.9k
  writer->Write(numallbits, allbits);
1317
12.5M
  for (int i = out.size(); i > 0; --i) {
1318
12.5M
    writer->Write(out_nbits[i - 1], out[i - 1]);
1319
12.5M
  }
1320
23.9k
  return num_extra_bits;
1321
23.9k
}
1322
1323
Status WriteTokens(const std::vector<Token>& tokens,
1324
                   const EntropyEncodingData& codes, size_t context_offset,
1325
26.3k
                   BitWriter* writer, LayerType layer, AuxOut* aux_out) {
1326
  // Theoretically, we could have 15 prefix code bits + 31 extra bits.
1327
26.3k
  return writer->WithMaxBits(
1328
26.3k
      46 * tokens.size() + 32 * 1024 * 4, layer, aux_out, [&] {
1329
26.3k
        size_t num_extra_bits =
1330
26.3k
            WriteTokens(tokens, codes, context_offset, writer);
1331
26.3k
        if (aux_out != nullptr) {
1332
0
          aux_out->layer(layer).extra_bits += num_extra_bits;
1333
0
        }
1334
26.3k
        return true;
1335
26.3k
      });
1336
26.3k
}
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
9.86k
    const std::vector<uint8_t>& extra_dc_precision, bool streaming_mode) {
1347
9.86k
  HistogramParams params;
1348
9.86k
  params.streaming_mode = streaming_mode;
1349
9.86k
  if (cparams.speed_tier > SpeedTier::kKitten) {
1350
9.86k
    params.clustering = HistogramParams::ClusteringType::kFast;
1351
9.86k
    params.ans_histogram_strategy =
1352
9.86k
        cparams.speed_tier > SpeedTier::kThunder
1353
9.86k
            ? HistogramParams::ANSHistogramStrategy::kFast
1354
9.86k
            : HistogramParams::ANSHistogramStrategy::kApproximate;
1355
9.86k
    params.lz77_method =
1356
9.86k
        cparams.modular_mode && cparams.speed_tier <= SpeedTier::kHare
1357
9.86k
            ? HistogramParams::LZ77Method::kRLE
1358
9.86k
            : HistogramParams::LZ77Method::kNone;
1359
    // Near-lossless DC, as well as modular mode, require choosing hybrid uint
1360
    // more carefully.
1361
9.86k
    if ((!extra_dc_precision.empty() && extra_dc_precision[0] != 0) ||
1362
6.37k
        (cparams.modular_mode && cparams.speed_tier < SpeedTier::kCheetah)) {
1363
6.37k
      params.uint_method = HistogramParams::HybridUintMethod::kFast;
1364
6.37k
    } else {
1365
3.48k
      params.uint_method = HistogramParams::HybridUintMethod::kNone;
1366
3.48k
    }
1367
9.86k
  } 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
9.86k
  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
9.86k
    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
9.86k
  return params;
1387
9.86k
}
1388
}  // namespace jxl