Coverage Report

Created: 2025-10-12 07:48

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
4.96M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
4.96M
  JXL_DASSERT(n <= 255);
56
4.96M
  if (n == 0) {
57
462k
    writer->Write(1, 0);
58
4.50M
  } else {
59
4.50M
    writer->Write(1, 1);
60
4.50M
    size_t nbits = FloorLog2Nonzero(n);
61
4.50M
    writer->Write(3, nbits);
62
4.50M
    writer->Write(nbits, n - (1ULL << nbits));
63
4.50M
  }
64
4.96M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
54
4.74M
void StoreVarLenUint8(size_t n, Writer* writer) {
55
4.74M
  JXL_DASSERT(n <= 255);
56
4.74M
  if (n == 0) {
57
440k
    writer->Write(1, 0);
58
4.30M
  } else {
59
4.30M
    writer->Write(1, 1);
60
4.30M
    size_t nbits = FloorLog2Nonzero(n);
61
4.30M
    writer->Write(3, nbits);
62
4.30M
    writer->Write(nbits, n - (1ULL << nbits));
63
4.30M
  }
64
4.74M
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint8<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
54
219k
void StoreVarLenUint8(size_t n, Writer* writer) {
55
219k
  JXL_DASSERT(n <= 255);
56
219k
  if (n == 0) {
57
22.8k
    writer->Write(1, 0);
58
196k
  } else {
59
196k
    writer->Write(1, 1);
60
196k
    size_t nbits = FloorLog2Nonzero(n);
61
196k
    writer->Write(3, nbits);
62
196k
    writer->Write(nbits, n - (1ULL << nbits));
63
196k
  }
64
219k
}
65
66
template <typename Writer>
67
22.9k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
22.9k
  JXL_DASSERT(n <= 65535);
69
22.9k
  if (n == 0) {
70
725
    writer->Write(1, 0);
71
22.1k
  } else {
72
22.1k
    writer->Write(1, 1);
73
22.1k
    size_t nbits = FloorLog2Nonzero(n);
74
22.1k
    writer->Write(4, nbits);
75
22.1k
    writer->Write(nbits, n - (1ULL << nbits));
76
22.1k
  }
77
22.9k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::BitWriter>(unsigned long, jxl::BitWriter*)
Line
Count
Source
67
7.47k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
7.47k
  JXL_DASSERT(n <= 65535);
69
7.47k
  if (n == 0) {
70
725
    writer->Write(1, 0);
71
6.75k
  } else {
72
6.75k
    writer->Write(1, 1);
73
6.75k
    size_t nbits = FloorLog2Nonzero(n);
74
6.75k
    writer->Write(4, nbits);
75
6.75k
    writer->Write(nbits, n - (1ULL << nbits));
76
6.75k
  }
77
7.47k
}
enc_ans.cc:void jxl::(anonymous namespace)::StoreVarLenUint16<jxl::SizeWriter>(unsigned long, jxl::SizeWriter*)
Line
Count
Source
67
15.4k
void StoreVarLenUint16(size_t n, Writer* writer) {
68
15.4k
  JXL_DASSERT(n <= 65535);
69
15.4k
  if (n == 0) {
70
0
    writer->Write(1, 0);
71
15.4k
  } else {
72
15.4k
    writer->Write(1, 1);
73
15.4k
    size_t nbits = FloorLog2Nonzero(n);
74
15.4k
    writer->Write(4, nbits);
75
15.4k
    writer->Write(nbits, n - (1ULL << nbits));
76
15.4k
  }
77
15.4k
}
78
79
class ANSEncodingHistogram {
80
 public:
81
142k
  const std::vector<ANSHistBin>& Counts() const { return counts_; }
82
610k
  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
610k
      HistogramParams::ANSHistogramStrategy ans_histogram_strategy) {
87
610k
    ANSEncodingHistogram result;
88
89
610k
    result.alphabet_size_ = histo.alphabet_size();
90
610k
    if (result.alphabet_size_ > ANS_MAX_ALPHABET_SIZE)
91
0
      return JXL_FAILURE("Too many entries in an ANS histogram");
92
93
610k
    if (result.alphabet_size_ > 0) {
94
      // Flat code
95
610k
      result.method_ = 0;
96
610k
      result.num_symbols_ = result.alphabet_size_;
97
610k
      result.counts_ = CreateFlatHistogram(result.alphabet_size_, ANS_TAB_SIZE);
98
      // in this case length can be non-suitable for SIMD - fix it
99
610k
      result.counts_.resize(histo.counts.size());
100
610k
      SizeWriter writer;
101
610k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
102
610k
      result.cost_ = writer.size + EstimateDataBitsFlat(histo);
103
610k
    } 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
610k
    size_t symbol_count = 0;
112
21.3M
    for (size_t n = 0; n < result.alphabet_size_; ++n) {
113
20.7M
      if (histo.counts[n] > 0) {
114
9.69M
        if (symbol_count < kMaxNumSymbolsForSmallCode) {
115
1.18M
          result.symbols_[symbol_count] = n;
116
1.18M
        }
117
9.69M
        ++symbol_count;
118
9.69M
      }
119
20.7M
    }
120
610k
    result.num_symbols_ = symbol_count;
121
610k
    if (symbol_count == 1) {
122
      // Single-bin histogram
123
35.4k
      result.method_ = 1;
124
35.4k
      result.counts_ = histo.counts;
125
35.4k
      result.counts_[result.symbols_[0]] = ANS_TAB_SIZE;
126
35.4k
      SizeWriter writer;
127
35.4k
      JXL_RETURN_IF_ERROR(result.Encode(&writer));
128
35.4k
      result.cost_ = writer.size;
129
35.4k
      return result;
130
35.4k
    }
131
132
    // Here min 2 symbols
133
574k
    ANSEncodingHistogram normalized = result;
134
2.32M
    auto try_shift = [&](uint32_t shift) -> Status {
135
      // `shift = 12` and `shift = 11` are the same
136
2.32M
      normalized.method_ = std::min(shift, ANS_LOG_TAB_SIZE - 1) + 1;
137
138
2.32M
      if (!normalized.RebalanceHistogram(histo)) {
139
0
        return JXL_FAILURE("Logic error: couldn't rebalance a histogram");
140
0
      }
141
2.32M
      SizeWriter writer;
142
2.32M
      JXL_RETURN_IF_ERROR(normalized.Encode(&writer));
143
2.32M
      normalized.cost_ = writer.size + normalized.EstimateDataBits(histo);
144
2.32M
      if (normalized.cost_ < result.cost_) {
145
615k
        result = normalized;
146
615k
      }
147
2.32M
      return true;
148
2.32M
    };
149
150
574k
    switch (ans_histogram_strategy) {
151
9.43k
      case HistogramParams::ANSHistogramStrategy::kPrecise:
152
122k
        for (uint32_t shift = 0; shift < ANS_LOG_TAB_SIZE; shift++) {
153
113k
          JXL_RETURN_IF_ERROR(try_shift(shift));
154
113k
        }
155
9.43k
        break;
156
129k
      case HistogramParams::ANSHistogramStrategy::kApproximate:
157
1.03M
        for (uint32_t shift = 0; shift <= ANS_LOG_TAB_SIZE; shift += 2) {
158
908k
          JXL_RETURN_IF_ERROR(try_shift(shift));
159
908k
        }
160
129k
        break;
161
435k
      case HistogramParams::ANSHistogramStrategy::kFast:
162
435k
        JXL_RETURN_IF_ERROR(try_shift(0));
163
435k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE / 2));
164
435k
        JXL_RETURN_IF_ERROR(try_shift(ANS_LOG_TAB_SIZE));
165
435k
        break;
166
574k
    }
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
574k
    return result;
197
574k
  }
198
199
  template <typename Writer>
200
3.11M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
3.11M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
3.11M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
613k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
613k
      writer->Write(1, 1);
211
613k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
613k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
613k
      return true;
216
613k
    }
217
218
    /// Small tree.
219
2.49M
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
117k
      writer->Write(1, 1);
222
117k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
117k
      } else {
226
117k
        writer->Write(1, num_symbols_ - 1);
227
315k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
197k
          StoreVarLenUint8(symbols_[i], writer);
229
197k
        }
230
117k
      }
231
117k
      if (num_symbols_ == 2) {
232
79.7k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
79.7k
      }
234
235
117k
      return true;
236
117k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
2.38M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
2.38M
    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.38M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
2.38M
    int log = FloorLog2Nonzero(method_);
249
2.38M
    writer->Write(log, (1 << log) - 1);
250
2.38M
    if (log != upper_bound_log) writer->Write(1, 0);
251
2.38M
    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.38M
    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.38M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
2.38M
    size_t last = 0;
262
90.3M
    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
87.9M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
81.8M
          counts_[i] != counts_[last]) {
270
47.6M
        same[last] = i - last;
271
47.6M
        last = i;
272
47.6M
      }
273
87.9M
    }
274
275
2.38M
    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.38M
    int omit_width = 10;
281
90.3M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
87.9M
      if (i != omit_pos_ && counts_[i] > 0) {
283
39.2M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
39.2M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
39.2M
      }
286
87.9M
    }
287
2.38M
    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.38M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
2.38M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
2.38M
    };
294
2.38M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
2.38M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
2.38M
    };
297
2.38M
    constexpr uint8_t kMinReps = 5;
298
2.38M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
59.2M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
56.8M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
56.8M
                    kBitWidthSymbols[bit_width[i]]);
303
56.8M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.76M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.76M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.76M
        i += same[i] - 1;
308
1.76M
      }
309
56.8M
    }
310
    // Encode additional bits of accuracy
311
2.38M
    uint32_t shift = method_ - 1;
312
2.38M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
43.4M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
41.7M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
28.1M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
28.1M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
28.1M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
28.1M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
28.1M
        }
320
41.7M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.24M
          i += same[i] - 1;
323
1.24M
        }
324
41.7M
      }
325
1.74M
    }
326
2.38M
    return true;
327
2.49M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::SizeWriter>(jxl::SizeWriter*)
Line
Count
Source
200
2.97M
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
2.97M
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
2.97M
    if (method_ == 0) {
207
      // Mark non-small tree.
208
610k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
610k
      writer->Write(1, 1);
211
610k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
610k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
610k
      return true;
216
610k
    }
217
218
    /// Small tree.
219
2.36M
    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
303k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
190k
          StoreVarLenUint8(symbols_[i], writer);
229
190k
        }
230
112k
      }
231
112k
      if (num_symbols_ == 2) {
232
77.5k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
77.5k
      }
234
235
112k
      return true;
236
112k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
2.25M
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
2.25M
    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.25M
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
2.25M
    int log = FloorLog2Nonzero(method_);
249
2.25M
    writer->Write(log, (1 << log) - 1);
250
2.25M
    if (log != upper_bound_log) writer->Write(1, 0);
251
2.25M
    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.25M
    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.25M
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
2.25M
    size_t last = 0;
262
85.9M
    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
83.7M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
77.9M
          counts_[i] != counts_[last]) {
270
45.1M
        same[last] = i - last;
271
45.1M
        last = i;
272
45.1M
      }
273
83.7M
    }
274
275
2.25M
    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.25M
    int omit_width = 10;
281
85.9M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
83.7M
      if (i != omit_pos_ && counts_[i] > 0) {
283
37.0M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
37.0M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
37.0M
      }
286
83.7M
    }
287
2.25M
    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.25M
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
2.25M
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
2.25M
    };
294
2.25M
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
2.25M
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
2.25M
    };
297
2.25M
    constexpr uint8_t kMinReps = 5;
298
2.25M
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
56.0M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
53.8M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
53.8M
                    kBitWidthSymbols[bit_width[i]]);
303
53.8M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
1.69M
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
1.69M
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
1.69M
        i += same[i] - 1;
308
1.69M
      }
309
53.8M
    }
310
    // Encode additional bits of accuracy
311
2.25M
    uint32_t shift = method_ - 1;
312
2.25M
    if (shift != 0) {  // otherwise `bitcount = 0`
313
42.3M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
40.6M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
27.4M
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
27.4M
          int drop_bits = bit_width[i] - 1 - bitcount;
317
27.4M
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
27.4M
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
27.4M
        }
320
40.6M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
1.22M
          i += same[i] - 1;
323
1.22M
        }
324
40.6M
      }
325
1.69M
    }
326
2.25M
    return true;
327
2.36M
  }
enc_ans.cc:jxl::Status jxl::(anonymous namespace)::ANSEncodingHistogram::Encode<jxl::BitWriter>(jxl::BitWriter*)
Line
Count
Source
200
139k
  Status Encode(Writer* writer) {
201
    // The check ensures also that all RLE sequences can be
202
    // encoded by `StoreVarLenUint8`
203
139k
    JXL_ENSURE(alphabet_size_ <= ANS_MAX_ALPHABET_SIZE);
204
205
    /// Flat histogram.
206
139k
    if (method_ == 0) {
207
      // Mark non-small tree.
208
3.28k
      writer->Write(1, 0);
209
      // Mark uniform histogram.
210
3.28k
      writer->Write(1, 1);
211
3.28k
      JXL_ENSURE(alphabet_size_ > 0);
212
      // Encode alphabet size.
213
3.28k
      StoreVarLenUint8(alphabet_size_ - 1, writer);
214
215
3.28k
      return true;
216
3.28k
    }
217
218
    /// Small tree.
219
135k
    if (num_symbols_ <= kMaxNumSymbolsForSmallCode) {
220
      // Small tree marker to encode 1-2 symbols.
221
4.99k
      writer->Write(1, 1);
222
4.99k
      if (num_symbols_ == 0) {
223
0
        writer->Write(1, 0);
224
0
        StoreVarLenUint8(0, writer);
225
4.99k
      } else {
226
4.99k
        writer->Write(1, num_symbols_ - 1);
227
12.1k
        for (size_t i = 0; i < num_symbols_; ++i) {
228
7.16k
          StoreVarLenUint8(symbols_[i], writer);
229
7.16k
        }
230
4.99k
      }
231
4.99k
      if (num_symbols_ == 2) {
232
2.16k
        writer->Write(ANS_LOG_TAB_SIZE, counts_[symbols_[0]]);
233
2.16k
      }
234
235
4.99k
      return true;
236
4.99k
    }
237
238
    /// General tree.
239
    // Mark non-small tree.
240
130k
    writer->Write(1, 0);
241
    // Mark non-flat histogram.
242
130k
    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
130k
    int upper_bound_log = FloorLog2Nonzero(ANS_LOG_TAB_SIZE + 1);
248
130k
    int log = FloorLog2Nonzero(method_);
249
130k
    writer->Write(log, (1 << log) - 1);
250
130k
    if (log != upper_bound_log) writer->Write(1, 0);
251
130k
    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
130k
    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
130k
    uint8_t same[ANS_MAX_ALPHABET_SIZE] = {};
261
130k
    size_t last = 0;
262
4.38M
    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
4.25M
      if (i == alphabet_size_ || i == omit_pos_ || i == omit_pos_ + 1 ||
269
3.92M
          counts_[i] != counts_[last]) {
270
2.47M
        same[last] = i - last;
271
2.47M
        last = i;
272
2.47M
      }
273
4.25M
    }
274
275
130k
    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
130k
    int omit_width = 10;
281
4.38M
    for (size_t i = 0; i < alphabet_size_; ++i) {
282
4.25M
      if (i != omit_pos_ && counts_[i] > 0) {
283
2.14M
        bit_width[i] = FloorLog2Nonzero<uint32_t>(counts_[i]) + 1;
284
2.14M
        omit_width = std::max(omit_width, bit_width[i] + int{i < omit_pos_});
285
2.14M
      }
286
4.25M
    }
287
130k
    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
130k
    constexpr uint8_t kBitWidthLengths[ANS_LOG_TAB_SIZE + 2] = {
292
130k
        5, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 6, 7, 7,
293
130k
    };
294
130k
    constexpr uint8_t kBitWidthSymbols[ANS_LOG_TAB_SIZE + 2] = {
295
130k
        17, 11, 15, 3, 9, 7, 4, 2, 5, 6, 0, 33, 1, 65,
296
130k
    };
297
130k
    constexpr uint8_t kMinReps = 5;
298
130k
    constexpr size_t rep = ANS_LOG_TAB_SIZE + 1;
299
    // Encode count bit widths
300
3.15M
    for (size_t i = 0; i < alphabet_size_; ++i) {
301
3.01M
      writer->Write(kBitWidthLengths[bit_width[i]],
302
3.01M
                    kBitWidthSymbols[bit_width[i]]);
303
3.01M
      if (same[i] >= kMinReps) {
304
        // Encode the RLE symbol and skip the repeated ones.
305
78.2k
        writer->Write(kBitWidthLengths[rep], kBitWidthSymbols[rep]);
306
78.2k
        StoreVarLenUint8(same[i] - kMinReps, writer);
307
78.2k
        i += same[i] - 1;
308
78.2k
      }
309
3.01M
    }
310
    // Encode additional bits of accuracy
311
130k
    uint32_t shift = method_ - 1;
312
130k
    if (shift != 0) {  // otherwise `bitcount = 0`
313
1.13M
      for (size_t i = 0; i < alphabet_size_; ++i) {
314
1.08M
        if (bit_width[i] > 1 && i != omit_pos_) {
315
739k
          int bitcount = GetPopulationCountPrecision(bit_width[i] - 1, shift);
316
739k
          int drop_bits = bit_width[i] - 1 - bitcount;
317
739k
          JXL_DASSERT((counts_[i] & ((1 << drop_bits) - 1)) == 0);
318
739k
          writer->Write(bitcount, (counts_[i] >> drop_bits) - (1 << bitcount));
319
739k
        }
320
1.08M
        if (same[i] >= kMinReps) {
321
          // Skip symbols encoded by RLE.
322
28.6k
          i += same[i] - 1;
323
28.6k
        }
324
1.08M
      }
325
46.9k
    }
326
130k
    return true;
327
135k
  }
328
329
  void ANSBuildInfoTable(const AliasTable::Entry* table, size_t log_alpha_size,
330
142k
                         ANSEncSymbolInfo* info) {
331
    // Create valid alias table for empty streams
332
4.86M
    for (size_t s = 0; s < std::max(size_t{1}, alphabet_size_); ++s) {
333
4.72M
      const ANSHistBin freq = s == alphabet_size_ ? ANS_TAB_SIZE : counts_[s];
334
4.72M
      info[s].freq_ = static_cast<uint16_t>(freq);
335
4.72M
#ifdef USE_MULT_BY_RECIPROCAL
336
4.72M
      if (freq != 0) {
337
2.45M
        info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) /
338
2.45M
                         info[s].freq_;
339
2.45M
      } else {
340
2.26M
        info[s].ifreq_ =
341
2.26M
            1;  // Shouldn't matter (symbol shouldn't occur), but...
342
2.26M
      }
343
4.72M
#endif
344
4.72M
      info[s].reverse_map_.resize(freq);
345
4.72M
    }
346
142k
    size_t log_entry_size = ANS_LOG_TAB_SIZE - log_alpha_size;
347
142k
    size_t entry_size_minus_1 = (1 << log_entry_size) - 1;
348
585M
    for (int i = 0; i < ANS_TAB_SIZE; i++) {
349
585M
      AliasTable::Symbol s =
350
585M
          AliasTable::Lookup(table, i, log_entry_size, entry_size_minus_1);
351
585M
      info[s.value].reverse_map_[s.offset] = i;
352
585M
    }
353
142k
  }
354
355
 private:
356
610k
  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.32M
  float EstimateDataBits(const Histogram& histo) {
363
2.32M
    int64_t sum = 0;
364
86.7M
    for (size_t i = 0; i < alphabet_size_; ++i) {
365
      // += histogram[i] * -log(counts[i]/total_counts)
366
84.4M
      sum += histo.counts[i] * int64_t{lg2[counts_[i]]};
367
84.4M
    }
368
2.32M
    return (histo.total_count - ldexpf(sum, -31)) * ANS_LOG_TAB_SIZE;
369
2.32M
  }
370
371
610k
  static float EstimateDataBitsFlat(const Histogram& histo) {
372
610k
    size_t len = histo.alphabet_size();
373
610k
    int64_t flat_bits = int64_t{lg2[len]} * ANS_LOG_TAB_SIZE;
374
610k
    return ldexpf(histo.total_count * flat_bits, -31);
375
610k
  }
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
98.8M
  static uint32_t SmallestIncrementLog(uint32_t count, uint32_t shift) {
400
98.8M
    if (count == 0) return 0;
401
53.9M
    uint32_t bits = FloorLog2Nonzero(count);
402
53.9M
    uint32_t drop_bits = bits - GetPopulationCountPrecision(bits, shift);
403
53.9M
    return drop_bits;
404
98.8M
  }
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.32M
  bool RebalanceHistogram(const Histogram& histo) {
417
2.32M
    constexpr ANSHistBin table_size = ANS_TAB_SIZE;
418
2.32M
    uint32_t shift = method_ - 1;
419
420
2.32M
    struct EntropyDelta {
421
2.32M
      ANSHistBin freq;   // initial count
422
2.32M
      size_t count_ind;  // index of current bin value in `allowed_counts`
423
2.32M
      size_t bin_ind;    // index of current bin in `counts`
424
2.32M
    };
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.32M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_inc = {};
428
2.32M
    std::array<int64_t, ANS_LOG_TAB_SIZE - 1> balance_dec = {};
429
2.32M
    const auto& ac = allowed_counts.array[shift];
430
2.32M
    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
702M
    const auto delta_entropy_inc = [&](const EntropyDelta& a) {
437
702M
      return a.freq * int64_t{ac[a.count_ind].delta_lg2} -
438
702M
             balance_inc[ac[a.count_ind].step_log];
439
702M
    };
440
106M
    const auto delta_entropy_dec = [&](const EntropyDelta& a) {
441
106M
      return a.freq * int64_t{ac[a.count_ind + 1].delta_lg2} -
442
106M
             balance_dec[ac[a.count_ind + 1].step_log];
443
106M
    };
444
    // Compare steps by entropy increase per unit of histogram bin change.
445
    // Truncation is OK here, accuracy is anyway better than float
446
344M
    const auto IncLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
447
344M
      return delta_entropy_inc(a) >> ac[a.count_ind].step_log <
448
344M
             delta_entropy_inc(b) >> ac[b.count_ind].step_log;
449
344M
    };
450
51.7M
    const auto DecLess = [&](const EntropyDelta& a, const EntropyDelta& b) {
451
51.7M
      return delta_entropy_dec(a) >> ac[a.count_ind + 1].step_log <
452
51.7M
             delta_entropy_dec(b) >> ac[b.count_ind + 1].step_log;
453
51.7M
    };
454
    // Vector of adjustable bins from `allowed_counts`
455
2.32M
    std::vector<EntropyDelta> bins;
456
2.32M
    bins.reserve(256);
457
458
2.32M
    double norm = double{table_size} / histo.total_count;
459
460
2.32M
    size_t remainder_pos = 0;  // highest balancing bin in the histogram
461
2.32M
    int64_t max_freq = 0;
462
2.32M
    ANSHistBin rest = table_size;  // reserve of histogram counts to distribute
463
86.7M
    for (size_t n = 0; n < alphabet_size_; ++n) {
464
84.4M
      ANSHistBin freq = histo.counts[n];
465
84.4M
      if (freq > max_freq) {
466
5.71M
        remainder_pos = n;
467
5.71M
        max_freq = freq;
468
5.71M
      }
469
470
84.4M
      double target = freq * norm;  // rounding
471
      // Keep zeros and clamp nonzero freq counts to [1, table_size)
472
84.4M
      ANSHistBin count = std::max<ANSHistBin>(round(target), freq > 0);
473
84.4M
      count = std::min<ANSHistBin>(count, table_size - 1);
474
84.4M
      uint32_t step_log = SmallestIncrementLog(count, shift);
475
84.4M
      ANSHistBin inc = 1 << step_log;
476
84.4M
      count &= ~(inc - 1);
477
478
84.4M
      counts_[n] = count;
479
84.4M
      rest -= count;
480
84.4M
      if (target > 1.0) {
481
39.1M
        bins.push_back({freq, ai[count], n});
482
39.1M
      }
483
84.4M
    }
484
485
    // Delete the highest balancing bin from adjustable by `allowed_counts`
486
2.32M
    bins.erase(std::find_if(
487
2.32M
        bins.begin(), bins.end(),
488
13.9M
        [&](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.32M
    rest += counts_[remainder_pos];
492
493
2.32M
    if (!bins.empty()) {
494
2.32M
      const uint32_t max_log = ac[1].step_log;
495
13.9M
      while (true) {
496
        // Update balancing bin penalties setting guards and tractors
497
123M
        for (uint32_t log = 0; log <= max_log; ++log) {
498
109M
          ANSHistBin delta = 1 << log;
499
109M
          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
109M
          } else if (rest > 1) {
504
            // `rest` is OK, put guards against non-possible steps
505
109M
            balance_inc[log] =
506
109M
                rest > delta  // possible step
507
109M
                    ? max_freq * int64_t{lg2[rest] - lg2[rest - delta]}
508
109M
                    : std::numeric_limits<int64_t>::max();  // forbidden
509
109M
            balance_dec[log] =
510
109M
                rest + delta < table_size  // possible step
511
109M
                    ? max_freq * int64_t{lg2[rest + delta] - lg2[rest]}
512
109M
                    : 0;  // forbidden
513
109M
          } else {
514
            // Tract negative or zero `rest` into positive:
515
            // forbid all inc steps
516
332
            balance_inc[log] = std::numeric_limits<int64_t>::max();
517
            // permit all dec steps
518
332
            balance_dec[log] = std::numeric_limits<int64_t>::max();
519
332
          }
520
109M
        }
521
        // Try to increase entropy
522
13.9M
        auto best_bin_inc = std::max_element(bins.begin(), bins.end(), IncLess);
523
13.9M
        if (delta_entropy_inc(*best_bin_inc) > 0) {
524
          // Grow the bin with the best histogram entropy increase
525
10.9M
          rest -= 1 << ac[best_bin_inc->count_ind--].step_log;
526
10.9M
        } else {
527
          // This still implies that entropy is strictly increasing each step
528
          // (or `rest` is tracted into positive domain), so we cannot loop
529
          // infinitely
530
2.95M
          auto best_bin_dec =
531
2.95M
              std::min_element(bins.begin(), bins.end(), DecLess);
532
          // Break if no reverse steps can grow entropy (or valid)
533
2.95M
          if (delta_entropy_dec(*best_bin_dec) >= 0) break;
534
          // Decrease the bin with the best histogram entropy increase
535
629k
          rest += 1 << ac[++best_bin_dec->count_ind].step_log;
536
629k
        }
537
13.9M
      }
538
      // Set counts besides the balancing bin
539
36.8M
      for (auto& a : bins) counts_[a.bin_ind] = ac[a.count_ind].count;
540
541
      // The scheme works fine if we have room to grow `bit_width` of balancing
542
      // bin, otherwise we need to put balancing bin to the first bin of 12 bit
543
      // width. In this case both that bin and balancing one should be close to
544
      // 2048 in targets, so exchange of them will not produce much worse
545
      // histogram
546
27.7M
      for (size_t n = 0; n < remainder_pos; ++n) {
547
25.4M
        if (counts_[n] >= 2048) {
548
8.98k
          counts_[remainder_pos] = counts_[n];
549
8.98k
          remainder_pos = n;
550
8.98k
          break;
551
8.98k
        }
552
25.4M
      }
553
2.32M
    }
554
    // Set balancing bin
555
2.32M
    counts_[remainder_pos] = rest;
556
2.32M
    omit_pos_ = remainder_pos;
557
558
2.32M
    return counts_[remainder_pos] > 0;
559
2.32M
  }
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
467k
StatusOr<float> Histogram::ANSPopulationCost() const {
620
467k
  if (counts.size() > ANS_MAX_ALPHABET_SIZE) {
621
0
    return std::numeric_limits<float>::max();
622
0
  }
623
467k
  JXL_ASSIGN_OR_RETURN(
624
467k
      ANSEncodingHistogram normalized,
625
467k
      ANSEncodingHistogram::ComputeBest(
626
467k
          *this, HistogramParams::ANSHistogramStrategy::kFast));
627
467k
  return normalized.Cost();
628
467k
}
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
165k
    const Histogram& histogram, BitWriter* writer) {
636
165k
  ANSEncSymbolInfo* info = encoding_info.back().data();
637
165k
  size_t size = histogram.alphabet_size();
638
165k
  if (use_prefix_code) {
639
22.9k
    size_t cost = 0;
640
22.9k
    if (size <= 1) return 0;
641
22.1k
    std::vector<uint32_t> histo(size);
642
208k
    for (size_t i = 0; i < size; i++) {
643
186k
      JXL_ENSURE(histogram.counts[i] >= 0);
644
186k
      histo[i] = histogram.counts[i];
645
186k
    }
646
22.1k
    std::vector<uint8_t> depths(size);
647
22.1k
    std::vector<uint16_t> bits(size);
648
22.1k
    if (writer == nullptr) {
649
15.4k
      BitWriter tmp_writer{memory_manager};
650
15.4k
      JXL_RETURN_IF_ERROR(tmp_writer.WithMaxBits(
651
15.4k
          8 * size + 8,  // safe upper bound
652
15.4k
          LayerType::Header, /*aux_out=*/nullptr, [&] {
653
15.4k
            return BuildAndStoreHuffmanTree(histo.data(), size, depths.data(),
654
15.4k
                                            bits.data(), &tmp_writer);
655
15.4k
          }));
656
15.4k
      cost = tmp_writer.BitsWritten();
657
15.4k
    } else {
658
6.75k
      size_t start = writer->BitsWritten();
659
6.75k
      JXL_RETURN_IF_ERROR(BuildAndStoreHuffmanTree(
660
6.75k
          histo.data(), size, depths.data(), bits.data(), writer));
661
6.75k
      cost = writer->BitsWritten() - start;
662
6.75k
    }
663
208k
    for (size_t i = 0; i < size; i++) {
664
186k
      info[i].bits = depths[i] == 0 ? 0 : bits[i];
665
186k
      info[i].depth = depths[i];
666
186k
    }
667
    // Estimate data cost.
668
208k
    for (size_t i = 0; i < size; i++) {
669
186k
      cost += histo[i] * info[i].depth;
670
186k
    }
671
22.1k
    return cost;
672
22.1k
  }
673
285k
  JXL_ASSIGN_OR_RETURN(
674
285k
      ANSEncodingHistogram normalized,
675
285k
      ANSEncodingHistogram::ComputeBest(histogram, ans_histogram_strategy));
676
677
  // TODO(eustas): fix: 2KiB on stack
678
285k
  AliasTable::Entry a[ANS_MAX_ALPHABET_SIZE];
679
680
285k
  JXL_RETURN_IF_ERROR(
681
285k
      InitAliasTable(normalized.Counts(), ANS_LOG_TAB_SIZE, log_alpha_size, a));
682
142k
  normalized.ANSBuildInfoTable(a, log_alpha_size, info);
683
142k
  if (writer != nullptr) {
684
    // size_t start = writer->BitsWritten();
685
139k
    JXL_RETURN_IF_ERROR(normalized.Encode(writer));
686
    // return writer->BitsWritten() - start;
687
139k
  }
688
142k
  return static_cast<size_t>(ceilf(normalized.Cost()));
689
142k
}
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
34.6k
    std::vector<Histogram>& clustered_histograms) {
716
  // Set sane default `log_alpha_size`.
717
34.6k
  if (use_prefix_code) {
718
22.7k
    log_alpha_size = PREFIX_MAX_BITS;
719
22.7k
  } else if (params.streaming_mode) {
720
    // TODO(szabadka) Figure out if we can use lower values here.
721
0
    log_alpha_size = 8;
722
11.9k
  } else if (lz77.enabled) {
723
1.99k
    log_alpha_size = 8;
724
9.98k
  } else {
725
9.98k
    log_alpha_size = 7;
726
9.98k
  }
727
728
34.6k
  if (ans_fuzzer_friendly_) {
729
0
    uint_config.assign(1, HybridUintConfig(7, 0, 0));
730
0
    return true;
731
0
  }
732
733
34.6k
  uint_config.assign(clustered_histograms.size(), params.UintConfig());
734
  // If the uint config is fixed, just use it.
735
34.6k
  if (params.uint_method != HistogramParams::HybridUintMethod::kBest &&
736
32.5k
      params.uint_method != HistogramParams::HybridUintMethod::kFast) {
737
25.9k
    return true;
738
25.9k
  }
739
  // Even if the uint config is adaptive, just stick with the default in
740
  // streaming mode.
741
8.77k
  if (params.streaming_mode) {
742
0
    return true;
743
0
  }
744
745
  // Brute-force method that tries a few options.
746
8.77k
  std::vector<HybridUintConfig> configs;
747
8.77k
  if (params.uint_method == HistogramParams::HybridUintMethod::kBest) {
748
2.16k
    configs = {
749
2.16k
        HybridUintConfig(4, 2, 0),  // default
750
2.16k
        HybridUintConfig(4, 1, 0),  // less precise
751
2.16k
        HybridUintConfig(4, 2, 1),  // add sign
752
2.16k
        HybridUintConfig(4, 2, 2),  // add sign+parity
753
2.16k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
754
        // Same as above, but more direct coding.
755
2.16k
        HybridUintConfig(5, 2, 0), HybridUintConfig(5, 1, 0),
756
2.16k
        HybridUintConfig(5, 2, 1), HybridUintConfig(5, 2, 2),
757
2.16k
        HybridUintConfig(5, 1, 2),
758
        // Same as above, but less direct coding.
759
2.16k
        HybridUintConfig(3, 2, 0), HybridUintConfig(3, 1, 0),
760
2.16k
        HybridUintConfig(3, 2, 1), HybridUintConfig(3, 1, 2),
761
        // For near-lossless.
762
2.16k
        HybridUintConfig(4, 1, 3), HybridUintConfig(5, 1, 4),
763
2.16k
        HybridUintConfig(5, 2, 3), HybridUintConfig(6, 1, 5),
764
2.16k
        HybridUintConfig(6, 2, 4), HybridUintConfig(6, 0, 0),
765
        // Other
766
2.16k
        HybridUintConfig(0, 0, 0),   // varlenuint
767
2.16k
        HybridUintConfig(2, 0, 1),   // works well for ctx map
768
2.16k
        HybridUintConfig(7, 0, 0),   // direct coding
769
2.16k
        HybridUintConfig(8, 0, 0),   // direct coding
770
2.16k
        HybridUintConfig(9, 0, 0),   // direct coding
771
2.16k
        HybridUintConfig(10, 0, 0),  // direct coding
772
2.16k
        HybridUintConfig(11, 0, 0),  // direct coding
773
2.16k
        HybridUintConfig(12, 0, 0),  // direct coding
774
2.16k
    };
775
6.60k
  } else {
776
6.60k
    JXL_DASSERT(params.uint_method == HistogramParams::HybridUintMethod::kFast);
777
6.60k
    configs = {
778
6.60k
        HybridUintConfig(4, 2, 0),  // default
779
6.60k
        HybridUintConfig(4, 1, 2),  // add parity but less msb
780
6.60k
        HybridUintConfig(0, 0, 0),  // smallest histograms
781
6.60k
        HybridUintConfig(2, 0, 1),  // works well for ctx map
782
6.60k
    };
783
6.60k
  }
784
785
8.77k
  size_t num_histo = clustered_histograms.size();
786
8.77k
  std::vector<uint8_t> is_valid(num_histo);
787
8.77k
  std::vector<size_t> histo_volume(2 * num_histo);
788
8.77k
  std::vector<size_t> histo_offset(2 * num_histo + 1);
789
8.77k
  std::vector<uint32_t> max_value_per_histo(2 * num_histo);
790
791
  // TODO(veluca): do not ignore lz77 commands.
792
793
81.8k
  for (const auto& stream : tokens) {
794
93.9M
    for (const auto& token : stream) {
795
93.9M
      size_t histo = context_map[token.context];
796
93.9M
      histo_volume[histo + (token.is_lz77_length ? num_histo : 0)]++;
797
93.9M
    }
798
81.8k
  }
799
8.77k
  size_t max_histo_volume = 0;
800
157k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
801
148k
    max_histo_volume = std::max(max_histo_volume, histo_volume[h]);
802
148k
    histo_offset[h + 1] = histo_offset[h] + histo_volume[h];
803
148k
  }
804
805
8.77k
  const size_t max_vec_size = MaxVectorSize();
806
8.77k
  std::vector<uint32_t> transposed(histo_offset[num_histo * 2] + max_vec_size);
807
8.77k
  {
808
8.77k
    std::vector<size_t> next_offset = histo_offset;  // copy
809
81.8k
    for (const auto& stream : tokens) {
810
93.9M
      for (const auto& token : stream) {
811
93.9M
        size_t histo =
812
93.9M
            context_map[token.context] + (token.is_lz77_length ? num_histo : 0);
813
93.9M
        transposed[next_offset[histo]++] = token.value;
814
93.9M
      }
815
81.8k
    }
816
8.77k
  }
817
157k
  for (size_t h = 0; h < 2 * num_histo; ++h) {
818
148k
    max_value_per_histo[h] =
819
148k
        MaxValue(transposed.data() + histo_offset[h], histo_volume[h]);
820
148k
  }
821
8.77k
  uint32_t max_lz77 = 0;
822
83.2k
  for (size_t h = num_histo; h < 2 * num_histo; ++h) {
823
74.4k
    max_lz77 = std::max(max_lz77, MaxValue(transposed.data() + histo_offset[h],
824
74.4k
                                           histo_volume[h]));
825
74.4k
  }
826
827
  // Wider histograms are assigned max cost in PopulationCost anyway
828
  // and therefore will not be used
829
8.77k
  size_t max_alpha = ANS_MAX_ALPHABET_SIZE;
830
831
8.77k
  JXL_ASSIGN_OR_RETURN(
832
8.77k
      AlignedMemory tmp,
833
8.77k
      AlignedMemory::Create(memory_manager, (max_histo_volume + max_vec_size) *
834
8.77k
                                                sizeof(uint32_t)));
835
83.2k
  for (size_t h = 0; h < num_histo; h++) {
836
74.4k
    float best_cost = std::numeric_limits<float>::max();
837
450k
    for (HybridUintConfig cfg : configs) {
838
450k
      uint32_t max_v = max_value_per_histo[h];
839
450k
      size_t capacity;
840
450k
      {
841
450k
        uint32_t tok, nbits, bits;
842
450k
        cfg.Encode(max_v, &tok, &nbits, &bits);
843
450k
        tok |= cfg.LsbMask();
844
450k
        if (tok >= max_alpha || (lz77.enabled && tok >= lz77.min_symbol)) {
845
10.4k
          continue;  // Not valid config for this context
846
10.4k
        }
847
440k
        capacity = tok + 1;
848
440k
      }
849
850
0
      Histogram histo;
851
440k
      histo.EnsureCapacity(capacity);
852
440k
      size_t len = histo_volume[h];
853
440k
      uint32_t* data = transposed.data() + histo_offset[h];
854
440k
      size_t extra_bits = EstimateTokenCost(data, len, cfg, tmp);
855
440k
      uint32_t* tmp_tokens = tmp.address<uint32_t>();
856
486M
      for (size_t i = 0; i < len; ++i) {
857
486M
        histo.FastAdd(tmp_tokens[i]);
858
486M
      }
859
440k
      histo.Condition();
860
440k
      JXL_ASSIGN_OR_RETURN(float cost, histo.ANSPopulationCost());
861
440k
      cost += extra_bits;
862
      // Add signaling cost of the hybriduintconfig itself.
863
440k
      cost += CeilLog2Nonzero(cfg.split_exponent + 1);
864
440k
      cost += CeilLog2Nonzero(cfg.split_exponent - cfg.msb_in_token + 1);
865
440k
      if (cost < best_cost) {
866
152k
        uint_config[h] = cfg;
867
152k
        best_cost = cost;
868
152k
        clustered_histograms[h].swap(histo);
869
152k
      }
870
440k
    }
871
74.4k
  }
872
873
8.77k
  size_t max_tok = 0;
874
83.2k
  for (size_t h = 0; h < num_histo; ++h) {
875
74.4k
    Histogram& histo = clustered_histograms[h];
876
74.4k
    max_tok = std::max(max_tok, histo.MaxSymbol());
877
74.4k
    size_t len = histo_volume[num_histo + h];
878
74.4k
    if (len == 0) continue;  // E.g. when lz77 not enabled
879
501
    size_t max_histo_tok = max_value_per_histo[num_histo + h];
880
501
    uint32_t tok, nbits, bits;
881
501
    lz77.length_uint_config.Encode(max_histo_tok, &tok, &nbits, &bits);
882
501
    tok |= lz77.length_uint_config.LsbMask();
883
501
    tok += lz77.min_symbol;
884
501
    histo.EnsureCapacity(tok + 1);
885
501
    uint32_t* data = transposed.data() + histo_offset[num_histo + h];
886
501
    uint32_t unused =
887
501
        EstimateTokenCost(data, len, lz77.length_uint_config, tmp);
888
501
    (void)unused;
889
501
    uint32_t* tmp_tokens = tmp.address<uint32_t>();
890
6.01k
    for (size_t i = 0; i < len; ++i) {
891
5.51k
      histo.FastAdd(tmp_tokens[i] + lz77.min_symbol);
892
5.51k
    }
893
501
    histo.Condition();
894
501
    max_tok = std::max(max_tok, histo.MaxSymbol());
895
501
  }
896
897
  // `log_alpha_size - 5` is encoded in the header, so min is 5.
898
8.77k
  size_t log_size = 5;
899
14.5k
  while (max_tok >= (1u << log_size)) ++log_size;
900
901
8.77k
  size_t max_log_alpha_size = use_prefix_code ? PREFIX_MAX_BITS : 8;
902
8.77k
  JXL_ENSURE(log_size <= max_log_alpha_size);
903
904
8.77k
  if (use_prefix_code) {
905
2.91k
    log_alpha_size = PREFIX_MAX_BITS;
906
5.85k
  } else {
907
5.85k
    log_alpha_size = log_size;
908
5.85k
  }
909
910
8.77k
  return true;
911
8.77k
}
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
34.6k
    AuxOut* aux_out) {
920
34.6k
  const size_t prev_histograms = encoding_info.size();
921
34.6k
  std::vector<Histogram> clustered_histograms;
922
34.6k
  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
34.6k
  size_t context_offset = context_map.size();
927
34.6k
  context_map.resize(context_offset + builder.size());
928
34.6k
  if (builder.size() > 1) {
929
13.2k
    if (!ans_fuzzer_friendly_) {
930
13.2k
      std::vector<uint32_t> histogram_symbols;
931
13.2k
      JXL_RETURN_IF_ERROR(ClusterHistograms(params, builder, kClustersLimit,
932
13.2k
                                            &clustered_histograms,
933
13.2k
                                            &histogram_symbols));
934
14.0M
      for (size_t c = 0; c < builder.size(); ++c) {
935
14.0M
        context_map[context_offset + c] =
936
14.0M
            static_cast<uint8_t>(histogram_symbols[c]);
937
14.0M
      }
938
13.2k
    } 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
13.2k
    if (writer != nullptr) {
953
11.9k
      JXL_RETURN_IF_ERROR(EncodeContextMap(
954
11.9k
          context_map, clustered_histograms.size(), writer, layer, aux_out));
955
11.9k
    }
956
21.4k
  } else {
957
21.4k
    JXL_ENSURE(encoding_info.empty());
958
21.4k
    clustered_histograms.push_back(builder[0]);
959
21.4k
  }
960
34.6k
  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
34.6k
  JXL_RETURN_IF_ERROR(
968
34.6k
      ChooseUintConfigs(memory_manager, params, tokens, clustered_histograms));
969
970
34.6k
  SizeWriter size_writer;  // Used if writer == nullptr to estimate costs.
971
34.6k
  size_t cost = use_prefix_code ? 1 : 3;
972
973
34.6k
  if (writer) writer->Write(1, TO_JXL_BOOL(use_prefix_code));
974
34.6k
  if (writer == nullptr) {
975
18.3k
    EncodeUintConfigs(uint_config, &size_writer, log_alpha_size);
976
18.3k
  } else {
977
16.3k
    if (!use_prefix_code) writer->Write(2, log_alpha_size - 5);
978
16.3k
    EncodeUintConfigs(uint_config, writer, log_alpha_size);
979
16.3k
  }
980
34.6k
  if (use_prefix_code) {
981
22.9k
    for (const auto& histo : clustered_histograms) {
982
22.9k
      size_t alphabet_size = std::max<size_t>(1, histo.alphabet_size());
983
22.9k
      if (writer) {
984
7.47k
        StoreVarLenUint16(alphabet_size - 1, writer);
985
15.4k
      } else {
986
15.4k
        StoreVarLenUint16(alphabet_size - 1, &size_writer);
987
15.4k
      }
988
22.9k
    }
989
22.7k
  }
990
34.6k
  cost += size_writer.size;
991
200k
  for (size_t c = prev_histograms; c < clustered_histograms.size(); ++c) {
992
165k
    size_t alphabet_size = clustered_histograms[c].alphabet_size();
993
165k
    encoding_info.emplace_back();
994
165k
    encoding_info.back().resize(alphabet_size);
995
165k
    BitWriter* histo_writer = writer;
996
165k
    if (params.streaming_mode) {
997
0
      encoded_histograms.emplace_back(memory_manager);
998
0
      histo_writer = &encoded_histograms.back();
999
0
    }
1000
165k
    const auto& body = [&]() -> Status {
1001
165k
      JXL_ASSIGN_OR_RETURN(size_t ans_cost,
1002
165k
                           BuildAndStoreANSEncodingData(
1003
165k
                               memory_manager, params.ans_histogram_strategy,
1004
165k
                               clustered_histograms[c], histo_writer));
1005
165k
      cost += ans_cost;
1006
165k
      return true;
1007
165k
    };
1008
165k
    if (histo_writer) {
1009
146k
      JXL_RETURN_IF_ERROR(histo_writer->WithMaxBits(
1010
146k
          256 + alphabet_size * 24, layer, aux_out, body,
1011
146k
          /*finished_histogram=*/true));
1012
146k
    } else {
1013
19.3k
      JXL_RETURN_IF_ERROR(body());
1014
19.3k
    }
1015
165k
    if (params.streaming_mode) {
1016
0
      JXL_RETURN_IF_ERROR(writer->AppendUnaligned(*histo_writer));
1017
0
    }
1018
165k
  }
1019
34.6k
  return cost;
1020
34.6k
}
1021
1022
template <typename Writer>
1023
void EncodeUintConfig(const HybridUintConfig uint_config, Writer* writer,
1024
168k
                      size_t log_alpha_size) {
1025
168k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
168k
                uint_config.split_exponent);
1027
168k
  if (uint_config.split_exponent == log_alpha_size) {
1028
48
    return;  // msb/lsb don't matter.
1029
48
  }
1030
168k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
168k
  writer->Write(nbits, uint_config.msb_in_token);
1032
168k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
168k
                          uint_config.msb_in_token + 1);
1034
168k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
168k
}
void jxl::EncodeUintConfig<jxl::SizeWriter>(jxl::HybridUintConfig, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1024
20.7k
                      size_t log_alpha_size) {
1025
20.7k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
20.7k
                uint_config.split_exponent);
1027
20.7k
  if (uint_config.split_exponent == log_alpha_size) {
1028
0
    return;  // msb/lsb don't matter.
1029
0
  }
1030
20.7k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
20.7k
  writer->Write(nbits, uint_config.msb_in_token);
1032
20.7k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
20.7k
                          uint_config.msb_in_token + 1);
1034
20.7k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
20.7k
}
void jxl::EncodeUintConfig<jxl::BitWriter>(jxl::HybridUintConfig, jxl::BitWriter*, unsigned long)
Line
Count
Source
1024
147k
                      size_t log_alpha_size) {
1025
147k
  writer->Write(CeilLog2Nonzero(log_alpha_size + 1),
1026
147k
                uint_config.split_exponent);
1027
147k
  if (uint_config.split_exponent == log_alpha_size) {
1028
48
    return;  // msb/lsb don't matter.
1029
48
  }
1030
147k
  size_t nbits = CeilLog2Nonzero(uint_config.split_exponent + 1);
1031
147k
  writer->Write(nbits, uint_config.msb_in_token);
1032
147k
  nbits = CeilLog2Nonzero(uint_config.split_exponent -
1033
147k
                          uint_config.msb_in_token + 1);
1034
147k
  writer->Write(nbits, uint_config.lsb_in_token);
1035
147k
}
1036
template <typename Writer>
1037
void EncodeUintConfigs(const std::vector<HybridUintConfig>& uint_config,
1038
34.6k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
165k
  for (const auto& cfg : uint_config) {
1041
165k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
165k
  }
1043
34.6k
}
void jxl::EncodeUintConfigs<jxl::BitWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::BitWriter*, unsigned long)
Line
Count
Source
1038
16.3k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
146k
  for (const auto& cfg : uint_config) {
1041
146k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
146k
  }
1043
16.3k
}
void jxl::EncodeUintConfigs<jxl::SizeWriter>(std::__1::vector<jxl::HybridUintConfig, std::__1::allocator<jxl::HybridUintConfig> > const&, jxl::SizeWriter*, unsigned long)
Line
Count
Source
1038
18.3k
                       Writer* writer, size_t log_alpha_size) {
1039
  // TODO(veluca): RLE?
1040
19.3k
  for (const auto& cfg : uint_config) {
1041
19.3k
    EncodeUintConfig(cfg, writer, log_alpha_size);
1042
19.3k
  }
1043
18.3k
}
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
34.6k
    AuxOut* aux_out) {
1087
  // TODO(Ivan): presumably not needed - default
1088
  // if (params.initialize_global_state) codes->lz77.enabled = false;
1089
34.6k
  codes->lz77.nonserialized_distance_context = num_contexts;
1090
34.6k
  codes->lz77.min_symbol = params.force_huffman ? 512 : 224;
1091
34.6k
  std::vector<std::vector<Token>> tokens_lz77 =
1092
34.6k
      ApplyLZ77(params, num_contexts, tokens, codes->lz77);
1093
34.6k
  if (!tokens_lz77.empty()) codes->lz77.enabled = true;
1094
34.6k
  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
34.6k
  size_t cost = 0;
1100
34.6k
  const size_t max_contexts = std::min(num_contexts, kClustersLimit);
1101
34.6k
  const auto& body = [&]() -> Status {
1102
34.6k
    if (writer) {
1103
16.3k
      JXL_RETURN_IF_ERROR(Bundle::Write(codes->lz77, writer, layer, aux_out));
1104
18.3k
    } else {
1105
18.3k
      size_t ebits, bits;
1106
18.3k
      JXL_RETURN_IF_ERROR(Bundle::CanEncode(codes->lz77, &ebits, &bits));
1107
18.3k
      cost += bits;
1108
18.3k
    }
1109
34.6k
    if (codes->lz77.enabled) {
1110
2.22k
      if (writer) {
1111
896
        size_t b = writer->BitsWritten();
1112
896
        EncodeUintConfig(codes->lz77.length_uint_config, writer,
1113
896
                         /*log_alpha_size=*/8);
1114
896
        cost += writer->BitsWritten() - b;
1115
1.32k
      } else {
1116
1.32k
        SizeWriter size_writer;
1117
1.32k
        EncodeUintConfig(codes->lz77.length_uint_config, &size_writer,
1118
1.32k
                         /*log_alpha_size=*/8);
1119
1.32k
        cost += size_writer.size;
1120
1.32k
      }
1121
2.22k
      num_contexts += 1;
1122
2.22k
      tokens = std::move(tokens_lz77);
1123
2.22k
    }
1124
34.6k
    size_t total_tokens = 0;
1125
    // Build histograms.
1126
34.6k
    std::vector<Histogram> builder(num_contexts);
1127
34.6k
    HybridUintConfig uint_config = params.UintConfig();
1128
34.6k
    if (ans_fuzzer_friendly_) {
1129
0
      uint_config = HybridUintConfig(10, 0, 0);
1130
0
    }
1131
111k
    for (const auto& stream : tokens) {
1132
111k
      if (codes->lz77.enabled) {
1133
2.47M
        for (const auto& token : stream) {
1134
2.47M
          total_tokens++;
1135
2.47M
          uint32_t tok, nbits, bits;
1136
2.47M
          (token.is_lz77_length ? codes->lz77.length_uint_config : uint_config)
1137
2.47M
              .Encode(token.value, &tok, &nbits, &bits);
1138
2.47M
          tok += token.is_lz77_length ? codes->lz77.min_symbol : 0;
1139
2.47M
          JXL_DASSERT(token.context < num_contexts);
1140
2.47M
          builder[token.context].Add(tok);
1141
2.47M
        }
1142
108k
      } else if (num_contexts == 1) {
1143
8.69M
        for (const auto& token : stream) {
1144
8.69M
          total_tokens++;
1145
8.69M
          uint32_t tok, nbits, bits;
1146
8.69M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1147
8.69M
          builder[0].Add(tok);
1148
8.69M
        }
1149
86.8k
      } else {
1150
243M
        for (const auto& token : stream) {
1151
243M
          total_tokens++;
1152
243M
          uint32_t tok, nbits, bits;
1153
243M
          uint_config.Encode(token.value, &tok, &nbits, &bits);
1154
243M
          JXL_DASSERT(token.context < num_contexts);
1155
243M
          builder[token.context].Add(tok);
1156
243M
        }
1157
86.8k
      }
1158
111k
    }
1159
1160
34.6k
    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
34.6k
    if (params.initialize_global_state) {
1169
34.6k
      bool use_prefix_code =
1170
34.6k
          params.force_huffman || total_tokens < 100 ||
1171
12.0k
          params.clustering == HistogramParams::ClusteringType::kFastest ||
1172
12.0k
          ans_fuzzer_friendly_;
1173
34.6k
      if (!use_prefix_code) {
1174
12.0k
        bool all_singleton = true;
1175
8.45M
        for (size_t i = 0; i < num_contexts; i++) {
1176
8.44M
          if (builder[i].ShannonEntropy() >= 1e-5) {
1177
1.08M
            all_singleton = false;
1178
1.08M
          }
1179
8.44M
        }
1180
12.0k
        if (all_singleton) {
1181
100
          use_prefix_code = true;
1182
100
        }
1183
12.0k
      }
1184
34.6k
      codes->use_prefix_code = use_prefix_code;
1185
34.6k
    }
1186
1187
34.6k
    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
34.6k
    JXL_ASSIGN_OR_RETURN(
1216
34.6k
        size_t entropy_bits,
1217
34.6k
        codes->BuildAndStoreEntropyCodes(memory_manager, params, tokens,
1218
34.6k
                                         builder, writer, layer, aux_out));
1219
34.6k
    cost += entropy_bits;
1220
34.6k
    return true;
1221
34.6k
  };
1222
34.6k
  if (writer) {
1223
16.3k
    JXL_RETURN_IF_ERROR(writer->WithMaxBits(
1224
16.3k
        128 + num_contexts * 40 + max_contexts * 96, layer, aux_out, body,
1225
16.3k
        /*finished_histogram=*/true));
1226
18.3k
  } else {
1227
18.3k
    JXL_RETURN_IF_ERROR(body());
1228
18.3k
  }
1229
1230
34.6k
  if (aux_out != nullptr) {
1231
0
    aux_out->layer(layer).num_clustered_histograms +=
1232
0
        codes->encoding_info.size();
1233
0
  }
1234
34.6k
  return cost;
1235
34.6k
}
1236
1237
size_t WriteTokens(const std::vector<Token>& tokens,
1238
                   const EntropyEncodingData& codes, size_t context_offset,
1239
24.9k
                   BitWriter* writer) {
1240
24.9k
  size_t num_extra_bits = 0;
1241
24.9k
  if (codes.use_prefix_code) {
1242
628k
    for (const auto& token : tokens) {
1243
628k
      uint32_t tok, nbits, bits;
1244
628k
      size_t histo = codes.context_map[context_offset + token.context];
1245
628k
      (token.is_lz77_length ? codes.lz77.length_uint_config
1246
628k
                            : codes.uint_config[histo])
1247
628k
          .Encode(token.value, &tok, &nbits, &bits);
1248
628k
      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
628k
      uint64_t data = codes.encoding_info[histo][tok].bits;
1254
628k
      data |= static_cast<uint64_t>(bits)
1255
628k
              << codes.encoding_info[histo][tok].depth;
1256
628k
      writer->Write(codes.encoding_info[histo][tok].depth + nbits, data);
1257
628k
      num_extra_bits += nbits;
1258
628k
    }
1259
8.51k
    return num_extra_bits;
1260
8.51k
  }
1261
16.4k
  std::vector<uint64_t> out;
1262
16.4k
  std::vector<uint8_t> out_nbits;
1263
16.4k
  out.reserve(tokens.size());
1264
16.4k
  out_nbits.reserve(tokens.size());
1265
16.4k
  uint64_t allbits = 0;
1266
16.4k
  size_t numallbits = 0;
1267
  // Writes in *reversed* order.
1268
493M
  auto addbits = [&](size_t bits, size_t nbits) {
1269
493M
    if (JXL_UNLIKELY(nbits)) {
1270
81.7M
      JXL_DASSERT(bits >> nbits == 0);
1271
81.7M
      if (JXL_UNLIKELY(numallbits + nbits > BitWriter::kMaxBitsPerCall)) {
1272
17.8M
        out.push_back(allbits);
1273
17.8M
        out_nbits.push_back(numallbits);
1274
17.8M
        numallbits = allbits = 0;
1275
17.8M
      }
1276
81.7M
      allbits <<= nbits;
1277
81.7M
      allbits |= bits;
1278
81.7M
      numallbits += nbits;
1279
81.7M
    }
1280
493M
  };
1281
16.4k
  const int end = tokens.size();
1282
16.4k
  ANSCoder ans;
1283
16.4k
  if (codes.lz77.enabled || codes.context_map.size() > 1) {
1284
244M
    for (int i = end - 1; i >= 0; --i) {
1285
244M
      const Token token = tokens[i];
1286
244M
      const uint8_t histo = codes.context_map[context_offset + token.context];
1287
244M
      uint32_t tok, nbits, bits;
1288
244M
      (token.is_lz77_length ? codes.lz77.length_uint_config
1289
244M
                            : codes.uint_config[histo])
1290
244M
          .Encode(tokens[i].value, &tok, &nbits, &bits);
1291
244M
      tok += token.is_lz77_length ? codes.lz77.min_symbol : 0;
1292
244M
      const ANSEncSymbolInfo& info = codes.encoding_info[histo][tok];
1293
244M
      JXL_DASSERT(info.freq_ > 0);
1294
      // Extra bits first as this is reversed.
1295
244M
      addbits(bits, nbits);
1296
244M
      num_extra_bits += nbits;
1297
244M
      uint8_t ans_nbits = 0;
1298
244M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1299
244M
      addbits(ans_bits, ans_nbits);
1300
244M
    }
1301
15.5k
  } else {
1302
2.59M
    for (int i = end - 1; i >= 0; --i) {
1303
2.59M
      uint32_t tok, nbits, bits;
1304
2.59M
      codes.uint_config[0].Encode(tokens[i].value, &tok, &nbits, &bits);
1305
2.59M
      const ANSEncSymbolInfo& info = codes.encoding_info[0][tok];
1306
      // Extra bits first as this is reversed.
1307
2.59M
      addbits(bits, nbits);
1308
2.59M
      num_extra_bits += nbits;
1309
2.59M
      uint8_t ans_nbits = 0;
1310
2.59M
      uint32_t ans_bits = ans.PutSymbol(info, &ans_nbits);
1311
2.59M
      addbits(ans_bits, ans_nbits);
1312
2.59M
    }
1313
868
  }
1314
16.4k
  const uint32_t state = ans.GetState();
1315
16.4k
  writer->Write(32, state);
1316
16.4k
  writer->Write(numallbits, allbits);
1317
17.8M
  for (int i = out.size(); i > 0; --i) {
1318
17.8M
    writer->Write(out_nbits[i - 1], out[i - 1]);
1319
17.8M
  }
1320
16.4k
  return num_extra_bits;
1321
24.9k
}
1322
1323
Status WriteTokens(const std::vector<Token>& tokens,
1324
                   const EntropyEncodingData& codes, size_t context_offset,
1325
19.9k
                   BitWriter* writer, LayerType layer, AuxOut* aux_out) {
1326
  // Theoretically, we could have 15 prefix code bits + 31 extra bits.
1327
19.9k
  return writer->WithMaxBits(
1328
19.9k
      46 * tokens.size() + 32 * 1024 * 4, layer, aux_out, [&] {
1329
19.9k
        size_t num_extra_bits =
1330
19.9k
            WriteTokens(tokens, codes, context_offset, writer);
1331
19.9k
        if (aux_out != nullptr) {
1332
0
          aux_out->layer(layer).extra_bits += num_extra_bits;
1333
0
        }
1334
19.9k
        return true;
1335
19.9k
      });
1336
19.9k
}
1337
1338
0
void SetANSFuzzerFriendly(bool ans_fuzzer_friendly) {
1339
#if JXL_IS_DEBUG_BUILD  // Guard against accidental / malicious changes.
1340
  ans_fuzzer_friendly_ = ans_fuzzer_friendly;
1341
#endif
1342
0
}
1343
1344
HistogramParams HistogramParams::ForModular(
1345
    const CompressParams& cparams,
1346
6.60k
    const std::vector<uint8_t>& extra_dc_precision, bool streaming_mode) {
1347
6.60k
  HistogramParams params;
1348
6.60k
  params.streaming_mode = streaming_mode;
1349
6.60k
  if (cparams.speed_tier > SpeedTier::kKitten) {
1350
6.60k
    params.clustering = HistogramParams::ClusteringType::kFast;
1351
6.60k
    params.ans_histogram_strategy =
1352
6.60k
        cparams.speed_tier > SpeedTier::kThunder
1353
6.60k
            ? HistogramParams::ANSHistogramStrategy::kFast
1354
6.60k
            : HistogramParams::ANSHistogramStrategy::kApproximate;
1355
6.60k
    params.lz77_method =
1356
6.60k
        cparams.modular_mode && cparams.speed_tier <= SpeedTier::kHare
1357
6.60k
            ? HistogramParams::LZ77Method::kRLE
1358
6.60k
            : HistogramParams::LZ77Method::kNone;
1359
    // Near-lossless DC, as well as modular mode, require choosing hybrid uint
1360
    // more carefully.
1361
6.60k
    if ((!extra_dc_precision.empty() && extra_dc_precision[0] != 0) ||
1362
4.07k
        (cparams.modular_mode && cparams.speed_tier < SpeedTier::kCheetah)) {
1363
4.07k
      params.uint_method = HistogramParams::HybridUintMethod::kFast;
1364
4.07k
    } else {
1365
2.52k
      params.uint_method = HistogramParams::HybridUintMethod::kNone;
1366
2.52k
    }
1367
6.60k
  } 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
6.60k
  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
6.60k
    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
6.60k
  return params;
1387
6.60k
}
1388
}  // namespace jxl