/src/libjxl/lib/jxl/enc_modular.cc
Line | Count | Source (jump to first uncovered line) |
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_modular.h" |
7 | | |
8 | | #include <jxl/cms_interface.h> |
9 | | #include <jxl/memory_manager.h> |
10 | | #include <jxl/types.h> |
11 | | |
12 | | #include <algorithm> |
13 | | #include <array> |
14 | | #include <cmath> |
15 | | #include <cstddef> |
16 | | #include <cstdint> |
17 | | #include <cstdlib> |
18 | | #include <cstring> |
19 | | #include <limits> |
20 | | #include <memory> |
21 | | #include <tuple> |
22 | | #include <utility> |
23 | | #include <vector> |
24 | | |
25 | | #include "lib/jxl/ac_strategy.h" |
26 | | #include "lib/jxl/base/bits.h" |
27 | | #include "lib/jxl/base/common.h" |
28 | | #include "lib/jxl/base/compiler_specific.h" |
29 | | #include "lib/jxl/base/data_parallel.h" |
30 | | #include "lib/jxl/base/printf_macros.h" |
31 | | #include "lib/jxl/base/rect.h" |
32 | | #include "lib/jxl/base/status.h" |
33 | | #include "lib/jxl/chroma_from_luma.h" |
34 | | #include "lib/jxl/common.h" |
35 | | #include "lib/jxl/compressed_dc.h" |
36 | | #include "lib/jxl/dec_ans.h" |
37 | | #include "lib/jxl/dec_modular.h" |
38 | | #include "lib/jxl/enc_ans.h" |
39 | | #include "lib/jxl/enc_ans_params.h" |
40 | | #include "lib/jxl/enc_aux_out.h" |
41 | | #include "lib/jxl/enc_bit_writer.h" |
42 | | #include "lib/jxl/enc_cache.h" |
43 | | #include "lib/jxl/enc_fields.h" |
44 | | #include "lib/jxl/enc_gaborish.h" |
45 | | #include "lib/jxl/enc_params.h" |
46 | | #include "lib/jxl/enc_patch_dictionary.h" |
47 | | #include "lib/jxl/enc_quant_weights.h" |
48 | | #include "lib/jxl/fields.h" |
49 | | #include "lib/jxl/frame_dimensions.h" |
50 | | #include "lib/jxl/frame_header.h" |
51 | | #include "lib/jxl/image.h" |
52 | | #include "lib/jxl/image_metadata.h" |
53 | | #include "lib/jxl/image_ops.h" |
54 | | #include "lib/jxl/modular/encoding/context_predict.h" |
55 | | #include "lib/jxl/modular/encoding/dec_ma.h" |
56 | | #include "lib/jxl/modular/encoding/enc_encoding.h" |
57 | | #include "lib/jxl/modular/encoding/enc_ma.h" |
58 | | #include "lib/jxl/modular/encoding/encoding.h" |
59 | | #include "lib/jxl/modular/encoding/ma_common.h" |
60 | | #include "lib/jxl/modular/modular_image.h" |
61 | | #include "lib/jxl/modular/options.h" |
62 | | #include "lib/jxl/modular/transform/enc_transform.h" |
63 | | #include "lib/jxl/modular/transform/transform.h" |
64 | | #include "lib/jxl/pack_signed.h" |
65 | | #include "lib/jxl/passes_state.h" |
66 | | #include "lib/jxl/quant_weights.h" |
67 | | #include "modular/options.h" |
68 | | |
69 | | namespace jxl { |
70 | | |
71 | | namespace { |
72 | | // constexpr bool kPrintTree = false; |
73 | | |
74 | | // Squeeze default quantization factors |
75 | | // these quantization factors are for -Q 50 (other qualities simply scale the |
76 | | // factors; things are rounded down and obviously cannot get below 1) |
77 | | const float squeeze_quality_factor = |
78 | | 0.35; // for easy tweaking of the quality range (decrease this number for |
79 | | // higher quality) |
80 | | const float squeeze_luma_factor = |
81 | | 1.1; // for easy tweaking of the balance between luma (or anything |
82 | | // non-chroma) and chroma (decrease this number for higher quality |
83 | | // luma) |
84 | | const float squeeze_quality_factor_xyb = 4.8f; |
85 | | const float squeeze_xyb_qtable[3][16] = { |
86 | | {163.84, 81.92, 40.96, 20.48, 10.24, 5.12, 2.56, 1.28, 0.64, 0.32, 0.16, |
87 | | 0.08, 0.04, 0.02, 0.01, 0.005}, // Y |
88 | | {1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5, 0.5, 0.5, 0.5, |
89 | | 0.5}, // X |
90 | | {2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5, 0.5, 0.5, |
91 | | 0.5}, // B-Y |
92 | | }; |
93 | | |
94 | | const float squeeze_luma_qtable[16] = {163.84, 81.92, 40.96, 20.48, 10.24, 5.12, |
95 | | 2.56, 1.28, 0.64, 0.32, 0.16, 0.08, |
96 | | 0.04, 0.02, 0.01, 0.005}; |
97 | | // for 8-bit input, the range of YCoCg chroma is -255..255 so basically this |
98 | | // does 4:2:0 subsampling (two most fine grained layers get quantized away) |
99 | | const float squeeze_chroma_qtable[16] = { |
100 | | 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 0.5, 0.5, 0.5, 0.5, 0.5}; |
101 | | |
102 | | // Merges the trees in `trees` using nodes that decide on stream_id, as defined |
103 | | // by `tree_splits`. |
104 | | Status MergeTrees(const std::vector<Tree>& trees, |
105 | | const std::vector<size_t>& tree_splits, size_t begin, |
106 | 683 | size_t end, Tree* tree) { |
107 | 683 | JXL_ENSURE(trees.size() + 1 == tree_splits.size()); |
108 | 683 | JXL_ENSURE(end > begin); |
109 | 683 | JXL_ENSURE(end <= trees.size()); |
110 | 683 | if (end == begin + 1) { |
111 | | // Insert the tree, adding the opportune offset to all child nodes. |
112 | | // This will make the leaf IDs wrong, but subsequent roundtripping will fix |
113 | | // them. |
114 | 483 | size_t sz = tree->size(); |
115 | 483 | tree->insert(tree->end(), trees[begin].begin(), trees[begin].end()); |
116 | 14.9k | for (size_t i = sz; i < tree->size(); i++) { |
117 | 14.4k | (*tree)[i].lchild += sz; |
118 | 14.4k | (*tree)[i].rchild += sz; |
119 | 14.4k | } |
120 | 483 | return true; |
121 | 483 | } |
122 | 200 | size_t mid = (begin + end) / 2; |
123 | 200 | size_t splitval = tree_splits[mid] - 1; |
124 | 200 | size_t cur = tree->size(); |
125 | 200 | tree->emplace_back(1 /*stream_id*/, splitval, 0, 0, Predictor::Zero, 0, 1); |
126 | 200 | (*tree)[cur].lchild = tree->size(); |
127 | 200 | JXL_RETURN_IF_ERROR(MergeTrees(trees, tree_splits, mid, end, tree)); |
128 | 200 | (*tree)[cur].rchild = tree->size(); |
129 | 200 | JXL_RETURN_IF_ERROR(MergeTrees(trees, tree_splits, begin, mid, tree)); |
130 | 200 | return true; |
131 | 200 | } |
132 | | |
133 | 291 | void QuantizeChannel(Channel& ch, const int q) { |
134 | 291 | if (q == 1) return; |
135 | 0 | for (size_t y = 0; y < ch.plane.ysize(); y++) { |
136 | 0 | pixel_type* row = ch.plane.Row(y); |
137 | 0 | for (size_t x = 0; x < ch.plane.xsize(); x++) { |
138 | 0 | if (row[x] < 0) { |
139 | 0 | row[x] = -((-row[x] + q / 2) / q) * q; |
140 | 0 | } else { |
141 | 0 | row[x] = ((row[x] + q / 2) / q) * q; |
142 | 0 | } |
143 | 0 | } |
144 | 0 | } |
145 | 0 | } |
146 | | |
147 | | // convert binary32 float that corresponds to custom [bits]-bit float (with |
148 | | // [exp_bits] exponent bits) to a [bits]-bit integer representation that should |
149 | | // fit in pixel_type |
150 | | Status float_to_int(const float* const row_in, pixel_type* const row_out, |
151 | | size_t xsize, unsigned int bits, unsigned int exp_bits, |
152 | 12.6k | bool fp, double dfactor) { |
153 | 12.6k | JXL_ENSURE(sizeof(pixel_type) * 8 >= bits); |
154 | 12.6k | if (!fp) { |
155 | 12.5k | if (bits > 22) { |
156 | 0 | for (size_t x = 0; x < xsize; ++x) { |
157 | 0 | row_out[x] = row_in[x] * dfactor + (row_in[x] < 0 ? -0.5 : 0.5); |
158 | 0 | } |
159 | 12.5k | } else { |
160 | 12.5k | float factor = dfactor; |
161 | 1.03M | for (size_t x = 0; x < xsize; ++x) { |
162 | 1.01M | row_out[x] = row_in[x] * factor + (row_in[x] < 0 ? -0.5f : 0.5f); |
163 | 1.01M | } |
164 | 12.5k | } |
165 | 12.5k | return true; |
166 | 12.5k | } |
167 | 96 | if (bits == 32 && fp) { |
168 | 96 | JXL_ENSURE(exp_bits == 8); |
169 | 96 | memcpy(static_cast<void*>(row_out), static_cast<const void*>(row_in), |
170 | 96 | 4 * xsize); |
171 | 96 | return true; |
172 | 96 | } |
173 | | |
174 | 0 | JXL_ENSURE(bits > 0); |
175 | 0 | int exp_bias = (1 << (exp_bits - 1)) - 1; |
176 | 0 | int max_exp = (1 << exp_bits) - 1; |
177 | 0 | uint32_t sign = (1u << (bits - 1)); |
178 | 0 | int mant_bits = bits - exp_bits - 1; |
179 | 0 | int mant_shift = 23 - mant_bits; |
180 | 0 | for (size_t x = 0; x < xsize; ++x) { |
181 | 0 | uint32_t f; |
182 | 0 | memcpy(&f, &row_in[x], 4); |
183 | 0 | int signbit = (f >> 31); |
184 | 0 | f &= 0x7fffffff; |
185 | 0 | if (f == 0) { |
186 | 0 | row_out[x] = (signbit ? sign : 0); |
187 | 0 | continue; |
188 | 0 | } |
189 | 0 | int exp = (f >> 23) - 127; |
190 | 0 | if (exp == 128) return JXL_FAILURE("Inf/NaN not allowed"); |
191 | 0 | int mantissa = (f & 0x007fffff); |
192 | | // broke up the binary32 into its parts, now reassemble into |
193 | | // arbitrary float |
194 | 0 | exp += exp_bias; |
195 | 0 | if (exp < 0) { // will become a subnormal number |
196 | | // add implicit leading 1 to mantissa |
197 | 0 | mantissa |= 0x00800000; |
198 | 0 | if (exp < -mant_bits) { |
199 | 0 | return JXL_FAILURE( |
200 | 0 | "Invalid float number: %g cannot be represented with %i " |
201 | 0 | "exp_bits and %i mant_bits (exp %i)", |
202 | 0 | row_in[x], exp_bits, mant_bits, exp); |
203 | 0 | } |
204 | 0 | mantissa >>= 1 - exp; |
205 | 0 | exp = 0; |
206 | 0 | } |
207 | | // exp should be representable in exp_bits, otherwise input was |
208 | | // invalid |
209 | 0 | if (exp > max_exp) return JXL_FAILURE("Invalid float exponent"); |
210 | 0 | if (mantissa & ((1 << mant_shift) - 1)) { |
211 | 0 | return JXL_FAILURE("%g is losing precision (mant: %x)", row_in[x], |
212 | 0 | mantissa); |
213 | 0 | } |
214 | 0 | mantissa >>= mant_shift; |
215 | 0 | f = (signbit ? sign : 0); |
216 | 0 | f |= (exp << mant_bits); |
217 | 0 | f |= mantissa; |
218 | 0 | row_out[x] = static_cast<pixel_type>(f); |
219 | 0 | } |
220 | 0 | return true; |
221 | 0 | } |
222 | | |
223 | 0 | float EstimateWPCost(const Image& img, size_t i) { |
224 | 0 | size_t extra_bits = 0; |
225 | 0 | float histo_cost = 0; |
226 | 0 | HybridUintConfig config; |
227 | 0 | int32_t cutoffs[] = {-500, -392, -255, -191, -127, -95, -63, -47, -31, |
228 | 0 | -23, -15, -11, -7, -4, -3, -1, 0, 1, |
229 | 0 | 3, 5, 7, 11, 15, 23, 31, 47, 63, |
230 | 0 | 95, 127, 191, 255, 392, 500}; |
231 | 0 | constexpr size_t nc = sizeof(cutoffs) / sizeof(*cutoffs) + 1; |
232 | 0 | Histogram histo[nc] = {}; |
233 | 0 | weighted::Header wp_header; |
234 | 0 | PredictorMode(i, &wp_header); |
235 | 0 | for (const Channel& ch : img.channel) { |
236 | 0 | const intptr_t onerow = ch.plane.PixelsPerRow(); |
237 | 0 | weighted::State wp_state(wp_header, ch.w, ch.h); |
238 | 0 | Properties properties(1); |
239 | 0 | for (size_t y = 0; y < ch.h; y++) { |
240 | 0 | const pixel_type* JXL_RESTRICT r = ch.Row(y); |
241 | 0 | for (size_t x = 0; x < ch.w; x++) { |
242 | 0 | size_t offset = 0; |
243 | 0 | pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0); |
244 | 0 | pixel_type_w top = (y ? *(r + x - onerow) : left); |
245 | 0 | pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left); |
246 | 0 | pixel_type_w topright = |
247 | 0 | (x + 1 < ch.w && y ? *(r + x + 1 - onerow) : top); |
248 | 0 | pixel_type_w toptop = (y > 1 ? *(r + x - onerow - onerow) : top); |
249 | 0 | pixel_type guess = wp_state.Predict</*compute_properties=*/true>( |
250 | 0 | x, y, ch.w, top, left, topright, topleft, toptop, &properties, |
251 | 0 | offset); |
252 | 0 | size_t ctx = 0; |
253 | 0 | for (int c : cutoffs) { |
254 | 0 | ctx += (c >= properties[0]) ? 1 : 0; |
255 | 0 | } |
256 | 0 | pixel_type res = r[x] - guess; |
257 | 0 | uint32_t token; |
258 | 0 | uint32_t nbits; |
259 | 0 | uint32_t bits; |
260 | 0 | config.Encode(PackSigned(res), &token, &nbits, &bits); |
261 | 0 | histo[ctx].Add(token); |
262 | 0 | extra_bits += nbits; |
263 | 0 | wp_state.UpdateErrors(r[x], x, y, ch.w); |
264 | 0 | } |
265 | 0 | } |
266 | 0 | for (auto& h : histo) { |
267 | 0 | histo_cost += h.ShannonEntropy(); |
268 | 0 | h.Clear(); |
269 | 0 | } |
270 | 0 | } |
271 | 0 | return histo_cost + extra_bits; |
272 | 0 | } |
273 | | |
274 | 14 | float EstimateCost(const Image& img) { |
275 | | // TODO(veluca): consider SIMDfication of this code. |
276 | 14 | size_t extra_bits = 0; |
277 | 14 | float histo_cost = 0; |
278 | 14 | HybridUintConfig config; |
279 | 14 | uint32_t cutoffs[] = {0, 1, 3, 5, 7, 11, 15, 23, 31, |
280 | 14 | 47, 63, 95, 127, 191, 255, 392, 500}; |
281 | 14 | constexpr size_t nc = sizeof(cutoffs) / sizeof(*cutoffs) + 1; |
282 | 14 | Histogram histo[nc] = {}; |
283 | 14 | for (const Channel& ch : img.channel) { |
284 | 14 | const intptr_t onerow = ch.plane.PixelsPerRow(); |
285 | 370 | for (size_t y = 0; y < ch.h; y++) { |
286 | 356 | const pixel_type* JXL_RESTRICT r = ch.Row(y); |
287 | 19.2k | for (size_t x = 0; x < ch.w; x++) { |
288 | 18.8k | pixel_type_w left = (x ? r[x - 1] : y ? *(r + x - onerow) : 0); |
289 | 18.8k | pixel_type_w top = (y ? *(r + x - onerow) : left); |
290 | 18.8k | pixel_type_w topleft = (x && y ? *(r + x - 1 - onerow) : left); |
291 | 18.8k | size_t max_diff = |
292 | 18.8k | std::max({left, top, topleft}) - std::min({left, top, topleft}); |
293 | 18.8k | size_t ctx = 0; |
294 | 320k | for (uint32_t c : cutoffs) { |
295 | 320k | ctx += (c > max_diff) ? 1 : 0; |
296 | 320k | } |
297 | 18.8k | pixel_type res = r[x] - ClampedGradient(top, left, topleft); |
298 | 18.8k | uint32_t token; |
299 | 18.8k | uint32_t nbits; |
300 | 18.8k | uint32_t bits; |
301 | 18.8k | config.Encode(PackSigned(res), &token, &nbits, &bits); |
302 | 18.8k | histo[ctx].Add(token); |
303 | 18.8k | extra_bits += nbits; |
304 | 18.8k | } |
305 | 356 | } |
306 | 252 | for (auto& h : histo) { |
307 | 252 | histo_cost += h.ShannonEntropy(); |
308 | 252 | h.Clear(); |
309 | 252 | } |
310 | 14 | } |
311 | 14 | return histo_cost + extra_bits; |
312 | 14 | } |
313 | | |
314 | | bool do_transform(Image& image, const Transform& tr, |
315 | | const weighted::Header& wp_header, |
316 | 14 | jxl::ThreadPool* pool = nullptr, bool force_jxlart = false) { |
317 | 14 | Transform t = tr; |
318 | 14 | bool did_it = true; |
319 | 14 | if (force_jxlart) { |
320 | 0 | if (!t.MetaApply(image)) return false; |
321 | 14 | } else { |
322 | 14 | did_it = TransformForward(t, image, wp_header, pool); |
323 | 14 | } |
324 | 14 | if (did_it) image.transform.push_back(t); |
325 | 14 | return did_it; |
326 | 14 | } |
327 | | |
328 | | bool maybe_do_transform(Image& image, const Transform& tr, |
329 | | const CompressParams& cparams, |
330 | | const weighted::Header& wp_header, float cost_before, |
331 | | jxl::ThreadPool* pool = nullptr, |
332 | 14 | bool force_jxlart = false) { |
333 | 14 | if (force_jxlart || cparams.speed_tier >= SpeedTier::kSquirrel) { |
334 | 14 | return do_transform(image, tr, wp_header, pool, force_jxlart); |
335 | 14 | } |
336 | 0 | bool did_it = do_transform(image, tr, wp_header, pool); |
337 | 0 | if (did_it) { |
338 | 0 | float cost_after = EstimateCost(image); |
339 | 0 | JXL_DEBUG_V(7, "Cost before: %f cost after: %f", cost_before, cost_after); |
340 | 0 | if (cost_after > cost_before) { |
341 | 0 | Transform t = image.transform.back(); |
342 | 0 | JXL_RETURN_IF_ERROR(t.Inverse(image, wp_header, pool)); |
343 | 0 | image.transform.pop_back(); |
344 | 0 | did_it = false; |
345 | 0 | } |
346 | 0 | } |
347 | 0 | return did_it; |
348 | 0 | } |
349 | | |
350 | | void try_palettes(Image& gi, int& max_bitdepth, int& maxval, |
351 | | const CompressParams& cparams_, float channel_colors_percent, |
352 | 111 | jxl::ThreadPool* pool = nullptr) { |
353 | 111 | float cost_before = 0.f; |
354 | 111 | size_t did_palette = 0; |
355 | 111 | float nb_pixels = gi.channel[0].w * gi.channel[0].h; |
356 | 111 | int nb_chans = gi.channel.size() - gi.nb_meta_channels; |
357 | | // arbitrary estimate: 4.8 bpp for 8-bit RGB |
358 | 111 | float arbitrary_bpp_estimate = 0.2f * gi.bitdepth * nb_chans; |
359 | | |
360 | 111 | if (cparams_.palette_colors != 0 || cparams_.lossy_palette) { |
361 | | // when not estimating, assume some arbitrary bpp |
362 | 14 | cost_before = cparams_.speed_tier <= SpeedTier::kSquirrel |
363 | 14 | ? EstimateCost(gi) |
364 | 14 | : nb_pixels * arbitrary_bpp_estimate; |
365 | | // all-channel palette (e.g. RGBA) |
366 | 14 | if (nb_chans > 1) { |
367 | 0 | Transform maybe_palette(TransformId::kPalette); |
368 | 0 | maybe_palette.begin_c = gi.nb_meta_channels; |
369 | 0 | maybe_palette.num_c = nb_chans; |
370 | | // Heuristic choice of max colors for a palette: |
371 | | // max_colors = nb_pixels * estimated_bpp_without_palette * 0.0005 + |
372 | | // + nb_pixels / 128 + 128 |
373 | | // (estimated_bpp_without_palette = cost_before / nb_pixels) |
374 | | // Rationale: small image with large palette is not effective; |
375 | | // also if the entropy (estimated bpp) is low (e.g. mostly solid/gradient |
376 | | // areas), palette is less useful and may even be counterproductive. |
377 | 0 | maybe_palette.nb_colors = std::min( |
378 | 0 | static_cast<int>(cost_before * 0.0005f + nb_pixels / 128 + 128), |
379 | 0 | std::abs(cparams_.palette_colors)); |
380 | 0 | maybe_palette.ordered_palette = cparams_.palette_colors >= 0; |
381 | 0 | maybe_palette.lossy_palette = |
382 | 0 | (cparams_.lossy_palette && maybe_palette.num_c == 3); |
383 | 0 | if (maybe_palette.lossy_palette) { |
384 | 0 | maybe_palette.predictor = Predictor::Average4; |
385 | 0 | } |
386 | | // TODO(veluca): use a custom weighted header if using the weighted |
387 | | // predictor. |
388 | 0 | if (maybe_do_transform(gi, maybe_palette, cparams_, weighted::Header(), |
389 | 0 | cost_before, pool, cparams_.options.zero_tokens)) { |
390 | 0 | did_palette = 1; |
391 | 0 | }; |
392 | 0 | } |
393 | | // all-minus-one-channel palette (RGB with separate alpha, or CMY with |
394 | | // separate K) |
395 | 14 | if (!did_palette && nb_chans > 3) { |
396 | 0 | Transform maybe_palette_3(TransformId::kPalette); |
397 | 0 | maybe_palette_3.begin_c = gi.nb_meta_channels; |
398 | 0 | maybe_palette_3.num_c = nb_chans - 1; |
399 | 0 | maybe_palette_3.nb_colors = std::min( |
400 | 0 | static_cast<int>(cost_before * 0.0005f + nb_pixels / 128 + 128), |
401 | 0 | std::abs(cparams_.palette_colors)); |
402 | 0 | maybe_palette_3.ordered_palette = cparams_.palette_colors >= 0; |
403 | 0 | maybe_palette_3.lossy_palette = cparams_.lossy_palette; |
404 | 0 | if (maybe_palette_3.lossy_palette) { |
405 | 0 | maybe_palette_3.predictor = Predictor::Average4; |
406 | 0 | } |
407 | 0 | if (maybe_do_transform(gi, maybe_palette_3, cparams_, weighted::Header(), |
408 | 0 | cost_before, pool, cparams_.options.zero_tokens)) { |
409 | 0 | did_palette = 1; |
410 | 0 | } |
411 | 0 | } |
412 | 14 | } |
413 | | |
414 | 111 | if (channel_colors_percent > 0) { |
415 | | // single channel palette (like FLIF's ChannelCompact) |
416 | 14 | size_t nb_channels = gi.channel.size() - gi.nb_meta_channels - did_palette; |
417 | 14 | int orig_bitdepth = max_bitdepth; |
418 | 14 | max_bitdepth = 0; |
419 | 14 | if (nb_channels > 0 && (did_palette || cost_before == 0)) { |
420 | 3 | cost_before = |
421 | 3 | cparams_.speed_tier < SpeedTier::kSquirrel ? EstimateCost(gi) : 0; |
422 | 3 | } |
423 | 28 | for (size_t i = did_palette; i < nb_channels + did_palette; i++) { |
424 | 14 | int32_t min; |
425 | 14 | int32_t max; |
426 | 14 | compute_minmax(gi.channel[gi.nb_meta_channels + i], &min, &max); |
427 | 14 | int64_t colors = static_cast<int64_t>(max) - min + 1; |
428 | 14 | JXL_DEBUG_V(10, "Channel %" PRIuS ": range=%i..%i", i, min, max); |
429 | 14 | Transform maybe_palette_1(TransformId::kPalette); |
430 | 14 | maybe_palette_1.begin_c = i + gi.nb_meta_channels; |
431 | 14 | maybe_palette_1.num_c = 1; |
432 | | // simple heuristic: if less than X percent of the values in the range |
433 | | // actually occur, it is probably worth it to do a compaction |
434 | | // (but only if the channel palette is less than 6% the size of the |
435 | | // image itself) |
436 | 14 | maybe_palette_1.nb_colors = |
437 | 14 | std::min(static_cast<int>(nb_pixels / 16), |
438 | 14 | static_cast<int>(channel_colors_percent / 100. * colors)); |
439 | 14 | if (maybe_do_transform(gi, maybe_palette_1, cparams_, weighted::Header(), |
440 | 14 | cost_before, pool)) { |
441 | | // effective bit depth is lower, adjust quantization accordingly |
442 | 1 | compute_minmax(gi.channel[gi.nb_meta_channels + i], &min, &max); |
443 | 1 | if (max < maxval) maxval = max; |
444 | 1 | int ch_bitdepth = |
445 | 1 | (max > 0 ? CeilLog2Nonzero(static_cast<uint32_t>(max)) : 0); |
446 | 1 | if (ch_bitdepth > max_bitdepth) max_bitdepth = ch_bitdepth; |
447 | 13 | } else { |
448 | 13 | max_bitdepth = orig_bitdepth; |
449 | 13 | } |
450 | 14 | } |
451 | 14 | } |
452 | 111 | } |
453 | | |
454 | | } // namespace |
455 | | |
456 | | StatusOr<std::unique_ptr<ModularFrameEncoder>> ModularFrameEncoder::Create( |
457 | | JxlMemoryManager* memory_manager, const FrameHeader& frame_header, |
458 | 283 | const CompressParams& cparams_orig, bool streaming_mode) { |
459 | 283 | auto self = std::unique_ptr<ModularFrameEncoder>( |
460 | 283 | new ModularFrameEncoder(memory_manager)); |
461 | 283 | JXL_RETURN_IF_ERROR(self->Init(frame_header, cparams_orig, streaming_mode)); |
462 | 283 | return self; |
463 | 283 | } |
464 | | |
465 | | ModularFrameEncoder::ModularFrameEncoder(JxlMemoryManager* memory_manager) |
466 | 283 | : memory_manager_(memory_manager) {} |
467 | | |
468 | | Status ModularFrameEncoder::Init(const FrameHeader& frame_header, |
469 | | const CompressParams& cparams_orig, |
470 | 283 | bool streaming_mode) { |
471 | 283 | frame_dim_ = frame_header.ToFrameDimensions(); |
472 | 283 | cparams_ = cparams_orig; |
473 | | |
474 | 283 | size_t num_streams = |
475 | 283 | ModularStreamId::Num(frame_dim_, frame_header.passes.num_passes); |
476 | | |
477 | | // Progressive lossless only benefits from levels 2 and higher |
478 | | // Lower levels of faster decoding can outperform higher tiers |
479 | | // depending on the PC |
480 | 283 | if (cparams_.responsive == 1 && cparams_.IsLossless() && |
481 | 283 | cparams_.decoding_speed_tier == 1) { |
482 | 0 | cparams_.decoding_speed_tier = 2; |
483 | 0 | } |
484 | 283 | if (cparams_.responsive == 1 && cparams_.IsLossless()) { |
485 | | // RCT selection seems bugged with Squeeze, YCoCg works well. |
486 | 0 | if (cparams_.colorspace < 0) { |
487 | 0 | cparams_.colorspace = 6; |
488 | 0 | } |
489 | 0 | } |
490 | | |
491 | 283 | if (cparams_.ModularPartIsLossless()) { |
492 | 186 | switch (cparams_.decoding_speed_tier) { |
493 | 186 | case 0: |
494 | 186 | cparams_.options.fast_decode_multiplier = 1.001f; |
495 | 186 | break; |
496 | 0 | case 1: // No Weighted predictor |
497 | 0 | cparams_.options.fast_decode_multiplier = 1.005f; |
498 | 0 | cparams_.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP; |
499 | 0 | break; |
500 | 0 | case 2: { // No Weighted predictor and Group size 0 defined in |
501 | | // enc_frame.cc |
502 | 0 | cparams_.options.fast_decode_multiplier = 1.015f; |
503 | 0 | cparams_.options.wp_tree_mode = ModularOptions::TreeMode::kNoWP; |
504 | 0 | break; |
505 | 0 | } |
506 | 0 | case 3: { // Gradient only, Group size 0, and Fast MA tree |
507 | 0 | cparams_.options.wp_tree_mode = ModularOptions::TreeMode::kGradientOnly; |
508 | 0 | cparams_.options.predictor = Predictor::Gradient; |
509 | 0 | break; |
510 | 0 | } |
511 | 0 | default: { // Gradient only, Group size 0, and No MA tree |
512 | 0 | cparams_.options.wp_tree_mode = ModularOptions::TreeMode::kGradientOnly; |
513 | 0 | cparams_.options.predictor = Predictor::Gradient; |
514 | 0 | cparams_.options.nb_repeats = 0; |
515 | | // Disabling MA Trees sometimes doesn't increase decode speed |
516 | | // depending on PC |
517 | 0 | break; |
518 | 0 | } |
519 | 186 | } |
520 | 186 | } |
521 | | |
522 | 6.91k | for (size_t i = 0; i < num_streams; ++i) { |
523 | 6.63k | stream_images_.emplace_back(memory_manager_); |
524 | 6.63k | } |
525 | | |
526 | | // use a sensible default if nothing explicit is specified: |
527 | | // Squeeze for lossy, no squeeze for lossless |
528 | 283 | if (cparams_.responsive < 0) { |
529 | 186 | if (cparams_.ModularPartIsLossless()) { |
530 | 186 | cparams_.responsive = 0; |
531 | 186 | } else { |
532 | 0 | cparams_.responsive = 1; |
533 | 0 | } |
534 | 186 | } |
535 | | |
536 | 283 | cparams_.options.splitting_heuristics_node_threshold = |
537 | 283 | 75 + 14 * static_cast<int>(cparams_.speed_tier) + |
538 | 283 | 10 * cparams_.decoding_speed_tier; |
539 | | |
540 | 283 | { |
541 | | // Set properties. |
542 | 283 | std::vector<uint32_t> prop_order; |
543 | 283 | if (cparams_.responsive) { |
544 | | // Properties in order of their likelihood of being useful for Squeeze |
545 | | // residuals. |
546 | 0 | prop_order = {0, 1, 4, 5, 6, 7, 8, 15, 9, 10, 11, 12, 13, 14, 2, 3}; |
547 | 283 | } else { |
548 | | // Same, but for the non-Squeeze case. |
549 | 283 | prop_order = {0, 1, 15, 9, 10, 11, 12, 13, 14, 2, 3, 4, 5, 6, 7, 8}; |
550 | | // if few groups, don't use group as a property |
551 | 283 | if (num_streams < 30 && cparams_.speed_tier > SpeedTier::kTortoise && |
552 | 283 | cparams_orig.ModularPartIsLossless()) { |
553 | 185 | prop_order.erase(prop_order.begin() + 1); |
554 | 185 | } |
555 | 283 | } |
556 | 283 | int max_properties = std::min<int>( |
557 | 283 | cparams_.options.max_properties, |
558 | 283 | static_cast<int>( |
559 | 283 | frame_header.nonserialized_metadata->m.num_extra_channels) + |
560 | 283 | (frame_header.encoding == FrameEncoding::kModular ? 2 : -1)); |
561 | 283 | switch (cparams_.speed_tier) { |
562 | 0 | case SpeedTier::kHare: |
563 | 0 | cparams_.options.splitting_heuristics_properties.assign( |
564 | 0 | prop_order.begin(), prop_order.begin() + 4); |
565 | 0 | cparams_.options.max_property_values = 24; |
566 | 0 | break; |
567 | 0 | case SpeedTier::kWombat: |
568 | 0 | cparams_.options.splitting_heuristics_properties.assign( |
569 | 0 | prop_order.begin(), prop_order.begin() + 5); |
570 | 0 | cparams_.options.max_property_values = 32; |
571 | 0 | break; |
572 | 283 | case SpeedTier::kSquirrel: |
573 | 283 | cparams_.options.splitting_heuristics_properties.assign( |
574 | 283 | prop_order.begin(), prop_order.begin() + 7); |
575 | 283 | cparams_.options.max_property_values = 48; |
576 | 283 | break; |
577 | 0 | case SpeedTier::kKitten: |
578 | 0 | cparams_.options.splitting_heuristics_properties.assign( |
579 | 0 | prop_order.begin(), prop_order.begin() + 10); |
580 | 0 | cparams_.options.max_property_values = 96; |
581 | 0 | break; |
582 | 0 | case SpeedTier::kGlacier: |
583 | 0 | case SpeedTier::kTortoise: |
584 | 0 | cparams_.options.splitting_heuristics_properties = prop_order; |
585 | 0 | cparams_.options.max_property_values = 256; |
586 | 0 | break; |
587 | 0 | default: |
588 | 0 | cparams_.options.splitting_heuristics_properties.assign( |
589 | 0 | prop_order.begin(), prop_order.begin() + 3); |
590 | 0 | cparams_.options.max_property_values = 16; |
591 | 0 | break; |
592 | 283 | } |
593 | 283 | if (cparams_.speed_tier > SpeedTier::kTortoise) { |
594 | | // Gradient in previous channels. |
595 | 283 | for (int i = 0; i < max_properties; i++) { |
596 | 0 | cparams_.options.splitting_heuristics_properties.push_back( |
597 | 0 | kNumNonrefProperties + i * 4 + 3); |
598 | 0 | } |
599 | 283 | } else { |
600 | | // All the extra properties in Tortoise mode. |
601 | 0 | for (int i = 0; i < max_properties * 4; i++) { |
602 | 0 | cparams_.options.splitting_heuristics_properties.push_back( |
603 | 0 | kNumNonrefProperties + i); |
604 | 0 | } |
605 | 0 | } |
606 | 283 | } |
607 | | |
608 | 283 | if ((cparams_.options.predictor == Predictor::Average0 || |
609 | 283 | cparams_.options.predictor == Predictor::Average1 || |
610 | 283 | cparams_.options.predictor == Predictor::Average2 || |
611 | 283 | cparams_.options.predictor == Predictor::Average3 || |
612 | 283 | cparams_.options.predictor == Predictor::Average4 || |
613 | 283 | cparams_.options.predictor == Predictor::Weighted) && |
614 | 283 | !cparams_.ModularPartIsLossless()) { |
615 | | // Lossy + Average/Weighted predictors does not work, so switch to default |
616 | | // predictors. |
617 | 0 | cparams_.options.predictor = kUndefinedPredictor; |
618 | 0 | } |
619 | | |
620 | 283 | if (cparams_.options.predictor == kUndefinedPredictor) { |
621 | | // no explicit predictor(s) given, set a good default |
622 | 186 | if ((cparams_.speed_tier <= SpeedTier::kGlacier || |
623 | 186 | cparams_.modular_mode == false) && |
624 | 186 | cparams_.IsLossless() && cparams_.responsive == JXL_FALSE) { |
625 | | // TODO(veluca): allow all predictors that don't break residual |
626 | | // multipliers in lossy mode. |
627 | 0 | cparams_.options.predictor = Predictor::Variable; |
628 | 186 | } else if (cparams_.responsive || cparams_.lossy_palette) { |
629 | | // zero predictor for Squeeze residues and lossy palette indices |
630 | | // TODO: Try adding 'Squeezed' predictor set, with the most |
631 | | // common predictors used by Variable in squeezed images, including none. |
632 | 0 | cparams_.options.predictor = Predictor::Zero; |
633 | 186 | } else if (!cparams_.IsLossless()) { |
634 | | // If not responsive and lossy. TODO(veluca): use near_lossless instead? |
635 | 186 | cparams_.options.predictor = Predictor::Gradient; |
636 | 186 | } else if (cparams_.speed_tier < SpeedTier::kFalcon) { |
637 | | // try median and weighted predictor for anything else |
638 | 0 | cparams_.options.predictor = Predictor::Best; |
639 | 0 | } else if (cparams_.speed_tier == SpeedTier::kFalcon) { |
640 | | // just weighted predictor in falcon mode |
641 | 0 | cparams_.options.predictor = Predictor::Weighted; |
642 | 0 | } else if (cparams_.speed_tier > SpeedTier::kFalcon) { |
643 | | // just gradient predictor in thunder mode |
644 | 0 | cparams_.options.predictor = Predictor::Gradient; |
645 | 0 | } |
646 | 186 | } else { |
647 | 97 | if (cparams_.lossy_palette) cparams_.options.predictor = Predictor::Zero; |
648 | 97 | } |
649 | 283 | if (!cparams_.ModularPartIsLossless()) { |
650 | 97 | if (cparams_.options.predictor == Predictor::Weighted || |
651 | 97 | cparams_.options.predictor == Predictor::Variable || |
652 | 97 | cparams_.options.predictor == Predictor::Best) |
653 | 0 | cparams_.options.predictor = Predictor::Zero; |
654 | 97 | } |
655 | 283 | tree_splits_.push_back(0); |
656 | 283 | if (cparams_.modular_mode == false) { |
657 | 186 | JXL_ASSIGN_OR_RETURN(ModularStreamId qt0, ModularStreamId::QuantTable(0)); |
658 | 186 | cparams_.options.fast_decode_multiplier = 1.0f; |
659 | 186 | tree_splits_.push_back(ModularStreamId::VarDCTDC(0).ID(frame_dim_)); |
660 | 186 | tree_splits_.push_back(ModularStreamId::ModularDC(0).ID(frame_dim_)); |
661 | 186 | tree_splits_.push_back(ModularStreamId::ACMetadata(0).ID(frame_dim_)); |
662 | 186 | tree_splits_.push_back(qt0.ID(frame_dim_)); |
663 | 186 | tree_splits_.push_back(ModularStreamId::ModularAC(0, 0).ID(frame_dim_)); |
664 | 186 | ac_metadata_size.resize(frame_dim_.num_dc_groups); |
665 | 186 | extra_dc_precision.resize(frame_dim_.num_dc_groups); |
666 | 186 | } |
667 | 283 | tree_splits_.push_back(num_streams); |
668 | 283 | cparams_.options.max_chan_size = frame_dim_.group_dim; |
669 | 283 | cparams_.options.group_dim = frame_dim_.group_dim; |
670 | | |
671 | | // TODO(veluca): figure out how to use different predictor sets per channel. |
672 | 283 | stream_options_.resize(num_streams, cparams_.options); |
673 | | |
674 | 283 | stream_options_[0] = cparams_.options; |
675 | 283 | if (cparams_.speed_tier == SpeedTier::kFalcon) { |
676 | 0 | stream_options_[0].tree_kind = ModularOptions::TreeKind::kWPFixedDC; |
677 | 283 | } else if (cparams_.speed_tier == SpeedTier::kThunder) { |
678 | 0 | stream_options_[0].tree_kind = ModularOptions::TreeKind::kGradientFixedDC; |
679 | 0 | } |
680 | 283 | stream_options_[0].histogram_params = |
681 | 283 | HistogramParams::ForModular(cparams_, {}, streaming_mode); |
682 | 283 | return true; |
683 | 283 | } |
684 | | |
685 | | Status ModularFrameEncoder::ComputeEncodingData( |
686 | | const FrameHeader& frame_header, const ImageMetadata& metadata, |
687 | | Image3F* JXL_RESTRICT color, const std::vector<ImageF>& extra_channels, |
688 | | const Rect& group_rect, const FrameDimensions& patch_dim, |
689 | | const Rect& frame_area_rect, PassesEncoderState* JXL_RESTRICT enc_state, |
690 | | const JxlCmsInterface& cms, ThreadPool* pool, AuxOut* aux_out, |
691 | 111 | bool do_color) { |
692 | 111 | JxlMemoryManager* memory_manager = enc_state->memory_manager(); |
693 | 111 | JXL_DEBUG_V(6, "Computing modular encoding data for frame %s", |
694 | 111 | frame_header.DebugString().c_str()); |
695 | | |
696 | 111 | bool groupwise = enc_state->streaming_mode; |
697 | | |
698 | 111 | if (do_color && frame_header.loop_filter.gab && !groupwise) { |
699 | 0 | float w = 0.9908511000000001f; |
700 | 0 | float weights[3] = {w, w, w}; |
701 | 0 | JXL_RETURN_IF_ERROR(GaborishInverse(color, Rect(*color), weights, pool)); |
702 | 0 | } |
703 | | |
704 | 111 | if (do_color && metadata.bit_depth.bits_per_sample <= 16 && |
705 | 111 | cparams_.speed_tier < SpeedTier::kCheetah && |
706 | 111 | cparams_.decoding_speed_tier < 2 && !groupwise) { |
707 | 97 | JXL_RETURN_IF_ERROR(FindBestPatchDictionary( |
708 | 97 | *color, enc_state, cms, nullptr, aux_out, |
709 | 97 | cparams_.color_transform == ColorTransform::kXYB)); |
710 | 97 | JXL_RETURN_IF_ERROR(PatchDictionaryEncoder::SubtractFrom( |
711 | 97 | enc_state->shared.image_features.patches, color)); |
712 | 97 | } |
713 | | |
714 | 111 | if (cparams_.custom_splines.HasAny()) { |
715 | 0 | PassesSharedState& shared = enc_state->shared; |
716 | 0 | ImageFeatures& image_features = shared.image_features; |
717 | 0 | image_features.splines = cparams_.custom_splines; |
718 | 0 | } |
719 | | |
720 | | // Convert ImageBundle to modular Image object |
721 | 111 | const size_t xsize = patch_dim.xsize; |
722 | 111 | const size_t ysize = patch_dim.ysize; |
723 | | |
724 | 111 | int nb_chans = 3; |
725 | 111 | if (metadata.color_encoding.IsGray() && |
726 | 111 | cparams_.color_transform == ColorTransform::kNone) { |
727 | 0 | nb_chans = 1; |
728 | 0 | } |
729 | 111 | if (!do_color) nb_chans = 0; |
730 | | |
731 | 111 | nb_chans += extra_channels.size(); |
732 | | |
733 | 111 | bool fp = metadata.bit_depth.floating_point_sample && |
734 | 111 | cparams_.color_transform != ColorTransform::kXYB; |
735 | | |
736 | | // bits_per_sample is just metadata for XYB images. |
737 | 111 | if (metadata.bit_depth.bits_per_sample >= 32 && do_color && |
738 | 111 | cparams_.color_transform != ColorTransform::kXYB) { |
739 | 0 | if (metadata.bit_depth.bits_per_sample == 32 && fp == false) { |
740 | 0 | return JXL_FAILURE("uint32_t not supported in enc_modular"); |
741 | 0 | } else if (metadata.bit_depth.bits_per_sample > 32) { |
742 | 0 | return JXL_FAILURE("bits_per_sample > 32 not supported"); |
743 | 0 | } |
744 | 0 | } |
745 | | |
746 | | // in the non-float case, there is an implicit 0 sign bit |
747 | 111 | int max_bitdepth = |
748 | 111 | do_color ? metadata.bit_depth.bits_per_sample + (fp ? 0 : 1) : 0; |
749 | 111 | Image& gi = stream_images_[0]; |
750 | 111 | JXL_ASSIGN_OR_RETURN( |
751 | 111 | gi, Image::Create(memory_manager, xsize, ysize, |
752 | 111 | metadata.bit_depth.bits_per_sample, nb_chans)); |
753 | 111 | int c = 0; |
754 | 111 | if (cparams_.color_transform == ColorTransform::kXYB && |
755 | 111 | cparams_.modular_mode == true) { |
756 | 97 | float enc_factors[3] = {65536.0f, 4096.0f, 4096.0f}; |
757 | 97 | if (cparams_.butteraugli_distance > 0 && !cparams_.responsive) { |
758 | | // quantize XYB here and then treat it as a lossless image |
759 | 97 | enc_factors[0] *= 1.f / (1.f + 23.f * cparams_.butteraugli_distance); |
760 | 97 | enc_factors[1] *= 1.f / (1.f + 14.f * cparams_.butteraugli_distance); |
761 | 97 | enc_factors[2] *= 1.f / (1.f + 14.f * cparams_.butteraugli_distance); |
762 | 97 | cparams_.butteraugli_distance = 0; |
763 | 97 | } |
764 | 97 | if (cparams_.manual_xyb_factors.size() == 3) { |
765 | 0 | JXL_RETURN_IF_ERROR(DequantMatricesSetCustomDC( |
766 | 0 | memory_manager, &enc_state->shared.matrices, |
767 | 0 | cparams_.manual_xyb_factors.data())); |
768 | | // TODO(jon): update max_bitdepth in this case |
769 | 97 | } else { |
770 | 97 | JXL_RETURN_IF_ERROR(DequantMatricesSetCustomDC( |
771 | 97 | memory_manager, &enc_state->shared.matrices, enc_factors)); |
772 | 97 | max_bitdepth = 12; |
773 | 97 | } |
774 | 97 | } |
775 | 111 | pixel_type maxval = gi.bitdepth < 32 ? (1u << gi.bitdepth) - 1 : 0; |
776 | 111 | if (do_color) { |
777 | 388 | for (; c < 3; c++) { |
778 | 291 | if (metadata.color_encoding.IsGray() && |
779 | 291 | cparams_.color_transform == ColorTransform::kNone && |
780 | 291 | c != (cparams_.color_transform == ColorTransform::kXYB ? 1 : 0)) |
781 | 0 | continue; |
782 | 291 | int c_out = c; |
783 | | // XYB is encoded as YX(B-Y) |
784 | 291 | if (cparams_.color_transform == ColorTransform::kXYB && c < 2) |
785 | 194 | c_out = 1 - c_out; |
786 | 291 | double factor = maxval; |
787 | 291 | if (cparams_.color_transform == ColorTransform::kXYB) |
788 | 291 | factor = enc_state->shared.matrices.InvDCQuant(c); |
789 | 291 | if (c == 2 && cparams_.color_transform == ColorTransform::kXYB) { |
790 | 97 | JXL_ENSURE(!fp); |
791 | 6.26k | for (size_t y = 0; y < ysize; ++y) { |
792 | 6.16k | const float* const JXL_RESTRICT row_in = color->PlaneRow(c, y); |
793 | 6.16k | pixel_type* const JXL_RESTRICT row_out = gi.channel[c_out].Row(y); |
794 | 6.16k | pixel_type* const JXL_RESTRICT row_Y = gi.channel[0].Row(y); |
795 | 512k | for (size_t x = 0; x < xsize; ++x) { |
796 | | // TODO(eustas): check if std::roundf is appropriate |
797 | 506k | row_out[x] = row_in[x] * factor + 0.5f; |
798 | 506k | row_out[x] -= row_Y[x]; |
799 | 506k | } |
800 | 6.16k | } |
801 | 194 | } else { |
802 | 194 | int bits = metadata.bit_depth.bits_per_sample; |
803 | 194 | int exp_bits = metadata.bit_depth.exponent_bits_per_sample; |
804 | 194 | gi.channel[c_out].hshift = frame_header.chroma_subsampling.HShift(c); |
805 | 194 | gi.channel[c_out].vshift = frame_header.chroma_subsampling.VShift(c); |
806 | 194 | size_t xsize_shifted = DivCeil(xsize, 1 << gi.channel[c_out].hshift); |
807 | 194 | size_t ysize_shifted = DivCeil(ysize, 1 << gi.channel[c_out].vshift); |
808 | 194 | JXL_RETURN_IF_ERROR( |
809 | 194 | gi.channel[c_out].shrink(xsize_shifted, ysize_shifted)); |
810 | 194 | const auto process_row = [&](const int task, |
811 | 12.3k | const int thread) -> Status { |
812 | 12.3k | const size_t y = task; |
813 | 12.3k | const float* const JXL_RESTRICT row_in = |
814 | 12.3k | color->PlaneRow(c, y + group_rect.y0()) + group_rect.x0(); |
815 | 12.3k | pixel_type* const JXL_RESTRICT row_out = gi.channel[c_out].Row(y); |
816 | 12.3k | JXL_RETURN_IF_ERROR(float_to_int(row_in, row_out, xsize_shifted, bits, |
817 | 12.3k | exp_bits, fp, factor)); |
818 | 12.3k | return true; |
819 | 12.3k | }; |
820 | 194 | JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted, |
821 | 194 | ThreadPool::NoInit, process_row, |
822 | 194 | "float2int")); |
823 | 194 | } |
824 | 291 | } |
825 | 97 | if (metadata.color_encoding.IsGray() && |
826 | 97 | cparams_.color_transform == ColorTransform::kNone) |
827 | 0 | c = 1; |
828 | 97 | } |
829 | | |
830 | 125 | for (size_t ec = 0; ec < extra_channels.size(); ec++, c++) { |
831 | 14 | const ExtraChannelInfo& eci = metadata.extra_channel_info[ec]; |
832 | 14 | size_t ecups = frame_header.extra_channel_upsampling[ec]; |
833 | 14 | JXL_RETURN_IF_ERROR( |
834 | 14 | gi.channel[c].shrink(DivCeil(patch_dim.xsize_upsampled, ecups), |
835 | 14 | DivCeil(patch_dim.ysize_upsampled, ecups))); |
836 | 14 | gi.channel[c].hshift = gi.channel[c].vshift = |
837 | 14 | CeilLog2Nonzero(ecups) - CeilLog2Nonzero(frame_header.upsampling); |
838 | | |
839 | 14 | int bits = eci.bit_depth.bits_per_sample; |
840 | 14 | int exp_bits = eci.bit_depth.exponent_bits_per_sample; |
841 | 14 | bool ec_fp = eci.bit_depth.floating_point_sample; |
842 | 14 | double factor = (ec_fp ? 1 : ((1u << eci.bit_depth.bits_per_sample) - 1)); |
843 | 14 | if (bits + (ec_fp ? 0 : 1) > max_bitdepth) { |
844 | 14 | max_bitdepth = bits + (ec_fp ? 0 : 1); |
845 | 14 | } |
846 | 356 | const auto process_row = [&](const int task, const int thread) -> Status { |
847 | 356 | const size_t y = task; |
848 | 356 | const float* const JXL_RESTRICT row_in = |
849 | 356 | extra_channels[ec].Row(y + group_rect.y0()) + group_rect.x0(); |
850 | 356 | pixel_type* const JXL_RESTRICT row_out = gi.channel[c].Row(y); |
851 | 356 | JXL_RETURN_IF_ERROR(float_to_int(row_in, row_out, |
852 | 356 | gi.channel[c].plane.xsize(), bits, |
853 | 356 | exp_bits, ec_fp, factor)); |
854 | 356 | return true; |
855 | 356 | }; |
856 | 14 | JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, gi.channel[c].plane.ysize(), |
857 | 14 | ThreadPool::NoInit, process_row, |
858 | 14 | "float2int")); |
859 | 14 | } |
860 | 111 | JXL_ENSURE(c == nb_chans); |
861 | | |
862 | 111 | int level_max_bitdepth = (cparams_.level == 5 ? 16 : 32); |
863 | 111 | if (max_bitdepth > level_max_bitdepth) { |
864 | 0 | return JXL_FAILURE( |
865 | 0 | "Bitdepth too high for level %i (need %i bits, have only %i in this " |
866 | 0 | "level)", |
867 | 0 | cparams_.level, max_bitdepth, level_max_bitdepth); |
868 | 0 | } |
869 | | |
870 | | // Set options and apply transformations |
871 | 111 | if (!cparams_.ModularPartIsLossless()) { |
872 | 97 | if (cparams_.palette_colors != 0) { |
873 | 97 | JXL_DEBUG_V(3, "Lossy encode, not doing palette transforms"); |
874 | 97 | } |
875 | 97 | if (cparams_.color_transform == ColorTransform::kXYB) { |
876 | 97 | cparams_.channel_colors_pre_transform_percent = 0; |
877 | 97 | } |
878 | 97 | cparams_.channel_colors_percent = 0; |
879 | 97 | cparams_.palette_colors = 0; |
880 | 97 | cparams_.lossy_palette = false; |
881 | 97 | } |
882 | | |
883 | | // Global palette transforms |
884 | 111 | float channel_colors_percent = 0; |
885 | 111 | if (!cparams_.lossy_palette && |
886 | 111 | (cparams_.speed_tier <= SpeedTier::kThunder || |
887 | 111 | (do_color && metadata.bit_depth.bits_per_sample > 8))) { |
888 | 111 | channel_colors_percent = cparams_.channel_colors_pre_transform_percent; |
889 | 111 | } |
890 | 111 | if (!groupwise) { |
891 | 111 | try_palettes(gi, max_bitdepth, maxval, cparams_, channel_colors_percent, |
892 | 111 | pool); |
893 | 111 | } |
894 | | |
895 | | // don't do an RCT if we're short on bits |
896 | 111 | if (cparams_.color_transform == ColorTransform::kNone && do_color && |
897 | 111 | gi.channel.size() - gi.nb_meta_channels >= 3 && |
898 | 111 | max_bitdepth + 1 < level_max_bitdepth) { |
899 | 0 | if (cparams_.colorspace < 0 && (!cparams_.ModularPartIsLossless() || |
900 | 0 | cparams_.speed_tier > SpeedTier::kHare)) { |
901 | 0 | Transform ycocg{TransformId::kRCT}; |
902 | 0 | ycocg.rct_type = 6; |
903 | 0 | ycocg.begin_c = gi.nb_meta_channels; |
904 | 0 | do_transform(gi, ycocg, weighted::Header(), pool); |
905 | 0 | max_bitdepth++; |
906 | 0 | } else if (cparams_.colorspace > 0) { |
907 | 0 | Transform sg(TransformId::kRCT); |
908 | 0 | sg.begin_c = gi.nb_meta_channels; |
909 | 0 | sg.rct_type = cparams_.colorspace; |
910 | 0 | do_transform(gi, sg, weighted::Header(), pool); |
911 | 0 | max_bitdepth++; |
912 | 0 | } |
913 | 0 | } |
914 | | |
915 | 111 | if (cparams_.move_to_front_from_channel > 0) { |
916 | 0 | for (size_t tgt = 0; |
917 | 0 | tgt + cparams_.move_to_front_from_channel < gi.channel.size(); tgt++) { |
918 | 0 | size_t pos = cparams_.move_to_front_from_channel; |
919 | 0 | while (pos > 0) { |
920 | 0 | Transform move(TransformId::kRCT); |
921 | 0 | if (pos == 1) { |
922 | 0 | move.begin_c = tgt; |
923 | 0 | move.rct_type = 28; // RGB -> GRB |
924 | 0 | pos -= 1; |
925 | 0 | } else { |
926 | 0 | move.begin_c = tgt + pos - 2; |
927 | 0 | move.rct_type = 14; // RGB -> BRG |
928 | 0 | pos -= 2; |
929 | 0 | } |
930 | 0 | do_transform(gi, move, weighted::Header(), pool); |
931 | 0 | } |
932 | 0 | } |
933 | 0 | } |
934 | | |
935 | | // don't do squeeze if we don't have some spare bits |
936 | 111 | if (!groupwise && cparams_.responsive && !gi.channel.empty() && |
937 | 111 | max_bitdepth + 2 < level_max_bitdepth) { |
938 | 0 | Transform t(TransformId::kSqueeze); |
939 | 0 | do_transform(gi, t, weighted::Header(), pool); |
940 | 0 | max_bitdepth += 2; |
941 | 0 | } |
942 | | |
943 | 111 | if (max_bitdepth + 1 > level_max_bitdepth) { |
944 | | // force no group RCTs if we don't have a spare bit |
945 | 4 | cparams_.colorspace = 0; |
946 | 4 | } |
947 | 111 | JXL_ENSURE(max_bitdepth <= level_max_bitdepth); |
948 | | |
949 | 111 | if (!cparams_.ModularPartIsLossless()) { |
950 | 97 | quants_.resize(gi.channel.size(), 1); |
951 | 97 | float quantizer = 0.25f; |
952 | 97 | if (!cparams_.responsive) { |
953 | 97 | JXL_DEBUG_V(1, |
954 | 97 | "Warning: lossy compression without Squeeze " |
955 | 97 | "transform is just color quantization."); |
956 | 97 | quantizer *= 0.1f; |
957 | 97 | } |
958 | 97 | float bitdepth_correction = 1.f; |
959 | 97 | if (cparams_.color_transform != ColorTransform::kXYB) { |
960 | 0 | bitdepth_correction = maxval / 255.f; |
961 | 0 | } |
962 | 97 | std::vector<float> quantizers; |
963 | 388 | for (size_t i = 0; i < 3; i++) { |
964 | 291 | float dist = cparams_.butteraugli_distance; |
965 | 291 | quantizers.push_back(quantizer * dist * bitdepth_correction); |
966 | 291 | } |
967 | 97 | for (size_t i = 0; i < extra_channels.size(); i++) { |
968 | 0 | int ec_bitdepth = |
969 | 0 | metadata.extra_channel_info[i].bit_depth.bits_per_sample; |
970 | 0 | pixel_type ec_maxval = ec_bitdepth < 32 ? (1u << ec_bitdepth) - 1 : 0; |
971 | 0 | bitdepth_correction = ec_maxval / 255.f; |
972 | 0 | float dist = 0; |
973 | 0 | if (i < cparams_.ec_distance.size()) dist = cparams_.ec_distance[i]; |
974 | 0 | if (dist < 0) dist = cparams_.butteraugli_distance; |
975 | 0 | quantizers.push_back(quantizer * dist * bitdepth_correction); |
976 | 0 | } |
977 | 97 | if (cparams_.options.nb_repeats == 0) { |
978 | 0 | return JXL_FAILURE("nb_repeats = 0 not supported with modular lossy!"); |
979 | 0 | } |
980 | 388 | for (uint32_t i = gi.nb_meta_channels; i < gi.channel.size(); i++) { |
981 | 291 | Channel& ch = gi.channel[i]; |
982 | 291 | int shift = ch.hshift + ch.vshift; // number of pixel halvings |
983 | 291 | if (shift > 16) shift = 16; |
984 | 291 | if (shift > 0) shift--; |
985 | 291 | int q; |
986 | | // assuming default Squeeze here |
987 | 291 | int component = |
988 | 291 | (do_color ? 0 : 3) + ((i - gi.nb_meta_channels) % nb_chans); |
989 | | // last 4 channels are final chroma residuals |
990 | 291 | if (nb_chans > 2 && i >= gi.channel.size() - 4 && cparams_.responsive) { |
991 | 0 | component = 1; |
992 | 0 | } |
993 | 291 | if (cparams_.color_transform == ColorTransform::kXYB && component < 3) { |
994 | 291 | q = quantizers[component] * squeeze_quality_factor_xyb * |
995 | 291 | squeeze_xyb_qtable[component][shift]; |
996 | 291 | } else { |
997 | 0 | if (cparams_.colorspace != 0 && component > 0 && component < 3) { |
998 | 0 | q = quantizers[component] * squeeze_quality_factor * |
999 | 0 | squeeze_chroma_qtable[shift]; |
1000 | 0 | } else { |
1001 | 0 | q = quantizers[component] * squeeze_quality_factor * |
1002 | 0 | squeeze_luma_factor * squeeze_luma_qtable[shift]; |
1003 | 0 | } |
1004 | 0 | } |
1005 | 291 | if (q < 1) q = 1; |
1006 | 291 | QuantizeChannel(gi.channel[i], q); |
1007 | 291 | quants_[i] = q; |
1008 | 291 | } |
1009 | 97 | } |
1010 | | |
1011 | | // Fill other groups. |
1012 | | // DC |
1013 | 222 | for (size_t group_id = 0; group_id < patch_dim.num_dc_groups; group_id++) { |
1014 | 111 | const size_t rgx = group_id % patch_dim.xsize_dc_groups; |
1015 | 111 | const size_t rgy = group_id / patch_dim.xsize_dc_groups; |
1016 | 111 | const Rect rect(rgx * patch_dim.dc_group_dim, rgy * patch_dim.dc_group_dim, |
1017 | 111 | patch_dim.dc_group_dim, patch_dim.dc_group_dim); |
1018 | 111 | size_t gx = rgx + frame_area_rect.x0() / 2048; |
1019 | 111 | size_t gy = rgy + frame_area_rect.y0() / 2048; |
1020 | 111 | size_t real_group_id = gy * frame_dim_.xsize_dc_groups + gx; |
1021 | | // minShift==3 because (frame_dim.dc_group_dim >> 3) == frame_dim.group_dim |
1022 | | // maxShift==1000 is infinity |
1023 | 111 | stream_params_.push_back( |
1024 | 111 | GroupParams{rect, 3, 1000, ModularStreamId::ModularDC(real_group_id)}); |
1025 | 111 | } |
1026 | | // AC global -> nothing. |
1027 | | // AC |
1028 | 222 | for (size_t group_id = 0; group_id < patch_dim.num_groups; group_id++) { |
1029 | 111 | const size_t rgx = group_id % patch_dim.xsize_groups; |
1030 | 111 | const size_t rgy = group_id / patch_dim.xsize_groups; |
1031 | 111 | const Rect mrect(rgx * patch_dim.group_dim, rgy * patch_dim.group_dim, |
1032 | 111 | patch_dim.group_dim, patch_dim.group_dim); |
1033 | 111 | size_t gx = rgx + frame_area_rect.x0() / (frame_dim_.group_dim); |
1034 | 111 | size_t gy = rgy + frame_area_rect.y0() / (frame_dim_.group_dim); |
1035 | 111 | size_t real_group_id = gy * frame_dim_.xsize_groups + gx; |
1036 | 222 | for (size_t i = 0; i < enc_state->progressive_splitter.GetNumPasses(); |
1037 | 111 | i++) { |
1038 | 111 | int maxShift; |
1039 | 111 | int minShift; |
1040 | 111 | frame_header.passes.GetDownsamplingBracket(i, minShift, maxShift); |
1041 | 111 | stream_params_.push_back( |
1042 | 111 | GroupParams{mrect, minShift, maxShift, |
1043 | 111 | ModularStreamId::ModularAC(real_group_id, i)}); |
1044 | 111 | } |
1045 | 111 | } |
1046 | | // if there's only one group, everything ends up in GlobalModular |
1047 | | // in that case, also try RCTs/WP params for the one group |
1048 | 111 | if (stream_params_.size() == 2) { |
1049 | 111 | stream_params_.push_back(GroupParams{Rect(0, 0, xsize, ysize), 0, 1000, |
1050 | 111 | ModularStreamId::Global()}); |
1051 | 111 | } |
1052 | 111 | gi_channel_.resize(stream_images_.size()); |
1053 | | |
1054 | 111 | const auto process_row = [&](const uint32_t i, |
1055 | 333 | size_t /* thread */) -> Status { |
1056 | 333 | size_t stream = stream_params_[i].id.ID(frame_dim_); |
1057 | 333 | if (stream != 0) { |
1058 | 222 | stream_options_[stream] = stream_options_[0]; |
1059 | 222 | } |
1060 | 333 | JXL_RETURN_IF_ERROR(PrepareStreamParams( |
1061 | 333 | stream_params_[i].rect, cparams_, stream_params_[i].minShift, |
1062 | 333 | stream_params_[i].maxShift, stream_params_[i].id, do_color, groupwise)); |
1063 | 333 | return true; |
1064 | 333 | }; |
1065 | 111 | JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, stream_params_.size(), |
1066 | 111 | ThreadPool::NoInit, process_row, |
1067 | 111 | "ChooseParams")); |
1068 | 111 | { |
1069 | | // Clear out channels that have been copied to groups. |
1070 | 111 | Image& full_image = stream_images_[0]; |
1071 | 111 | size_t ch = full_image.nb_meta_channels; |
1072 | 416 | for (; ch < full_image.channel.size(); ch++) { |
1073 | 305 | Channel& fc = full_image.channel[ch]; |
1074 | 305 | if (fc.w > frame_dim_.group_dim || fc.h > frame_dim_.group_dim) break; |
1075 | 305 | } |
1076 | 111 | for (; ch < full_image.channel.size(); ch++) { |
1077 | | // TODO(eustas): shrink / assign channel to keep size consistency |
1078 | 0 | full_image.channel[ch].plane = ImageI(); |
1079 | 0 | } |
1080 | 111 | } |
1081 | | |
1082 | 111 | JXL_RETURN_IF_ERROR(ValidateChannelDimensions(gi, stream_options_[0])); |
1083 | 111 | return true; |
1084 | 111 | } |
1085 | | |
1086 | 283 | Status ModularFrameEncoder::ComputeTree(ThreadPool* pool) { |
1087 | 283 | std::vector<ModularMultiplierInfo> multiplier_info; |
1088 | 283 | if (!quants_.empty()) { |
1089 | 2.23k | for (uint32_t stream_id = 0; stream_id < stream_images_.size(); |
1090 | 2.13k | stream_id++) { |
1091 | | // skip non-modular stream_ids |
1092 | 2.13k | if (stream_id > 0 && gi_channel_[stream_id].empty()) continue; |
1093 | 97 | const Image& image = stream_images_[stream_id]; |
1094 | 97 | const ModularOptions& options = stream_options_[stream_id]; |
1095 | 388 | for (uint32_t i = image.nb_meta_channels; i < image.channel.size(); i++) { |
1096 | 291 | if (image.channel[i].w > options.max_chan_size || |
1097 | 291 | image.channel[i].h > options.max_chan_size) { |
1098 | 0 | continue; |
1099 | 0 | } |
1100 | 291 | if (stream_id > 0 && gi_channel_[stream_id].empty()) continue; |
1101 | 291 | size_t ch_id = stream_id == 0 |
1102 | 291 | ? i |
1103 | 291 | : gi_channel_[stream_id][i - image.nb_meta_channels]; |
1104 | 291 | uint32_t q = quants_[ch_id]; |
1105 | | // Inform the tree splitting heuristics that each channel in each group |
1106 | | // used this quantization factor. This will produce a tree with the |
1107 | | // given multipliers. |
1108 | 291 | if (multiplier_info.empty() || |
1109 | 291 | multiplier_info.back().range[1][0] != stream_id || |
1110 | 291 | multiplier_info.back().multiplier != q) { |
1111 | 97 | StaticPropRange range; |
1112 | 97 | range[0] = {{i, i + 1}}; |
1113 | 97 | range[1] = {{stream_id, stream_id + 1}}; |
1114 | 97 | multiplier_info.push_back({range, q}); |
1115 | 194 | } else { |
1116 | | // Previous channel in the same group had the same quantization |
1117 | | // factor. Don't provide two different ranges, as that creates |
1118 | | // unnecessary nodes. |
1119 | 194 | multiplier_info.back().range[0][1] = i + 1; |
1120 | 194 | } |
1121 | 291 | } |
1122 | 97 | } |
1123 | | // Merge group+channel settings that have the same channels and quantization |
1124 | | // factors, to avoid unnecessary nodes. |
1125 | 97 | std::sort(multiplier_info.begin(), multiplier_info.end(), |
1126 | 97 | [](ModularMultiplierInfo a, ModularMultiplierInfo b) { |
1127 | 0 | return std::make_tuple(a.range, a.multiplier) < |
1128 | 0 | std::make_tuple(b.range, b.multiplier); |
1129 | 0 | }); |
1130 | 97 | size_t new_num = 1; |
1131 | 97 | for (size_t i = 1; i < multiplier_info.size(); i++) { |
1132 | 0 | ModularMultiplierInfo& prev = multiplier_info[new_num - 1]; |
1133 | 0 | ModularMultiplierInfo& cur = multiplier_info[i]; |
1134 | 0 | if (prev.range[0] == cur.range[0] && prev.multiplier == cur.multiplier && |
1135 | 0 | prev.range[1][1] == cur.range[1][0]) { |
1136 | 0 | prev.range[1][1] = cur.range[1][1]; |
1137 | 0 | } else { |
1138 | 0 | multiplier_info[new_num++] = multiplier_info[i]; |
1139 | 0 | } |
1140 | 0 | } |
1141 | 97 | multiplier_info.resize(new_num); |
1142 | 97 | } |
1143 | | |
1144 | 283 | if (!cparams_.custom_fixed_tree.empty()) { |
1145 | 0 | tree_ = cparams_.custom_fixed_tree; |
1146 | 283 | } else if (cparams_.speed_tier < SpeedTier::kFalcon || |
1147 | 283 | !cparams_.modular_mode) { |
1148 | | // Avoid creating a tree with leaves that don't correspond to any pixels. |
1149 | 283 | std::vector<size_t> useful_splits; |
1150 | 283 | useful_splits.reserve(tree_splits_.size()); |
1151 | 1.49k | for (size_t chunk = 0; chunk < tree_splits_.size() - 1; chunk++) { |
1152 | 1.21k | bool has_pixels = false; |
1153 | 1.21k | size_t start = tree_splits_[chunk]; |
1154 | 1.21k | size_t stop = tree_splits_[chunk + 1]; |
1155 | 7.84k | for (size_t i = start; i < stop; i++) { |
1156 | 6.63k | if (!stream_images_[i].empty()) has_pixels = true; |
1157 | 6.63k | } |
1158 | 1.21k | if (has_pixels) { |
1159 | 483 | useful_splits.push_back(tree_splits_[chunk]); |
1160 | 483 | } |
1161 | 1.21k | } |
1162 | | // Don't do anything if modular mode does not have any pixels in this image |
1163 | 283 | if (useful_splits.empty()) return true; |
1164 | 283 | useful_splits.push_back(tree_splits_.back()); |
1165 | | |
1166 | 283 | std::vector<Tree> trees(useful_splits.size() - 1); |
1167 | 283 | const auto process_chunk = [&](const uint32_t chunk, |
1168 | 483 | size_t /* thread */) -> Status { |
1169 | | // TODO(veluca): parallelize more. |
1170 | 483 | uint32_t start = useful_splits[chunk]; |
1171 | 483 | uint32_t stop = useful_splits[chunk + 1]; |
1172 | 483 | while (start < stop && stream_images_[start].empty()) ++start; |
1173 | 6.46k | while (start < stop && stream_images_[stop - 1].empty()) --stop; |
1174 | | |
1175 | 483 | if (stream_options_[start].tree_kind == |
1176 | 483 | ModularOptions::TreeKind::kLearn) { |
1177 | 111 | JXL_ASSIGN_OR_RETURN( |
1178 | 111 | trees[chunk], |
1179 | 111 | LearnTree(stream_images_.data(), stream_options_.data(), start, |
1180 | 111 | stop, multiplier_info)); |
1181 | 372 | } else { |
1182 | 372 | size_t total_pixels = 0; |
1183 | 744 | for (size_t i = start; i < stop; i++) { |
1184 | 1.30k | for (const Channel& ch : stream_images_[i].channel) { |
1185 | 1.30k | total_pixels += ch.w * ch.h; |
1186 | 1.30k | } |
1187 | 372 | } |
1188 | 372 | total_pixels = std::max<size_t>(total_pixels, 1); |
1189 | | |
1190 | 372 | trees[chunk] = PredefinedTree(stream_options_[start].tree_kind, |
1191 | 372 | total_pixels, 8, 0); |
1192 | 372 | } |
1193 | 483 | return true; |
1194 | 483 | }; |
1195 | 283 | JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, useful_splits.size() - 1, |
1196 | 283 | ThreadPool::NoInit, process_chunk, |
1197 | 283 | "LearnTrees")); |
1198 | 283 | tree_.clear(); |
1199 | 283 | JXL_RETURN_IF_ERROR( |
1200 | 283 | MergeTrees(trees, useful_splits, 0, useful_splits.size() - 1, &tree_)); |
1201 | 283 | } else { |
1202 | | // Fixed tree. |
1203 | 0 | size_t total_pixels = 0; |
1204 | 0 | int max_bitdepth = 0; |
1205 | 0 | for (const Image& img : stream_images_) { |
1206 | 0 | max_bitdepth = std::max(max_bitdepth, img.bitdepth); |
1207 | 0 | for (const Channel& ch : img.channel) { |
1208 | 0 | total_pixels += ch.w * ch.h; |
1209 | 0 | } |
1210 | 0 | } |
1211 | 0 | if (cparams_.speed_tier <= SpeedTier::kFalcon) { |
1212 | 0 | tree_ = PredefinedTree(ModularOptions::TreeKind::kWPFixedDC, total_pixels, |
1213 | 0 | max_bitdepth, stream_options_[0].max_properties); |
1214 | 0 | } else if (cparams_.speed_tier <= SpeedTier::kThunder) { |
1215 | 0 | tree_ = PredefinedTree(ModularOptions::TreeKind::kGradientFixedDC, |
1216 | 0 | total_pixels, max_bitdepth, |
1217 | 0 | stream_options_[0].max_properties); |
1218 | 0 | } else { |
1219 | 0 | tree_ = {PropertyDecisionNode::Leaf(Predictor::Gradient)}; |
1220 | 0 | } |
1221 | 0 | } |
1222 | 283 | tree_tokens_.resize(1); |
1223 | 283 | tree_tokens_[0].clear(); |
1224 | 283 | Tree decoded_tree; |
1225 | 283 | JXL_RETURN_IF_ERROR(TokenizeTree(tree_, tree_tokens_.data(), &decoded_tree)); |
1226 | 283 | JXL_ENSURE(tree_.size() == decoded_tree.size()); |
1227 | 283 | tree_ = std::move(decoded_tree); |
1228 | | |
1229 | | /* TODO(szabadka) Add text output callback to cparams |
1230 | | if (kPrintTree && WantDebugOutput(aux_out)) { |
1231 | | if (frame_header.dc_level > 0) { |
1232 | | PrintTree(tree_, aux_out->debug_prefix + "/dc_frame_level" + |
1233 | | std::to_string(frame_header.dc_level) + "_tree"); |
1234 | | } else { |
1235 | | PrintTree(tree_, aux_out->debug_prefix + "/global_tree"); |
1236 | | } |
1237 | | } */ |
1238 | 283 | return true; |
1239 | 283 | } |
1240 | | |
1241 | 283 | Status ModularFrameEncoder::ComputeTokens(ThreadPool* pool) { |
1242 | 283 | size_t num_streams = stream_images_.size(); |
1243 | 283 | stream_headers_.resize(num_streams); |
1244 | 283 | tokens_.resize(num_streams); |
1245 | 283 | image_widths_.resize(num_streams); |
1246 | 283 | const auto process_stream = [&](const uint32_t stream_id, |
1247 | 6.63k | size_t /* thread */) -> Status { |
1248 | 6.63k | tokens_[stream_id].clear(); |
1249 | 6.63k | JXL_RETURN_IF_ERROR( |
1250 | 6.63k | ModularCompress(stream_images_[stream_id], stream_options_[stream_id], |
1251 | 6.63k | stream_id, tree_, stream_headers_[stream_id], |
1252 | 6.63k | tokens_[stream_id], &image_widths_[stream_id])); |
1253 | 6.63k | return true; |
1254 | 6.63k | }; |
1255 | 283 | JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, num_streams, ThreadPool::NoInit, |
1256 | 283 | process_stream, "ComputeTokens")); |
1257 | 283 | return true; |
1258 | 283 | } |
1259 | | |
1260 | | Status ModularFrameEncoder::EncodeGlobalInfo(bool streaming_mode, |
1261 | | BitWriter* writer, |
1262 | 283 | AuxOut* aux_out) { |
1263 | 283 | JxlMemoryManager* memory_manager = writer->memory_manager(); |
1264 | 283 | bool skip_rest = false; |
1265 | 283 | JXL_RETURN_IF_ERROR( |
1266 | 283 | writer->WithMaxBits(1, LayerType::ModularTree, aux_out, [&] { |
1267 | | // If we are using brotli, or not using modular mode. |
1268 | 283 | if (tree_tokens_.empty() || tree_tokens_[0].empty()) { |
1269 | 283 | writer->Write(1, 0); |
1270 | 283 | skip_rest = true; |
1271 | 283 | } else { |
1272 | 283 | writer->Write(1, 1); |
1273 | 283 | } |
1274 | 283 | return true; |
1275 | 283 | })); |
1276 | 283 | if (skip_rest) return true; |
1277 | | |
1278 | | // Write tree |
1279 | 283 | HistogramParams params = |
1280 | 283 | HistogramParams::ForModular(cparams_, extra_dc_precision, streaming_mode); |
1281 | 283 | { |
1282 | 283 | EntropyEncodingData tree_code; |
1283 | 283 | JXL_ASSIGN_OR_RETURN( |
1284 | 283 | size_t cost, BuildAndEncodeHistograms( |
1285 | 283 | memory_manager, params, kNumTreeContexts, tree_tokens_, |
1286 | 283 | &tree_code, writer, LayerType::ModularTree, aux_out)); |
1287 | 283 | (void)cost; |
1288 | 283 | JXL_RETURN_IF_ERROR(WriteTokens(tree_tokens_[0], tree_code, 0, writer, |
1289 | 283 | LayerType::ModularTree, aux_out)); |
1290 | 283 | } |
1291 | 283 | params.streaming_mode = streaming_mode; |
1292 | 283 | params.add_missing_symbols = streaming_mode; |
1293 | 283 | params.image_widths = image_widths_; |
1294 | | // Write histograms. |
1295 | 283 | JXL_ASSIGN_OR_RETURN( |
1296 | 283 | size_t cost, BuildAndEncodeHistograms( |
1297 | 283 | memory_manager, params, (tree_.size() + 1) / 2, tokens_, |
1298 | 283 | &code_, writer, LayerType::ModularGlobal, aux_out)); |
1299 | 283 | (void)cost; |
1300 | 283 | return true; |
1301 | 283 | } |
1302 | | |
1303 | | Status ModularFrameEncoder::EncodeStream(BitWriter* writer, AuxOut* aux_out, |
1304 | | LayerType layer, |
1305 | 1.63k | const ModularStreamId& stream) { |
1306 | 1.63k | size_t stream_id = stream.ID(frame_dim_); |
1307 | 1.63k | if (stream_images_[stream_id].channel.empty()) { |
1308 | 1.14k | JXL_DEBUG_V(10, "Modular stream %" PRIuS " is empty.", stream_id); |
1309 | 1.14k | return true; // Image with no channels, header never gets decoded. |
1310 | 1.14k | } |
1311 | 483 | if (tokens_.empty()) { |
1312 | 0 | JXL_RETURN_IF_ERROR(ModularGenericCompress( |
1313 | 0 | stream_images_[stream_id], stream_options_[stream_id], *writer, aux_out, |
1314 | 0 | layer, stream_id)); |
1315 | 483 | } else { |
1316 | 483 | JXL_RETURN_IF_ERROR( |
1317 | 483 | Bundle::Write(stream_headers_[stream_id], writer, layer, aux_out)); |
1318 | 483 | JXL_RETURN_IF_ERROR( |
1319 | 483 | WriteTokens(tokens_[stream_id], code_, 0, writer, layer, aux_out)); |
1320 | 483 | } |
1321 | 483 | return true; |
1322 | 483 | } |
1323 | | |
1324 | 0 | void ModularFrameEncoder::ClearStreamData(const ModularStreamId& stream) { |
1325 | 0 | size_t stream_id = stream.ID(frame_dim_); |
1326 | 0 | Image empty_image(stream_images_[stream_id].memory_manager()); |
1327 | 0 | std::swap(stream_images_[stream_id], empty_image); |
1328 | 0 | } |
1329 | | |
1330 | 0 | void ModularFrameEncoder::ClearModularStreamData() { |
1331 | 0 | for (const auto& group : stream_params_) { |
1332 | 0 | ClearStreamData(group.id); |
1333 | 0 | } |
1334 | 0 | stream_params_.clear(); |
1335 | 0 | } |
1336 | | |
1337 | | size_t ModularFrameEncoder::ComputeStreamingAbsoluteAcGroupId( |
1338 | | size_t dc_group_id, size_t ac_group_id, |
1339 | 0 | const FrameDimensions& patch_dim) const { |
1340 | 0 | size_t dc_group_x = dc_group_id % frame_dim_.xsize_dc_groups; |
1341 | 0 | size_t dc_group_y = dc_group_id / frame_dim_.xsize_dc_groups; |
1342 | 0 | size_t ac_group_x = ac_group_id % patch_dim.xsize_groups; |
1343 | 0 | size_t ac_group_y = ac_group_id / patch_dim.xsize_groups; |
1344 | 0 | return (dc_group_x * 8 + ac_group_x) + |
1345 | 0 | (dc_group_y * 8 + ac_group_y) * frame_dim_.xsize_groups; |
1346 | 0 | } |
1347 | | |
1348 | | Status ModularFrameEncoder::PrepareStreamParams(const Rect& rect, |
1349 | | const CompressParams& cparams, |
1350 | | int minShift, int maxShift, |
1351 | | const ModularStreamId& stream, |
1352 | 333 | bool do_color, bool groupwise) { |
1353 | 333 | size_t stream_id = stream.ID(frame_dim_); |
1354 | 333 | if (stream_id == 0 && frame_dim_.num_groups != 1) { |
1355 | | // If we have multiple groups, then the stream with ID 0 holds the full |
1356 | | // image and we do not want to apply transforms or in general change the |
1357 | | // pixel values. |
1358 | 0 | return true; |
1359 | 0 | } |
1360 | 333 | Image& full_image = stream_images_[0]; |
1361 | 333 | JxlMemoryManager* memory_manager = full_image.memory_manager(); |
1362 | 333 | const size_t xsize = rect.xsize(); |
1363 | 333 | const size_t ysize = rect.ysize(); |
1364 | 333 | Image& gi = stream_images_[stream_id]; |
1365 | 333 | if (stream_id > 0) { |
1366 | 222 | JXL_ASSIGN_OR_RETURN(gi, Image::Create(memory_manager, xsize, ysize, |
1367 | 222 | full_image.bitdepth, 0)); |
1368 | | // start at the first bigger-than-frame_dim.group_dim non-metachannel |
1369 | 222 | size_t c = full_image.nb_meta_channels; |
1370 | 222 | if (!groupwise) { |
1371 | 832 | for (; c < full_image.channel.size(); c++) { |
1372 | 610 | Channel& fc = full_image.channel[c]; |
1373 | 610 | if (fc.w > frame_dim_.group_dim || fc.h > frame_dim_.group_dim) break; |
1374 | 610 | } |
1375 | 222 | } |
1376 | 222 | for (; c < full_image.channel.size(); c++) { |
1377 | 0 | Channel& fc = full_image.channel[c]; |
1378 | 0 | int shift = std::min(fc.hshift, fc.vshift); |
1379 | 0 | if (shift > maxShift) continue; |
1380 | 0 | if (shift < minShift) continue; |
1381 | 0 | Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift, |
1382 | 0 | rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h); |
1383 | 0 | if (r.xsize() == 0 || r.ysize() == 0) continue; |
1384 | 0 | gi_channel_[stream_id].push_back(c); |
1385 | 0 | JXL_ASSIGN_OR_RETURN( |
1386 | 0 | Channel gc, Channel::Create(memory_manager, r.xsize(), r.ysize())); |
1387 | 0 | gc.hshift = fc.hshift; |
1388 | 0 | gc.vshift = fc.vshift; |
1389 | 0 | for (size_t y = 0; y < r.ysize(); ++y) { |
1390 | 0 | memcpy(gc.Row(y), r.ConstRow(fc.plane, y), |
1391 | 0 | r.xsize() * sizeof(pixel_type)); |
1392 | 0 | } |
1393 | 0 | gi.channel.emplace_back(std::move(gc)); |
1394 | 0 | } |
1395 | | |
1396 | 222 | if (gi.channel.empty()) return true; |
1397 | | // Do some per-group transforms |
1398 | | |
1399 | | // Local palette transforms |
1400 | | // TODO(veluca): make this work with quantize-after-prediction in lossy |
1401 | | // mode. |
1402 | 0 | if (cparams.butteraugli_distance == 0.f && !cparams.lossy_palette && |
1403 | 0 | cparams.speed_tier < SpeedTier::kCheetah) { |
1404 | 0 | int max_bitdepth = 0, maxval = 0; // don't care about that here |
1405 | 0 | float channel_color_percent = 0; |
1406 | 0 | if (!(cparams.responsive && |
1407 | 0 | (cparams.decoding_speed_tier >= 1 || cparams.IsLossless()))) { |
1408 | 0 | channel_color_percent = cparams.channel_colors_percent; |
1409 | 0 | } |
1410 | 0 | try_palettes(gi, max_bitdepth, maxval, cparams, channel_color_percent); |
1411 | 0 | } |
1412 | 0 | } |
1413 | | |
1414 | | // lossless and no specific color transform specified: try Nothing, YCoCg, |
1415 | | // and 17 RCTs |
1416 | 111 | if (cparams.color_transform == ColorTransform::kNone && |
1417 | 111 | cparams.IsLossless() && cparams.colorspace < 0 && |
1418 | 111 | gi.channel.size() - gi.nb_meta_channels >= 3 && |
1419 | 111 | cparams.responsive == JXL_FALSE && do_color && |
1420 | 111 | cparams.speed_tier <= SpeedTier::kHare) { |
1421 | 0 | Transform sg(TransformId::kRCT); |
1422 | 0 | sg.begin_c = gi.nb_meta_channels; |
1423 | 0 | size_t nb_rcts_to_try = 0; |
1424 | 0 | switch (cparams.speed_tier) { |
1425 | 0 | case SpeedTier::kLightning: |
1426 | 0 | case SpeedTier::kThunder: |
1427 | 0 | case SpeedTier::kFalcon: |
1428 | 0 | case SpeedTier::kCheetah: |
1429 | 0 | nb_rcts_to_try = 0; // Just do global YCoCg |
1430 | 0 | break; |
1431 | 0 | case SpeedTier::kHare: |
1432 | 0 | nb_rcts_to_try = 4; |
1433 | 0 | break; |
1434 | 0 | case SpeedTier::kWombat: |
1435 | 0 | nb_rcts_to_try = 5; |
1436 | 0 | break; |
1437 | 0 | case SpeedTier::kSquirrel: |
1438 | 0 | nb_rcts_to_try = 7; |
1439 | 0 | break; |
1440 | 0 | case SpeedTier::kKitten: |
1441 | 0 | nb_rcts_to_try = 9; |
1442 | 0 | break; |
1443 | 0 | case SpeedTier::kTectonicPlate: |
1444 | 0 | case SpeedTier::kGlacier: |
1445 | 0 | case SpeedTier::kTortoise: |
1446 | 0 | nb_rcts_to_try = 19; |
1447 | 0 | break; |
1448 | 0 | } |
1449 | 0 | float best_cost = std::numeric_limits<float>::max(); |
1450 | 0 | size_t best_rct = 0; |
1451 | | // These should be 19 actually different transforms; the remaining ones |
1452 | | // are equivalent to one of these (note that the first two are do-nothing |
1453 | | // and YCoCg) modulo channel reordering (which only matters in the case of |
1454 | | // MA-with-prev-channels-properties) and/or sign (e.g. RmG vs GmR) |
1455 | 0 | for (int i : {0 * 7 + 0, 0 * 7 + 6, 0 * 7 + 5, 1 * 7 + 3, 3 * 7 + 5, |
1456 | 0 | 5 * 7 + 5, 1 * 7 + 5, 2 * 7 + 5, 1 * 7 + 1, 0 * 7 + 4, |
1457 | 0 | 1 * 7 + 2, 2 * 7 + 1, 2 * 7 + 2, 2 * 7 + 3, 4 * 7 + 4, |
1458 | 0 | 4 * 7 + 5, 0 * 7 + 2, 0 * 7 + 1, 0 * 7 + 3}) { |
1459 | 0 | if (nb_rcts_to_try == 0) break; |
1460 | 0 | sg.rct_type = i; |
1461 | 0 | nb_rcts_to_try--; |
1462 | 0 | if (do_transform(gi, sg, weighted::Header())) { |
1463 | 0 | float cost = EstimateCost(gi); |
1464 | 0 | if (cost < best_cost) { |
1465 | 0 | best_rct = i; |
1466 | 0 | best_cost = cost; |
1467 | 0 | } |
1468 | 0 | Transform t = gi.transform.back(); |
1469 | 0 | JXL_RETURN_IF_ERROR(t.Inverse(gi, weighted::Header(), nullptr)); |
1470 | 0 | gi.transform.pop_back(); |
1471 | 0 | } |
1472 | 0 | } |
1473 | | // Apply the best RCT to the image for future encoding. |
1474 | 0 | sg.rct_type = best_rct; |
1475 | 0 | do_transform(gi, sg, weighted::Header()); |
1476 | 111 | } else { |
1477 | | // No need to try anything, just use the default options. |
1478 | 111 | } |
1479 | 111 | size_t nb_wp_modes = 1; |
1480 | 111 | if (cparams.speed_tier <= SpeedTier::kTortoise) { |
1481 | 0 | nb_wp_modes = 5; |
1482 | 111 | } else if (cparams.speed_tier <= SpeedTier::kKitten) { |
1483 | 0 | nb_wp_modes = 2; |
1484 | 0 | } |
1485 | 111 | if (nb_wp_modes > 1 && |
1486 | 111 | (stream_options_[stream_id].predictor == Predictor::Weighted || |
1487 | 0 | stream_options_[stream_id].predictor == Predictor::Best || |
1488 | 0 | stream_options_[stream_id].predictor == Predictor::Variable)) { |
1489 | 0 | float best_cost = std::numeric_limits<float>::max(); |
1490 | 0 | stream_options_[stream_id].wp_mode = 0; |
1491 | 0 | for (size_t i = 0; i < nb_wp_modes; i++) { |
1492 | 0 | float cost = EstimateWPCost(gi, i); |
1493 | 0 | if (cost < best_cost) { |
1494 | 0 | best_cost = cost; |
1495 | 0 | stream_options_[stream_id].wp_mode = i; |
1496 | 0 | } |
1497 | 0 | } |
1498 | 0 | } |
1499 | 111 | return true; |
1500 | 111 | } |
1501 | | |
1502 | | constexpr float q_deadzone = 0.62f; |
1503 | | int QuantizeWP(const int32_t* qrow, size_t onerow, size_t c, size_t x, size_t y, |
1504 | | size_t w, weighted::State* wp_state, float value, |
1505 | 1.19M | float inv_factor) { |
1506 | 1.19M | float svalue = value * inv_factor; |
1507 | 1.19M | PredictionResult pred = |
1508 | 1.19M | PredictNoTreeWP(w, qrow + x, onerow, x, y, Predictor::Weighted, wp_state); |
1509 | 1.19M | svalue -= pred.guess; |
1510 | 1.19M | if (svalue > -q_deadzone && svalue < q_deadzone) svalue = 0; |
1511 | 1.19M | int residual = std::round(svalue); |
1512 | 1.19M | if (residual > 2 || residual < -2) residual = std::round(svalue * 0.5f) * 2; |
1513 | 1.19M | return residual + pred.guess; |
1514 | 1.19M | } |
1515 | | |
1516 | | int QuantizeGradient(const int32_t* qrow, size_t onerow, size_t c, size_t x, |
1517 | 0 | size_t y, size_t w, float value, float inv_factor) { |
1518 | 0 | float svalue = value * inv_factor; |
1519 | 0 | PredictionResult pred = |
1520 | 0 | PredictNoTreeNoWP(w, qrow + x, onerow, x, y, Predictor::Gradient); |
1521 | 0 | svalue -= pred.guess; |
1522 | 0 | if (svalue > -q_deadzone && svalue < q_deadzone) svalue = 0; |
1523 | 0 | int residual = std::round(svalue); |
1524 | 0 | if (residual > 2 || residual < -2) residual = std::round(svalue * 0.5f) * 2; |
1525 | 0 | return residual + pred.guess; |
1526 | 0 | } |
1527 | | |
1528 | | Status ModularFrameEncoder::AddVarDCTDC(const FrameHeader& frame_header, |
1529 | | const Image3F& dc, const Rect& r, |
1530 | | size_t group_index, bool nl_dc, |
1531 | | PassesEncoderState* enc_state, |
1532 | 186 | bool jpeg_transcode) { |
1533 | 186 | JxlMemoryManager* memory_manager = dc.memory_manager(); |
1534 | 186 | extra_dc_precision[group_index] = nl_dc ? 1 : 0; |
1535 | 186 | float mul = 1 << extra_dc_precision[group_index]; |
1536 | | |
1537 | 186 | size_t stream_id = ModularStreamId::VarDCTDC(group_index).ID(frame_dim_); |
1538 | 186 | stream_options_[stream_id].max_chan_size = 0xFFFFFF; |
1539 | 186 | stream_options_[stream_id].predictor = Predictor::Weighted; |
1540 | 186 | stream_options_[stream_id].wp_tree_mode = ModularOptions::TreeMode::kWPOnly; |
1541 | 186 | if (cparams_.speed_tier >= SpeedTier::kSquirrel) { |
1542 | 186 | stream_options_[stream_id].tree_kind = ModularOptions::TreeKind::kWPFixedDC; |
1543 | 186 | } |
1544 | 186 | if (cparams_.speed_tier < SpeedTier::kSquirrel && !nl_dc) { |
1545 | 0 | stream_options_[stream_id].predictor = |
1546 | 0 | (cparams_.speed_tier < SpeedTier::kKitten ? Predictor::Variable |
1547 | 0 | : Predictor::Best); |
1548 | 0 | stream_options_[stream_id].wp_tree_mode = |
1549 | 0 | ModularOptions::TreeMode::kDefault; |
1550 | 0 | stream_options_[stream_id].tree_kind = ModularOptions::TreeKind::kLearn; |
1551 | 0 | } |
1552 | 186 | if (cparams_.decoding_speed_tier >= 1) { |
1553 | 0 | stream_options_[stream_id].tree_kind = |
1554 | 0 | ModularOptions::TreeKind::kGradientFixedDC; |
1555 | 0 | } |
1556 | 186 | stream_options_[stream_id].histogram_params = |
1557 | 186 | stream_options_[0].histogram_params; |
1558 | | |
1559 | 186 | JXL_ASSIGN_OR_RETURN( |
1560 | 186 | stream_images_[stream_id], |
1561 | 186 | Image::Create(memory_manager, r.xsize(), r.ysize(), 8, 3)); |
1562 | 186 | const ColorCorrelation& color_correlation = enc_state->shared.cmap.base(); |
1563 | 186 | if (nl_dc && stream_options_[stream_id].tree_kind == |
1564 | 186 | ModularOptions::TreeKind::kGradientFixedDC) { |
1565 | 0 | JXL_ENSURE(frame_header.chroma_subsampling.Is444()); |
1566 | 0 | for (size_t c : {1, 0, 2}) { |
1567 | 0 | float inv_factor = enc_state->shared.quantizer.GetInvDcStep(c) * mul; |
1568 | 0 | float y_factor = enc_state->shared.quantizer.GetDcStep(1) / mul; |
1569 | 0 | float cfl_factor = color_correlation.DCFactors()[c]; |
1570 | 0 | for (size_t y = 0; y < r.ysize(); y++) { |
1571 | 0 | int32_t* quant_row = |
1572 | 0 | stream_images_[stream_id].channel[c < 2 ? c ^ 1 : c].plane.Row(y); |
1573 | 0 | size_t stride = stream_images_[stream_id] |
1574 | 0 | .channel[c < 2 ? c ^ 1 : c] |
1575 | 0 | .plane.PixelsPerRow(); |
1576 | 0 | const float* row = r.ConstPlaneRow(dc, c, y); |
1577 | 0 | if (c == 1) { |
1578 | 0 | for (size_t x = 0; x < r.xsize(); x++) { |
1579 | 0 | quant_row[x] = QuantizeGradient(quant_row, stride, c, x, y, |
1580 | 0 | r.xsize(), row[x], inv_factor); |
1581 | 0 | } |
1582 | 0 | } else { |
1583 | 0 | int32_t* quant_row_y = |
1584 | 0 | stream_images_[stream_id].channel[0].plane.Row(y); |
1585 | 0 | for (size_t x = 0; x < r.xsize(); x++) { |
1586 | 0 | quant_row[x] = QuantizeGradient( |
1587 | 0 | quant_row, stride, c, x, y, r.xsize(), |
1588 | 0 | row[x] - quant_row_y[x] * (y_factor * cfl_factor), inv_factor); |
1589 | 0 | } |
1590 | 0 | } |
1591 | 0 | } |
1592 | 0 | } |
1593 | 186 | } else if (nl_dc) { |
1594 | 186 | JXL_ENSURE(frame_header.chroma_subsampling.Is444()); |
1595 | 558 | for (size_t c : {1, 0, 2}) { |
1596 | 558 | float inv_factor = enc_state->shared.quantizer.GetInvDcStep(c) * mul; |
1597 | 558 | float y_factor = enc_state->shared.quantizer.GetDcStep(1) / mul; |
1598 | 558 | float cfl_factor = color_correlation.DCFactors()[c]; |
1599 | 558 | weighted::Header header; |
1600 | 558 | weighted::State wp_state(header, r.xsize(), r.ysize()); |
1601 | 22.5k | for (size_t y = 0; y < r.ysize(); y++) { |
1602 | 21.9k | int32_t* quant_row = |
1603 | 21.9k | stream_images_[stream_id].channel[c < 2 ? c ^ 1 : c].plane.Row(y); |
1604 | 21.9k | size_t stride = stream_images_[stream_id] |
1605 | 21.9k | .channel[c < 2 ? c ^ 1 : c] |
1606 | 21.9k | .plane.PixelsPerRow(); |
1607 | 21.9k | const float* row = r.ConstPlaneRow(dc, c, y); |
1608 | 21.9k | if (c == 1) { |
1609 | 405k | for (size_t x = 0; x < r.xsize(); x++) { |
1610 | 398k | quant_row[x] = QuantizeWP(quant_row, stride, c, x, y, r.xsize(), |
1611 | 398k | &wp_state, row[x], inv_factor); |
1612 | 398k | wp_state.UpdateErrors(quant_row[x], x, y, r.xsize()); |
1613 | 398k | } |
1614 | 14.6k | } else { |
1615 | 14.6k | int32_t* quant_row_y = |
1616 | 14.6k | stream_images_[stream_id].channel[0].plane.Row(y); |
1617 | 810k | for (size_t x = 0; x < r.xsize(); x++) { |
1618 | 796k | quant_row[x] = QuantizeWP( |
1619 | 796k | quant_row, stride, c, x, y, r.xsize(), &wp_state, |
1620 | 796k | row[x] - quant_row_y[x] * (y_factor * cfl_factor), inv_factor); |
1621 | 796k | wp_state.UpdateErrors(quant_row[x], x, y, r.xsize()); |
1622 | 796k | } |
1623 | 14.6k | } |
1624 | 21.9k | } |
1625 | 558 | } |
1626 | 186 | } else if (frame_header.chroma_subsampling.Is444()) { |
1627 | 0 | for (size_t c : {1, 0, 2}) { |
1628 | 0 | float inv_factor = enc_state->shared.quantizer.GetInvDcStep(c) * mul; |
1629 | 0 | float y_factor = enc_state->shared.quantizer.GetDcStep(1) / mul; |
1630 | 0 | float cfl_factor = color_correlation.DCFactors()[c]; |
1631 | 0 | for (size_t y = 0; y < r.ysize(); y++) { |
1632 | 0 | int32_t* quant_row = |
1633 | 0 | stream_images_[stream_id].channel[c < 2 ? c ^ 1 : c].plane.Row(y); |
1634 | 0 | const float* row = r.ConstPlaneRow(dc, c, y); |
1635 | 0 | if (c == 1) { |
1636 | 0 | for (size_t x = 0; x < r.xsize(); x++) { |
1637 | 0 | quant_row[x] = std::round(row[x] * inv_factor); |
1638 | 0 | } |
1639 | 0 | } else { |
1640 | 0 | int32_t* quant_row_y = |
1641 | 0 | stream_images_[stream_id].channel[0].plane.Row(y); |
1642 | 0 | for (size_t x = 0; x < r.xsize(); x++) { |
1643 | 0 | quant_row[x] = |
1644 | 0 | std::round((row[x] - quant_row_y[x] * (y_factor * cfl_factor)) * |
1645 | 0 | inv_factor); |
1646 | 0 | } |
1647 | 0 | } |
1648 | 0 | } |
1649 | 0 | } |
1650 | 0 | } else { |
1651 | 0 | for (size_t c : {1, 0, 2}) { |
1652 | 0 | Rect rect(r.x0() >> frame_header.chroma_subsampling.HShift(c), |
1653 | 0 | r.y0() >> frame_header.chroma_subsampling.VShift(c), |
1654 | 0 | r.xsize() >> frame_header.chroma_subsampling.HShift(c), |
1655 | 0 | r.ysize() >> frame_header.chroma_subsampling.VShift(c)); |
1656 | 0 | float inv_factor = enc_state->shared.quantizer.GetInvDcStep(c) * mul; |
1657 | 0 | size_t ys = rect.ysize(); |
1658 | 0 | size_t xs = rect.xsize(); |
1659 | 0 | Channel& ch = stream_images_[stream_id].channel[c < 2 ? c ^ 1 : c]; |
1660 | 0 | ch.w = xs; |
1661 | 0 | ch.h = ys; |
1662 | 0 | JXL_RETURN_IF_ERROR(ch.shrink()); |
1663 | 0 | for (size_t y = 0; y < ys; y++) { |
1664 | 0 | int32_t* quant_row = ch.plane.Row(y); |
1665 | 0 | const float* row = rect.ConstPlaneRow(dc, c, y); |
1666 | 0 | for (size_t x = 0; x < xs; x++) { |
1667 | 0 | quant_row[x] = std::round(row[x] * inv_factor); |
1668 | 0 | } |
1669 | 0 | } |
1670 | 0 | } |
1671 | 0 | } |
1672 | | |
1673 | 186 | DequantDC(r, &enc_state->shared.dc_storage, &enc_state->shared.quant_dc, |
1674 | 186 | stream_images_[stream_id], enc_state->shared.quantizer.MulDC(), |
1675 | 186 | 1.0 / mul, color_correlation.DCFactors(), |
1676 | 186 | frame_header.chroma_subsampling, enc_state->shared.block_ctx_map); |
1677 | 186 | return true; |
1678 | 186 | } |
1679 | | |
1680 | | Status ModularFrameEncoder::AddACMetadata(const Rect& r, size_t group_index, |
1681 | | bool jpeg_transcode, |
1682 | 186 | PassesEncoderState* enc_state) { |
1683 | 186 | JxlMemoryManager* memory_manager = enc_state->memory_manager(); |
1684 | 186 | size_t stream_id = ModularStreamId::ACMetadata(group_index).ID(frame_dim_); |
1685 | 186 | stream_options_[stream_id].max_chan_size = 0xFFFFFF; |
1686 | 186 | if (stream_options_[stream_id].predictor != Predictor::Weighted) { |
1687 | 186 | stream_options_[stream_id].wp_tree_mode = ModularOptions::TreeMode::kNoWP; |
1688 | 186 | } |
1689 | 186 | if (jpeg_transcode) { |
1690 | 0 | stream_options_[stream_id].tree_kind = |
1691 | 0 | ModularOptions::TreeKind::kJpegTranscodeACMeta; |
1692 | 186 | } else if (cparams_.speed_tier >= SpeedTier::kFalcon) { |
1693 | 0 | stream_options_[stream_id].tree_kind = |
1694 | 0 | ModularOptions::TreeKind::kFalconACMeta; |
1695 | 186 | } else if (cparams_.speed_tier > SpeedTier::kKitten) { |
1696 | 186 | stream_options_[stream_id].tree_kind = ModularOptions::TreeKind::kACMeta; |
1697 | 186 | } |
1698 | | // If we are using a non-constant CfL field, and are in a slow enough mode, |
1699 | | // re-enable tree computation for it. |
1700 | 186 | if (cparams_.speed_tier < SpeedTier::kSquirrel && |
1701 | 186 | cparams_.force_cfl_jpeg_recompression) { |
1702 | 0 | stream_options_[stream_id].tree_kind = ModularOptions::TreeKind::kLearn; |
1703 | 0 | } |
1704 | 186 | stream_options_[stream_id].histogram_params = |
1705 | 186 | stream_options_[0].histogram_params; |
1706 | | // YToX, YToB, ACS + QF, EPF |
1707 | 186 | Image& image = stream_images_[stream_id]; |
1708 | 186 | JXL_ASSIGN_OR_RETURN( |
1709 | 186 | image, Image::Create(memory_manager, r.xsize(), r.ysize(), 8, 4)); |
1710 | 186 | static_assert(kColorTileDimInBlocks == 8, "Color tile size changed"); |
1711 | 186 | Rect cr(r.x0() >> 3, r.y0() >> 3, (r.xsize() + 7) >> 3, (r.ysize() + 7) >> 3); |
1712 | 186 | JXL_ASSIGN_OR_RETURN( |
1713 | 186 | image.channel[0], |
1714 | 186 | Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3)); |
1715 | 186 | JXL_ASSIGN_OR_RETURN( |
1716 | 186 | image.channel[1], |
1717 | 186 | Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3)); |
1718 | 186 | JXL_ASSIGN_OR_RETURN( |
1719 | 186 | image.channel[2], |
1720 | 186 | Channel::Create(memory_manager, r.xsize() * r.ysize(), 2, 0, 0)); |
1721 | 186 | JXL_RETURN_IF_ERROR(ConvertPlaneAndClamp(cr, enc_state->shared.cmap.ytox_map, |
1722 | 186 | Rect(image.channel[0].plane), |
1723 | 186 | &image.channel[0].plane)); |
1724 | 186 | JXL_RETURN_IF_ERROR(ConvertPlaneAndClamp(cr, enc_state->shared.cmap.ytob_map, |
1725 | 186 | Rect(image.channel[1].plane), |
1726 | 186 | &image.channel[1].plane)); |
1727 | 186 | size_t num = 0; |
1728 | 7.51k | for (size_t y = 0; y < r.ysize(); y++) { |
1729 | 7.32k | AcStrategyRow row_acs = enc_state->shared.ac_strategy.ConstRow(r, y); |
1730 | 7.32k | const int32_t* row_qf = r.ConstRow(enc_state->shared.raw_quant_field, y); |
1731 | 7.32k | const uint8_t* row_epf = r.ConstRow(enc_state->shared.epf_sharpness, y); |
1732 | 7.32k | int32_t* out_acs = image.channel[2].plane.Row(0); |
1733 | 7.32k | int32_t* out_qf = image.channel[2].plane.Row(1); |
1734 | 7.32k | int32_t* row_out_epf = image.channel[3].plane.Row(y); |
1735 | 405k | for (size_t x = 0; x < r.xsize(); x++) { |
1736 | 398k | row_out_epf[x] = row_epf[x]; |
1737 | 398k | if (!row_acs[x].IsFirstBlock()) continue; |
1738 | 241k | out_acs[num] = row_acs[x].RawStrategy(); |
1739 | 241k | out_qf[num] = row_qf[x] - 1; |
1740 | 241k | num++; |
1741 | 241k | } |
1742 | 7.32k | } |
1743 | 186 | image.channel[2].w = num; |
1744 | 186 | ac_metadata_size[group_index] = num; |
1745 | 186 | return true; |
1746 | 186 | } |
1747 | | |
1748 | | Status ModularFrameEncoder::EncodeQuantTable( |
1749 | | JxlMemoryManager* memory_manager, size_t size_x, size_t size_y, |
1750 | | BitWriter* writer, const QuantEncoding& encoding, size_t idx, |
1751 | 0 | ModularFrameEncoder* modular_frame_encoder) { |
1752 | 0 | JXL_ENSURE(encoding.qraw.qtable); |
1753 | 0 | JXL_ENSURE(size_x * size_y * 3 == encoding.qraw.qtable->size()); |
1754 | 0 | JXL_ENSURE(idx < kNumQuantTables); |
1755 | 0 | int* qtable = encoding.qraw.qtable->data(); |
1756 | 0 | JXL_RETURN_IF_ERROR(F16Coder::Write(encoding.qraw.qtable_den, writer)); |
1757 | 0 | if (modular_frame_encoder) { |
1758 | 0 | JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx)); |
1759 | 0 | JXL_RETURN_IF_ERROR(modular_frame_encoder->EncodeStream( |
1760 | 0 | writer, nullptr, LayerType::Header, qt)); |
1761 | 0 | return true; |
1762 | 0 | } |
1763 | 0 | JXL_ASSIGN_OR_RETURN(Image image, |
1764 | 0 | Image::Create(memory_manager, size_x, size_y, 8, 3)); |
1765 | 0 | for (size_t c = 0; c < 3; c++) { |
1766 | 0 | for (size_t y = 0; y < size_y; y++) { |
1767 | 0 | int32_t* JXL_RESTRICT row = image.channel[c].Row(y); |
1768 | 0 | for (size_t x = 0; x < size_x; x++) { |
1769 | 0 | row[x] = qtable[c * size_x * size_y + y * size_x + x]; |
1770 | 0 | } |
1771 | 0 | } |
1772 | 0 | } |
1773 | 0 | ModularOptions cfopts; |
1774 | 0 | JXL_RETURN_IF_ERROR(ModularGenericCompress(image, cfopts, *writer)); |
1775 | 0 | return true; |
1776 | 0 | } |
1777 | | |
1778 | | Status ModularFrameEncoder::AddQuantTable(size_t size_x, size_t size_y, |
1779 | | const QuantEncoding& encoding, |
1780 | 0 | size_t idx) { |
1781 | 0 | JXL_ENSURE(idx < kNumQuantTables); |
1782 | 0 | JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx)); |
1783 | 0 | size_t stream_id = qt.ID(frame_dim_); |
1784 | 0 | JXL_ENSURE(encoding.qraw.qtable); |
1785 | 0 | JXL_ENSURE(size_x * size_y * 3 == encoding.qraw.qtable->size()); |
1786 | 0 | int* qtable = encoding.qraw.qtable->data(); |
1787 | 0 | Image& image = stream_images_[stream_id]; |
1788 | 0 | JxlMemoryManager* memory_manager = image.memory_manager(); |
1789 | 0 | JXL_ASSIGN_OR_RETURN(image, |
1790 | 0 | Image::Create(memory_manager, size_x, size_y, 8, 3)); |
1791 | 0 | for (size_t c = 0; c < 3; c++) { |
1792 | 0 | for (size_t y = 0; y < size_y; y++) { |
1793 | 0 | int32_t* JXL_RESTRICT row = image.channel[c].Row(y); |
1794 | 0 | for (size_t x = 0; x < size_x; x++) { |
1795 | 0 | row[x] = qtable[c * size_x * size_y + y * size_x + x]; |
1796 | 0 | } |
1797 | 0 | } |
1798 | 0 | } |
1799 | 0 | return true; |
1800 | 0 | } |
1801 | | } // namespace jxl |