Coverage Report

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