Coverage Report

Created: 2025-06-16 07:00

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