Coverage Report

Created: 2026-11-12 07:35

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