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