Coverage Report

Created: 2025-11-16 07:22

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