Coverage Report

Created: 2025-09-08 07:52

/src/libjxl/lib/jxl/dec_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/dec_modular.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <cstdint>
11
#include <vector>
12
13
#include "lib/jxl/frame_header.h"
14
15
#undef HWY_TARGET_INCLUDE
16
#define HWY_TARGET_INCLUDE "lib/jxl/dec_modular.cc"
17
#include <hwy/foreach_target.h>
18
#include <hwy/highway.h>
19
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/base/printf_macros.h"
22
#include "lib/jxl/base/rect.h"
23
#include "lib/jxl/base/status.h"
24
#include "lib/jxl/compressed_dc.h"
25
#include "lib/jxl/epf.h"
26
#include "lib/jxl/modular/encoding/encoding.h"
27
#include "lib/jxl/modular/modular_image.h"
28
#include "lib/jxl/modular/transform/transform.h"
29
30
HWY_BEFORE_NAMESPACE();
31
namespace jxl {
32
namespace HWY_NAMESPACE {
33
34
// These templates are not found via ADL.
35
using hwy::HWY_NAMESPACE::Add;
36
using hwy::HWY_NAMESPACE::Mul;
37
using hwy::HWY_NAMESPACE::Rebind;
38
39
void MultiplySum(const size_t xsize,
40
                 const pixel_type* const JXL_RESTRICT row_in,
41
                 const pixel_type* const JXL_RESTRICT row_in_Y,
42
186k
                 const float factor, float* const JXL_RESTRICT row_out) {
43
186k
  const HWY_FULL(float) df;
44
186k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
45
186k
  const auto factor_v = Set(df, factor);
46
32.2M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
47
32.1M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
48
32.1M
    const auto out = Mul(ConvertTo(df, in), factor_v);
49
32.1M
    Store(out, df, row_out + x);
50
32.1M
  }
51
186k
}
52
53
void RgbFromSingle(const size_t xsize,
54
                   const pixel_type* const JXL_RESTRICT row_in,
55
                   const float factor, float* out_r, float* out_g,
56
1.31k
                   float* out_b) {
57
1.31k
  const HWY_FULL(float) df;
58
1.31k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
59
60
1.31k
  const auto factor_v = Set(df, factor);
61
272k
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
62
270k
    const auto in = Load(di, row_in + x);
63
270k
    const auto out = Mul(ConvertTo(df, in), factor_v);
64
270k
    Store(out, df, out_r + x);
65
270k
    Store(out, df, out_g + x);
66
270k
    Store(out, df, out_b + x);
67
270k
  }
68
1.31k
}
69
70
void SingleFromSingle(const size_t xsize,
71
                      const pixel_type* const JXL_RESTRICT row_in,
72
1.55M
                      const float factor, float* row_out) {
73
1.55M
  const HWY_FULL(float) df;
74
1.55M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
75
76
1.55M
  const auto factor_v = Set(df, factor);
77
239M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
78
237M
    const auto in = Load(di, row_in + x);
79
237M
    const auto out = Mul(ConvertTo(df, in), factor_v);
80
237M
    Store(out, df, row_out + x);
81
237M
  }
82
1.55M
}
83
// NOLINTNEXTLINE(google-readability-namespace-comments)
84
}  // namespace HWY_NAMESPACE
85
}  // namespace jxl
86
HWY_AFTER_NAMESPACE();
87
88
#if HWY_ONCE
89
namespace jxl {
90
HWY_EXPORT(MultiplySum);       // Local function
91
HWY_EXPORT(RgbFromSingle);     // Local function
92
HWY_EXPORT(SingleFromSingle);  // Local function
93
94
// Slow conversion using double precision multiplication, only
95
// needed when the bit depth is too high for single precision
96
void SingleFromSingleAccurate(const size_t xsize,
97
                              const pixel_type* const JXL_RESTRICT row_in,
98
516
                              const double factor, float* row_out) {
99
1.77k
  for (size_t x = 0; x < xsize; x++) {
100
1.25k
    row_out[x] = row_in[x] * factor;
101
1.25k
  }
102
516
}
103
104
// convert custom [bits]-bit float (with [exp_bits] exponent bits) stored as int
105
// back to binary32 float
106
Status int_to_float(const pixel_type* const JXL_RESTRICT row_in,
107
                    float* const JXL_RESTRICT row_out, const size_t xsize,
108
68.3k
                    const int bits, const int exp_bits) {
109
68.3k
  static_assert(sizeof(pixel_type) == sizeof(float));
110
68.3k
  if (bits == 32) {
111
67.3k
    JXL_ENSURE(exp_bits == 8);
112
67.3k
    memcpy(row_out, row_in, xsize * sizeof(float));
113
67.3k
    return true;
114
67.3k
  }
115
1.05k
  int exp_bias = (1 << (exp_bits - 1)) - 1;
116
1.05k
  int sign_shift = bits - 1;
117
1.05k
  int mant_bits = bits - exp_bits - 1;
118
1.05k
  int mant_shift = 23 - mant_bits;
119
34.8k
  for (size_t x = 0; x < xsize; ++x) {
120
33.7k
    uint32_t f;
121
33.7k
    memcpy(&f, &row_in[x], 4);
122
33.7k
    int signbit = (f >> sign_shift);
123
33.7k
    f &= (1 << sign_shift) - 1;
124
33.7k
    if (f == 0) {
125
9.32k
      row_out[x] = (signbit ? -0.f : 0.f);
126
9.32k
      continue;
127
9.32k
    }
128
24.4k
    int exp = (f >> mant_bits);
129
24.4k
    int mantissa = (f & ((1 << mant_bits) - 1));
130
24.4k
    mantissa <<= mant_shift;
131
    // Try to normalize only if there is space for maneuver.
132
24.4k
    if (exp == 0 && exp_bits < 8) {
133
      // subnormal number
134
470
      while ((mantissa & 0x800000) == 0) {
135
326
        mantissa <<= 1;
136
326
        exp--;
137
326
      }
138
144
      exp++;
139
      // remove leading 1 because it is implicit now
140
144
      mantissa &= 0x7fffff;
141
144
    }
142
24.4k
    exp -= exp_bias;
143
    // broke up the arbitrary float into its parts, now reassemble into
144
    // binary32
145
24.4k
    exp += 127;
146
24.4k
    JXL_ENSURE(exp >= 0);
147
24.4k
    f = (signbit ? 0x80000000 : 0);
148
24.4k
    f |= (exp << 23);
149
24.4k
    f |= mantissa;
150
24.4k
    memcpy(&row_out[x], &f, 4);
151
24.4k
  }
152
1.05k
  return true;
153
1.05k
}
154
155
#if JXL_DEBUG_V_LEVEL >= 1
156
std::string ModularStreamId::DebugString() const {
157
  std::ostringstream os;
158
  os << (kind == GlobalData   ? "ModularGlobal"
159
         : kind == VarDCTDC   ? "VarDCTDC"
160
         : kind == ModularDC  ? "ModularDC"
161
         : kind == ACMetadata ? "ACMeta"
162
         : kind == QuantTable ? "QuantTable"
163
         : kind == ModularAC  ? "ModularAC"
164
                              : "");
165
  if (kind == VarDCTDC || kind == ModularDC || kind == ACMetadata ||
166
      kind == ModularAC) {
167
    os << " group " << group_id;
168
  }
169
  if (kind == ModularAC) {
170
    os << " pass " << pass_id;
171
  }
172
  if (kind == QuantTable) {
173
    os << " " << quant_table_id;
174
  }
175
  return os.str();
176
}
177
#endif
178
179
Status ModularFrameDecoder::DecodeGlobalInfo(BitReader* reader,
180
                                             const FrameHeader& frame_header,
181
10.6k
                                             bool allow_truncated_group) {
182
10.6k
  JxlMemoryManager* memory_manager = this->memory_manager();
183
10.6k
  bool decode_color = frame_header.encoding == FrameEncoding::kModular;
184
10.6k
  const auto& metadata = frame_header.nonserialized_metadata->m;
185
10.6k
  bool is_gray = metadata.color_encoding.IsGray();
186
10.6k
  size_t nb_chans = 3;
187
10.6k
  if (is_gray && frame_header.color_transform == ColorTransform::kNone) {
188
16
    nb_chans = 1;
189
16
  }
190
10.6k
  do_color = decode_color;
191
10.6k
  size_t nb_extra = metadata.extra_channel_info.size();
192
10.6k
  bool has_tree = static_cast<bool>(reader->ReadBits(1));
193
10.6k
  if (!allow_truncated_group ||
194
10.6k
      reader->TotalBitsConsumed() < reader->TotalBytes() * kBitsPerByte) {
195
10.6k
    if (has_tree) {
196
7.76k
      size_t tree_size_limit =
197
7.76k
          std::min(static_cast<size_t>(1 << 22),
198
7.76k
                   1024 + frame_dim.xsize * frame_dim.ysize *
199
7.76k
                              (nb_chans + nb_extra) / 16);
200
7.76k
      JXL_RETURN_IF_ERROR(
201
7.76k
          DecodeTree(memory_manager, reader, &tree, tree_size_limit));
202
7.75k
      JXL_RETURN_IF_ERROR(DecodeHistograms(
203
7.75k
          memory_manager, reader, (tree.size() + 1) / 2, &code, &context_map));
204
7.75k
    }
205
10.6k
  }
206
10.6k
  if (!do_color) nb_chans = 0;
207
208
10.6k
  bool fp = metadata.bit_depth.floating_point_sample;
209
210
  // bits_per_sample is just metadata for XYB images.
211
10.6k
  if (metadata.bit_depth.bits_per_sample >= 32 && do_color &&
212
10.6k
      frame_header.color_transform != ColorTransform::kXYB) {
213
1.13k
    if (metadata.bit_depth.bits_per_sample == 32 && fp == false) {
214
0
      return JXL_FAILURE("uint32_t not supported in dec_modular");
215
1.13k
    } else if (metadata.bit_depth.bits_per_sample > 32) {
216
0
      return JXL_FAILURE("bits_per_sample > 32 not supported");
217
0
    }
218
1.13k
  }
219
220
21.2k
  JXL_ASSIGN_OR_RETURN(
221
21.2k
      Image gi,
222
21.2k
      Image::Create(memory_manager, frame_dim.xsize, frame_dim.ysize,
223
21.2k
                    metadata.bit_depth.bits_per_sample, nb_chans + nb_extra));
224
225
21.2k
  all_same_shift = true;
226
21.2k
  if (frame_header.color_transform == ColorTransform::kYCbCr) {
227
6.00k
    for (size_t c = 0; c < nb_chans; c++) {
228
4.50k
      gi.channel[c].hshift = frame_header.chroma_subsampling.HShift(c);
229
4.50k
      gi.channel[c].vshift = frame_header.chroma_subsampling.VShift(c);
230
4.50k
      size_t xsize_shifted =
231
4.50k
          DivCeil(frame_dim.xsize, 1 << gi.channel[c].hshift);
232
4.50k
      size_t ysize_shifted =
233
4.50k
          DivCeil(frame_dim.ysize, 1 << gi.channel[c].vshift);
234
4.50k
      JXL_RETURN_IF_ERROR(gi.channel[c].shrink(xsize_shifted, ysize_shifted));
235
4.50k
      if (gi.channel[c].hshift != gi.channel[0].hshift ||
236
4.50k
          gi.channel[c].vshift != gi.channel[0].vshift)
237
1.96k
        all_same_shift = false;
238
4.50k
    }
239
1.50k
  }
240
241
12.8k
  for (size_t ec = 0, c = nb_chans; ec < nb_extra; ec++, c++) {
242
2.23k
    size_t ecups = frame_header.extra_channel_upsampling[ec];
243
2.23k
    JXL_RETURN_IF_ERROR(
244
2.23k
        gi.channel[c].shrink(DivCeil(frame_dim.xsize_upsampled, ecups),
245
2.23k
                             DivCeil(frame_dim.ysize_upsampled, ecups)));
246
2.23k
    gi.channel[c].hshift = gi.channel[c].vshift =
247
2.23k
        CeilLog2Nonzero(ecups) - CeilLog2Nonzero(frame_header.upsampling);
248
2.23k
    if (gi.channel[c].hshift != gi.channel[0].hshift ||
249
2.23k
        gi.channel[c].vshift != gi.channel[0].vshift)
250
685
      all_same_shift = false;
251
2.23k
  }
252
253
10.6k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (w/o transforms) %s",
254
10.6k
              gi.DebugString().c_str());
255
10.6k
  ModularOptions options;
256
10.6k
  options.max_chan_size = frame_dim.group_dim;
257
10.6k
  options.group_dim = frame_dim.group_dim;
258
10.6k
  Status dec_status = ModularGenericDecompress(
259
10.6k
      reader, gi, &global_header, ModularStreamId::Global().ID(frame_dim),
260
10.6k
      &options,
261
10.6k
      /*undo_transforms=*/false, &tree, &code, &context_map,
262
10.6k
      allow_truncated_group);
263
10.6k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
264
10.6k
  if (dec_status.IsFatalError()) {
265
0
    return JXL_FAILURE("Failed to decode global modular info");
266
0
  }
267
268
  // TODO(eustas): are we sure this can be done after partial decode?
269
10.6k
  have_something = false;
270
39.2k
  for (size_t c = 0; c < gi.channel.size(); c++) {
271
28.6k
    Channel& gic = gi.channel[c];
272
28.6k
    if (c >= gi.nb_meta_channels && gic.w <= frame_dim.group_dim &&
273
28.6k
        gic.h <= frame_dim.group_dim)
274
24.8k
      have_something = true;
275
28.6k
  }
276
  // move global transforms to groups if possible
277
10.6k
  if (!have_something && all_same_shift) {
278
5.97k
    if (gi.transform.size() == 1 && gi.transform[0].id == TransformId::kRCT) {
279
18
      global_transform = gi.transform;
280
18
      gi.transform.clear();
281
      // TODO(jon): also move no-delta-palette out (trickier though)
282
18
    }
283
5.97k
  }
284
10.6k
  full_image = std::move(gi);
285
10.6k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (with transforms) %s",
286
10.6k
              full_image.DebugString().c_str());
287
10.6k
  return dec_status;
288
10.6k
}
289
290
10.5k
void ModularFrameDecoder::MaybeDropFullImage() {
291
10.5k
  if (full_image.transform.empty() && !have_something && all_same_shift) {
292
5.94k
    use_full_image = false;
293
5.94k
    JXL_DEBUG_V(6, "Dropping full image");
294
5.94k
    for (auto& ch : full_image.channel) {
295
      // keep metadata on channels around, but dealloc their planes
296
262
      ch.plane = Plane<pixel_type>();
297
262
    }
298
5.94k
  }
299
10.5k
}
300
301
Status ModularFrameDecoder::DecodeGroup(
302
    const FrameHeader& frame_header, const Rect& rect, BitReader* reader,
303
    int minShift, int maxShift, const ModularStreamId& stream, bool zerofill,
304
    PassesDecoderState* dec_state, RenderPipelineInput* render_pipeline_input,
305
27.8k
    bool allow_truncated, bool* should_run_pipeline) {
306
27.8k
  JXL_DEBUG_V(6, "Decoding %s with rect %s and shift bracket %d..%d %s",
307
27.8k
              stream.DebugString().c_str(), Description(rect).c_str(), minShift,
308
27.8k
              maxShift, zerofill ? "using zerofill" : "");
309
27.8k
  JXL_ENSURE(stream.kind == ModularStreamId::Kind::ModularDC ||
310
27.8k
             stream.kind == ModularStreamId::Kind::ModularAC);
311
27.8k
  const size_t xsize = rect.xsize();
312
27.8k
  const size_t ysize = rect.ysize();
313
27.8k
  JXL_ASSIGN_OR_RETURN(Image gi, Image::Create(memory_manager_, xsize, ysize,
314
27.8k
                                               full_image.bitdepth, 0));
315
  // start at the first bigger-than-groupsize non-metachannel
316
27.8k
  size_t c = full_image.nb_meta_channels;
317
65.4k
  for (; c < full_image.channel.size(); c++) {
318
45.7k
    Channel& fc = full_image.channel[c];
319
45.7k
    if (fc.w > frame_dim.group_dim || fc.h > frame_dim.group_dim) break;
320
45.7k
  }
321
27.8k
  size_t beginc = c;
322
74.9k
  for (; c < full_image.channel.size(); c++) {
323
47.0k
    Channel& fc = full_image.channel[c];
324
47.0k
    int shift = std::min(fc.hshift, fc.vshift);
325
47.0k
    if (shift > maxShift) continue;
326
45.2k
    if (shift < minShift) continue;
327
30.6k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
328
30.6k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
329
30.6k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
330
30.6k
    if (zerofill && use_full_image) {
331
0
      for (size_t y = 0; y < r.ysize(); ++y) {
332
0
        pixel_type* const JXL_RESTRICT row_out = r.Row(&fc.plane, y);
333
0
        memset(row_out, 0, r.xsize() * sizeof(*row_out));
334
0
      }
335
30.6k
    } else {
336
30.6k
      JXL_ASSIGN_OR_RETURN(
337
30.6k
          Channel gc, Channel::Create(memory_manager_, r.xsize(), r.ysize()));
338
30.6k
      if (zerofill) ZeroFillImage(&gc.plane);
339
30.6k
      gc.hshift = fc.hshift;
340
30.6k
      gc.vshift = fc.vshift;
341
30.6k
      gi.channel.emplace_back(std::move(gc));
342
30.6k
    }
343
30.6k
  }
344
27.8k
  if (zerofill && use_full_image) return true;
345
  // Return early if there's nothing to decode. Otherwise there might be
346
  // problems later (in ModularImageToDecodedRect).
347
27.8k
  if (gi.channel.empty()) {
348
21.8k
    if (dec_state && should_run_pipeline) {
349
10.1k
      const auto* metadata = frame_header.nonserialized_metadata;
350
10.1k
      if (do_color || metadata->m.num_extra_channels > 0) {
351
        // Signal to FrameDecoder that we do not have some of the required input
352
        // for the render pipeline.
353
3.97k
        *should_run_pipeline = false;
354
3.97k
      }
355
10.1k
    }
356
21.8k
    JXL_DEBUG_V(6, "Nothing to decode, returning early.");
357
21.8k
    return true;
358
21.8k
  }
359
6.02k
  ModularOptions options;
360
6.03k
  if (!zerofill) {
361
6.03k
    auto status = ModularGenericDecompress(
362
6.03k
        reader, gi, /*header=*/nullptr, stream.ID(frame_dim), &options,
363
6.03k
        /*undo_transforms=*/true, &tree, &code, &context_map, allow_truncated);
364
6.05k
    if (!allow_truncated) JXL_RETURN_IF_ERROR(status);
365
5.97k
    if (status.IsFatalError()) return status;
366
5.97k
  }
367
  // Undo global transforms that have been pushed to the group level
368
5.96k
  if (!use_full_image) {
369
3.33k
    JXL_ENSURE(render_pipeline_input);
370
3.33k
    for (const auto& t : global_transform) {
371
1.88k
      JXL_RETURN_IF_ERROR(t.Inverse(gi, global_header.wp_header));
372
1.88k
    }
373
3.33k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
374
3.33k
        frame_header, gi, dec_state, nullptr, *render_pipeline_input,
375
3.33k
        Rect(0, 0, gi.w, gi.h)));
376
3.33k
    return true;
377
3.33k
  }
378
2.62k
  int gic = 0;
379
30.3k
  for (c = beginc; c < full_image.channel.size(); c++) {
380
27.6k
    Channel& fc = full_image.channel[c];
381
27.6k
    int shift = std::min(fc.hshift, fc.vshift);
382
27.6k
    if (shift > maxShift) continue;
383
25.9k
    if (shift < minShift) continue;
384
18.0k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
385
18.0k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
386
18.0k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
387
18.0k
    JXL_ENSURE(use_full_image);
388
18.0k
    JXL_RETURN_IF_ERROR(
389
18.0k
        CopyImageTo(/*rect_from=*/Rect(0, 0, r.xsize(), r.ysize()),
390
18.0k
                    /*from=*/gi.channel[gic].plane,
391
18.0k
                    /*rect_to=*/r, /*to=*/&fc.plane));
392
18.0k
    gic++;
393
18.0k
  }
394
2.62k
  return true;
395
2.62k
}
396
397
Status ModularFrameDecoder::DecodeVarDCTDC(const FrameHeader& frame_header,
398
                                           size_t group_id, BitReader* reader,
399
5.91k
                                           PassesDecoderState* dec_state) {
400
5.91k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
401
5.91k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
402
5.91k
  JXL_DEBUG_V(6, "Decoding VarDCT DC with rect %s", Description(r).c_str());
403
  // TODO(eustas): investigate if we could reduce the impact of
404
  //               EvalRationalPolynomial; generally speaking, the limit is
405
  //               2**(128/(3*magic)), where 128 comes from IEEE 754 exponent,
406
  //               3 comes from XybToRgb that cubes the values, and "magic" is
407
  //               the sum of all other contributions. 2**18 is known to lead
408
  //               to NaN on input found by fuzzing (see commit message).
409
5.91k
  JXL_ASSIGN_OR_RETURN(Image image,
410
5.91k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
411
5.91k
                                     full_image.bitdepth, 3));
412
5.91k
  size_t stream_id = ModularStreamId::VarDCTDC(group_id).ID(frame_dim);
413
5.91k
  reader->Refill();
414
5.91k
  size_t extra_precision = reader->ReadFixedBits<2>();
415
5.91k
  float mul = 1.0f / (1 << extra_precision);
416
5.91k
  ModularOptions options;
417
23.6k
  for (size_t c = 0; c < 3; c++) {
418
17.7k
    Channel& ch = image.channel[c < 2 ? c ^ 1 : c];
419
17.7k
    ch.w >>= frame_header.chroma_subsampling.HShift(c);
420
17.7k
    ch.h >>= frame_header.chroma_subsampling.VShift(c);
421
17.7k
    JXL_RETURN_IF_ERROR(ch.shrink());
422
17.7k
  }
423
5.91k
  if (!ModularGenericDecompress(
424
5.91k
          reader, image, /*header=*/nullptr, stream_id, &options,
425
5.91k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
426
7
    return JXL_FAILURE("Failed to decode VarDCT DC group (DC group id %d)",
427
7
                       static_cast<int>(group_id));
428
7
  }
429
5.91k
  DequantDC(r, &dec_state->shared_storage.dc_storage,
430
5.91k
            &dec_state->shared_storage.quant_dc, image,
431
5.91k
            dec_state->shared->quantizer.MulDC(), mul,
432
5.91k
            dec_state->shared->cmap.base().DCFactors(),
433
5.91k
            frame_header.chroma_subsampling, dec_state->shared->block_ctx_map);
434
5.91k
  return true;
435
5.91k
}
436
437
Status ModularFrameDecoder::DecodeAcMetadata(const FrameHeader& frame_header,
438
                                             size_t group_id, BitReader* reader,
439
5.91k
                                             PassesDecoderState* dec_state) {
440
5.91k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
441
5.91k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
442
5.91k
  JXL_DEBUG_V(6, "Decoding AcMetadata with rect %s", Description(r).c_str());
443
5.91k
  size_t upper_bound = r.xsize() * r.ysize();
444
5.91k
  reader->Refill();
445
5.91k
  size_t count = reader->ReadBits(CeilLog2Nonzero(upper_bound)) + 1;
446
5.91k
  size_t stream_id = ModularStreamId::ACMetadata(group_id).ID(frame_dim);
447
  // YToX, YToB, ACS + QF, EPF
448
5.91k
  JXL_ASSIGN_OR_RETURN(Image image,
449
5.91k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
450
5.91k
                                     full_image.bitdepth, 4));
451
5.91k
  static_assert(kColorTileDimInBlocks == 8, "Color tile size changed");
452
5.91k
  Rect cr(r.x0() >> 3, r.y0() >> 3, (r.xsize() + 7) >> 3, (r.ysize() + 7) >> 3);
453
5.91k
  JXL_ASSIGN_OR_RETURN(
454
5.91k
      image.channel[0],
455
5.91k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
456
5.91k
  JXL_ASSIGN_OR_RETURN(
457
5.91k
      image.channel[1],
458
5.91k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
459
5.91k
  JXL_ASSIGN_OR_RETURN(image.channel[2],
460
5.91k
                       Channel::Create(memory_manager, count, 2, 0, 0));
461
5.91k
  ModularOptions options;
462
5.91k
  if (!ModularGenericDecompress(
463
5.91k
          reader, image, /*header=*/nullptr, stream_id, &options,
464
5.91k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
465
7
    return JXL_FAILURE("Failed to decode AC metadata");
466
7
  }
467
5.90k
  JXL_RETURN_IF_ERROR(
468
5.90k
      ConvertPlaneAndClamp(Rect(image.channel[0].plane), image.channel[0].plane,
469
5.90k
                           cr, &dec_state->shared_storage.cmap.ytox_map));
470
5.90k
  JXL_RETURN_IF_ERROR(
471
5.90k
      ConvertPlaneAndClamp(Rect(image.channel[1].plane), image.channel[1].plane,
472
5.90k
                           cr, &dec_state->shared_storage.cmap.ytob_map));
473
5.90k
  size_t num = 0;
474
5.90k
  bool is444 = frame_header.chroma_subsampling.Is444();
475
5.90k
  auto& ac_strategy = dec_state->shared_storage.ac_strategy;
476
5.90k
  size_t xlim = std::min(ac_strategy.xsize(), r.x0() + r.xsize());
477
5.90k
  size_t ylim = std::min(ac_strategy.ysize(), r.y0() + r.ysize());
478
5.90k
  uint32_t local_used_acs = 0;
479
18.0k
  for (size_t iy = 0; iy < r.ysize(); iy++) {
480
12.1k
    size_t y = r.y0() + iy;
481
12.1k
    int32_t* row_qf = r.Row(&dec_state->shared_storage.raw_quant_field, iy);
482
12.1k
    uint8_t* row_epf = r.Row(&dec_state->shared_storage.epf_sharpness, iy);
483
12.1k
    int32_t* row_in_1 = image.channel[2].plane.Row(0);
484
12.1k
    int32_t* row_in_2 = image.channel[2].plane.Row(1);
485
12.1k
    int32_t* row_in_3 = image.channel[3].plane.Row(iy);
486
119k
    for (size_t ix = 0; ix < r.xsize(); ix++) {
487
107k
      size_t x = r.x0() + ix;
488
107k
      int sharpness = row_in_3[ix];
489
107k
      if (sharpness < 0 || sharpness >= LoopFilter::kEpfSharpEntries) {
490
2
        return JXL_FAILURE("Corrupted sharpness field");
491
2
      }
492
107k
      row_epf[ix] = sharpness;
493
107k
      if (ac_strategy.IsValid(x, y)) {
494
23.6k
        continue;
495
23.6k
      }
496
497
84.0k
      if (num >= count) return JXL_FAILURE("Corrupted stream");
498
499
84.0k
      if (!AcStrategy::IsRawStrategyValid(row_in_1[num])) {
500
0
        return JXL_FAILURE("Invalid AC strategy");
501
0
      }
502
84.0k
      local_used_acs |= 1u << row_in_1[num];
503
84.0k
      AcStrategy acs = AcStrategy::FromRawStrategy(row_in_1[num]);
504
84.0k
      if ((acs.covered_blocks_x() > 1 || acs.covered_blocks_y() > 1) &&
505
84.0k
          !is444) {
506
0
        return JXL_FAILURE(
507
0
            "AC strategy not compatible with chroma subsampling");
508
0
      }
509
      // Ensure that blocks do not overflow *AC* groups.
510
84.0k
      size_t next_x_ac_block = (x / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
511
84.0k
      size_t next_y_ac_block = (y / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
512
84.0k
      size_t next_x_dct_block = x + acs.covered_blocks_x();
513
84.0k
      size_t next_y_dct_block = y + acs.covered_blocks_y();
514
84.0k
      if (next_x_dct_block > next_x_ac_block || next_x_dct_block > xlim) {
515
1
        return JXL_FAILURE("Invalid AC strategy, x overflow");
516
1
      }
517
84.1k
      if (next_y_dct_block > next_y_ac_block || next_y_dct_block > ylim) {
518
0
        return JXL_FAILURE("Invalid AC strategy, y overflow");
519
0
      }
520
84.0k
      JXL_RETURN_IF_ERROR(
521
84.0k
          ac_strategy.SetNoBoundsCheck(x, y, AcStrategyType(row_in_1[num])));
522
84.0k
      row_qf[ix] = 1 + std::max<int32_t>(0, std::min(Quantizer::kQuantMax - 1,
523
84.0k
                                                     row_in_2[num]));
524
84.0k
      num++;
525
84.0k
    }
526
12.1k
  }
527
5.89k
  dec_state->used_acs |= local_used_acs;
528
5.90k
  if (frame_header.loop_filter.epf_iters > 0) {
529
5.90k
    JXL_RETURN_IF_ERROR(ComputeSigma(frame_header.loop_filter, r, dec_state));
530
5.90k
  }
531
5.89k
  return true;
532
5.89k
}
533
534
Status ModularFrameDecoder::ModularImageToDecodedRect(
535
    const FrameHeader& frame_header, Image& gi, PassesDecoderState* dec_state,
536
    jxl::ThreadPool* pool, RenderPipelineInput& render_pipeline_input,
537
8.86k
    Rect modular_rect) const {
538
8.86k
  const auto* metadata = frame_header.nonserialized_metadata;
539
8.86k
  JXL_ENSURE(gi.transform.empty());
540
541
1.69M
  auto get_row = [&](size_t c, size_t y) {
542
1.69M
    const auto& buffer = render_pipeline_input.GetBuffer(c);
543
1.69M
    return buffer.second.Row(buffer.first, y);
544
1.69M
  };
545
546
8.86k
  size_t c = 0;
547
8.86k
  if (do_color) {
548
8.86k
    const bool rgb_from_gray =
549
8.86k
        metadata->m.color_encoding.IsGray() &&
550
8.86k
        frame_header.color_transform == ColorTransform::kNone;
551
8.86k
    const bool fp = metadata->m.bit_depth.floating_point_sample &&
552
8.86k
                    frame_header.color_transform != ColorTransform::kXYB;
553
35.3k
    for (; c < 3; c++) {
554
26.4k
      double factor = full_image.bitdepth < 32
555
26.4k
                          ? 1.0 / ((1u << full_image.bitdepth) - 1)
556
26.4k
                          : 0;
557
26.4k
      size_t c_in = c;
558
26.4k
      if (frame_header.color_transform == ColorTransform::kXYB) {
559
8.59k
        factor = dec_state->shared->matrices.DCQuants()[c];
560
        // XYB is encoded as YX(B-Y)
561
8.59k
        if (c < 2) c_in = 1 - c;
562
17.9k
      } else if (rgb_from_gray) {
563
14
        c_in = 0;
564
14
      }
565
26.4k
      JXL_ENSURE(c_in < gi.channel.size());
566
26.4k
      Channel& ch_in = gi.channel[c_in];
567
      // TODO(eustas): could we detect it on earlier stage?
568
26.4k
      if (ch_in.w == 0 || ch_in.h == 0) {
569
0
        return JXL_FAILURE("Empty image");
570
0
      }
571
26.4k
      JXL_ENSURE(ch_in.hshift <= 3 && ch_in.vshift <= 3);
572
26.4k
      Rect r = render_pipeline_input.GetBuffer(c).second;
573
26.4k
      Rect mr(modular_rect.x0() >> ch_in.hshift,
574
26.4k
              modular_rect.y0() >> ch_in.vshift,
575
26.4k
              DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
576
26.4k
              DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
577
26.4k
      mr = mr.Crop(ch_in.plane);
578
26.4k
      size_t xsize_shifted = r.xsize();
579
26.4k
      size_t ysize_shifted = r.ysize();
580
26.5k
      if (r.ysize() != mr.ysize() || r.xsize() != mr.xsize()) {
581
0
        return JXL_FAILURE("Dimension mismatch: trying to fit a %" PRIuS
582
0
                           "x%" PRIuS
583
0
                           " modular channel into "
584
0
                           "a %" PRIuS "x%" PRIuS " rect",
585
0
                           mr.xsize(), mr.ysize(), r.xsize(), r.ysize());
586
0
      }
587
26.4k
      if (frame_header.color_transform == ColorTransform::kXYB && c == 2) {
588
2.86k
        JXL_ENSURE(!fp);
589
2.86k
        const auto process_row = [&](const uint32_t task,
590
186k
                                     size_t /* thread */) -> Status {
591
186k
          const size_t y = task;
592
186k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
593
186k
          const pixel_type* const JXL_RESTRICT row_in_Y =
594
186k
              mr.Row(&gi.channel[0].plane, y);
595
186k
          float* const JXL_RESTRICT row_out = get_row(c, y);
596
186k
          HWY_DYNAMIC_DISPATCH(MultiplySum)
597
186k
          (xsize_shifted, row_in, row_in_Y, factor, row_out);
598
186k
          return true;
599
186k
        };
600
2.86k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
601
2.86k
                                      ThreadPool::NoInit, process_row,
602
2.86k
                                      "ModularIntToFloat"));
603
23.6k
      } else if (fp) {
604
3.42k
        int bits = metadata->m.bit_depth.bits_per_sample;
605
3.42k
        int exp_bits = metadata->m.bit_depth.exponent_bits_per_sample;
606
3.42k
        const auto process_row = [&](const uint32_t task,
607
63.7k
                                     size_t /* thread */) -> Status {
608
63.7k
          const size_t y = task;
609
63.7k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
610
63.7k
          if (rgb_from_gray) {
611
9.21k
            for (size_t cc = 0; cc < 3; cc++) {
612
6.91k
              float* const JXL_RESTRICT row_out = get_row(cc, y);
613
6.91k
              JXL_RETURN_IF_ERROR(
614
6.91k
                  int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
615
6.91k
            }
616
61.4k
          } else {
617
61.4k
            float* const JXL_RESTRICT row_out = get_row(c, y);
618
61.4k
            JXL_RETURN_IF_ERROR(
619
61.4k
                int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
620
61.4k
          }
621
63.7k
          return true;
622
63.7k
        };
623
3.42k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
624
3.42k
                                      ThreadPool::NoInit, process_row,
625
3.42k
                                      "ModularIntToFloat_losslessfloat"));
626
20.2k
      } else {
627
20.2k
        const auto process_row = [&](const uint32_t task,
628
1.45M
                                     size_t /* thread */) -> Status {
629
1.45M
          const size_t y = task;
630
1.45M
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
631
1.45M
          if (rgb_from_gray) {
632
1.31k
            if (full_image.bitdepth < 23) {
633
1.31k
              HWY_DYNAMIC_DISPATCH(RgbFromSingle)
634
1.31k
              (xsize_shifted, row_in, factor, get_row(0, y), get_row(1, y),
635
1.31k
               get_row(2, y));
636
1.31k
            } else {
637
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
638
0
                                       get_row(0, y));
639
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
640
0
                                       get_row(1, y));
641
0
              SingleFromSingleAccurate(xsize_shifted, row_in, factor,
642
0
                                       get_row(2, y));
643
0
            }
644
1.44M
          } else {
645
1.44M
            float* const JXL_RESTRICT row_out = get_row(c, y);
646
1.44M
            if (full_image.bitdepth < 23) {
647
1.37M
              HWY_DYNAMIC_DISPATCH(SingleFromSingle)
648
1.37M
              (xsize_shifted, row_in, factor, row_out);
649
1.37M
            } else {
650
70.0k
              SingleFromSingleAccurate(xsize_shifted, row_in, factor, row_out);
651
70.0k
            }
652
1.44M
          }
653
1.45M
          return true;
654
1.45M
        };
655
20.2k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
656
20.2k
                                      ThreadPool::NoInit, process_row,
657
20.2k
                                      "ModularIntToFloat"));
658
20.2k
      }
659
26.4k
      if (rgb_from_gray) {
660
14
        break;
661
14
      }
662
26.4k
    }
663
8.86k
    if (rgb_from_gray) {
664
14
      c = 1;
665
14
    }
666
8.86k
  }
667
8.86k
  size_t num_extra_channels = metadata->m.num_extra_channels;
668
10.8k
  for (size_t ec = 0; ec < num_extra_channels; ec++, c++) {
669
2.00k
    const ExtraChannelInfo& eci = metadata->m.extra_channel_info[ec];
670
2.00k
    int bits = eci.bit_depth.bits_per_sample;
671
2.00k
    int exp_bits = eci.bit_depth.exponent_bits_per_sample;
672
2.00k
    bool fp = eci.bit_depth.floating_point_sample;
673
2.00k
    JXL_ENSURE(fp || bits < 32);
674
2.00k
    const double factor = fp ? 0 : (1.0 / ((1u << bits) - 1));
675
2.00k
    JXL_ENSURE(c < gi.channel.size());
676
2.00k
    Channel& ch_in = gi.channel[c];
677
2.00k
    const auto& buffer = render_pipeline_input.GetBuffer(3 + ec);
678
2.00k
    Rect r = buffer.second;
679
2.00k
    Rect mr(modular_rect.x0() >> ch_in.hshift,
680
2.00k
            modular_rect.y0() >> ch_in.vshift,
681
2.00k
            DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
682
2.00k
            DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
683
2.00k
    mr = mr.Crop(ch_in.plane);
684
2.00k
    if (r.ysize() != mr.ysize() || r.xsize() != mr.xsize()) {
685
0
      return JXL_FAILURE("Dimension mismatch: trying to fit a %" PRIuS
686
0
                         "x%" PRIuS
687
0
                         " modular channel into "
688
0
                         "a %" PRIuS "x%" PRIuS " rect",
689
0
                         mr.xsize(), mr.ysize(), r.xsize(), r.ysize());
690
0
    }
691
170k
    for (size_t y = 0; y < r.ysize(); ++y) {
692
168k
      float* const JXL_RESTRICT row_out = r.Row(buffer.first, y);
693
168k
      const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
694
168k
      if (fp) {
695
0
        JXL_RETURN_IF_ERROR(
696
0
            int_to_float(row_in, row_out, r.xsize(), bits, exp_bits));
697
168k
      } else {
698
168k
        if (full_image.bitdepth < 23) {
699
167k
          HWY_DYNAMIC_DISPATCH(SingleFromSingle)
700
167k
          (r.xsize(), row_in, factor, row_out);
701
167k
        } else {
702
509
          SingleFromSingleAccurate(r.xsize(), row_in, factor, row_out);
703
509
        }
704
168k
      }
705
168k
    }
706
2.00k
  }
707
8.86k
  return true;
708
8.86k
}
709
710
Status ModularFrameDecoder::FinalizeDecoding(const FrameHeader& frame_header,
711
                                             PassesDecoderState* dec_state,
712
                                             jxl::ThreadPool* pool,
713
10.5k
                                             bool inplace) {
714
10.5k
  if (!use_full_image) return true;
715
4.63k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
716
4.63k
  Image gi{memory_manager};
717
4.63k
  if (inplace) {
718
4.63k
    gi = std::move(full_image);
719
4.63k
  } else {
720
0
    JXL_ASSIGN_OR_RETURN(gi, Image::Clone(full_image));
721
0
  }
722
4.63k
  size_t xsize = gi.w;
723
4.63k
  size_t ysize = gi.h;
724
725
4.63k
  JXL_DEBUG_V(3, "Finalizing decoding for modular image: %s",
726
4.63k
              gi.DebugString().c_str());
727
728
  // Don't use threads if total image size is smaller than a group
729
4.63k
  if (xsize * ysize < frame_dim.group_dim * frame_dim.group_dim) pool = nullptr;
730
731
  // Undo the global transforms
732
4.63k
  gi.undo_transforms(global_header.wp_header, pool);
733
4.63k
  JXL_ENSURE(global_transform.empty());
734
4.63k
  if (gi.error) return JXL_FAILURE("Undoing transforms failed");
735
736
10.1k
  for (size_t i = 0; i < dec_state->shared->frame_dim.num_groups; i++) {
737
5.52k
    dec_state->render_pipeline->ClearDone(i);
738
5.52k
  }
739
740
4.63k
  const auto init = [&](size_t num_threads) -> Status {
741
4.63k
    bool use_group_ids = (frame_header.encoding == FrameEncoding::kVarDCT ||
742
4.63k
                          (frame_header.flags & FrameHeader::kNoise));
743
4.63k
    JXL_RETURN_IF_ERROR(dec_state->render_pipeline->PrepareForThreads(
744
4.63k
        num_threads, use_group_ids));
745
4.63k
    return true;
746
4.63k
  };
747
4.63k
  const auto process_group = [&](const uint32_t group,
748
5.52k
                                 size_t thread_id) -> Status {
749
5.52k
    RenderPipelineInput input =
750
5.52k
        dec_state->render_pipeline->GetInputBuffers(group, thread_id);
751
5.52k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
752
5.52k
        frame_header, gi, dec_state, nullptr, input,
753
5.52k
        dec_state->shared->frame_dim.GroupRect(group)));
754
5.52k
    JXL_RETURN_IF_ERROR(input.Done());
755
5.52k
    return true;
756
5.52k
  };
757
4.63k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0,
758
4.63k
                                dec_state->shared->frame_dim.num_groups, init,
759
4.63k
                                process_group, "ModularToRect"));
760
4.63k
  return true;
761
4.63k
}
762
763
static constexpr const float kAlmostZero = 1e-8f;
764
765
Status ModularFrameDecoder::DecodeQuantTable(
766
    JxlMemoryManager* memory_manager, size_t required_size_x,
767
    size_t required_size_y, BitReader* br, QuantEncoding* encoding, size_t idx,
768
0
    ModularFrameDecoder* modular_frame_decoder) {
769
0
  JXL_RETURN_IF_ERROR(F16Coder::Read(br, &encoding->qraw.qtable_den));
770
0
  if (encoding->qraw.qtable_den < kAlmostZero) {
771
    // qtable[] values are already checked for <= 0 so the denominator may not
772
    // be negative.
773
0
    return JXL_FAILURE("Invalid qtable_den: value too small");
774
0
  }
775
0
  JXL_ASSIGN_OR_RETURN(
776
0
      Image image,
777
0
      Image::Create(memory_manager, required_size_x, required_size_y, 8, 3));
778
0
  ModularOptions options;
779
0
  if (modular_frame_decoder) {
780
0
    JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx));
781
0
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(
782
0
        br, image, /*header=*/nullptr, qt.ID(modular_frame_decoder->frame_dim),
783
0
        &options, /*undo_transforms=*/true, &modular_frame_decoder->tree,
784
0
        &modular_frame_decoder->code, &modular_frame_decoder->context_map));
785
0
  } else {
786
0
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(br, image, /*header=*/nullptr,
787
0
                                                 0, &options,
788
0
                                                 /*undo_transforms=*/true));
789
0
  }
790
0
  if (!encoding->qraw.qtable) {
791
0
    encoding->qraw.qtable =
792
0
        new std::vector<int>(required_size_x * required_size_y * 3);
793
0
  } else {
794
0
    JXL_ENSURE(encoding->qraw.qtable->size() ==
795
0
               required_size_x * required_size_y * 3);
796
0
  }
797
0
  int* qtable = encoding->qraw.qtable->data();
798
0
  for (size_t c = 0; c < 3; c++) {
799
0
    for (size_t y = 0; y < required_size_y; y++) {
800
0
      int32_t* JXL_RESTRICT row = image.channel[c].Row(y);
801
0
      for (size_t x = 0; x < required_size_x; x++) {
802
0
        qtable[c * required_size_x * required_size_y + y * required_size_x +
803
0
               x] = row[x];
804
0
        if (row[x] <= 0) {
805
0
          return JXL_FAILURE("Invalid raw quantization table");
806
0
        }
807
0
      }
808
0
    }
809
0
  }
810
0
  return true;
811
0
}
812
813
}  // namespace jxl
814
#endif  // HWY_ONCE