Coverage Report

Created: 2025-07-23 08:18

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