Coverage Report

Created: 2026-06-16 07:20

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