Coverage Report

Created: 2025-08-12 07:37

/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
742k
                 const float factor, float* const JXL_RESTRICT row_out) {
65
742k
  const HWY_FULL(float) df;
66
742k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
67
742k
  const auto factor_v = Set(df, factor);
68
15.2M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
69
14.5M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
70
14.5M
    const auto out = Mul(ConvertTo(df, in), factor_v);
71
14.5M
    Store(out, df, row_out + x);
72
14.5M
  }
73
742k
}
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
742k
                 const float factor, float* const JXL_RESTRICT row_out) {
65
742k
  const HWY_FULL(float) df;
66
742k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
67
742k
  const auto factor_v = Set(df, factor);
68
15.2M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
69
14.5M
    const auto in = Add(Load(di, row_in + x), Load(di, row_in_Y + x));
70
14.5M
    const auto out = Mul(ConvertTo(df, in), factor_v);
71
14.5M
    Store(out, df, row_out + x);
72
14.5M
  }
73
742k
}
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
45.8k
                   float* out_b) {
79
45.8k
  const HWY_FULL(float) df;
80
45.8k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
81
82
45.8k
  const auto factor_v = Set(df, factor);
83
567k
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
84
521k
    const auto in = Load(di, row_in + x);
85
521k
    const auto out = Mul(ConvertTo(df, in), factor_v);
86
521k
    Store(out, df, out_r + x);
87
521k
    Store(out, df, out_g + x);
88
521k
    Store(out, df, out_b + x);
89
521k
  }
90
45.8k
}
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
45.8k
                   float* out_b) {
79
45.8k
  const HWY_FULL(float) df;
80
45.8k
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
81
82
45.8k
  const auto factor_v = Set(df, factor);
83
567k
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
84
521k
    const auto in = Load(di, row_in + x);
85
521k
    const auto out = Mul(ConvertTo(df, in), factor_v);
86
521k
    Store(out, df, out_r + x);
87
521k
    Store(out, df, out_g + x);
88
521k
    Store(out, df, out_b + x);
89
521k
  }
90
45.8k
}
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.93M
                      const float factor, float* row_out) {
95
1.93M
  const HWY_FULL(float) df;
96
1.93M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
97
98
1.93M
  const auto factor_v = Set(df, factor);
99
35.0M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
100
33.0M
    const auto in = Load(di, row_in + x);
101
33.0M
    const auto out = Mul(ConvertTo(df, in), factor_v);
102
33.0M
    Store(out, df, row_out + x);
103
33.0M
  }
104
1.93M
}
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.93M
                      const float factor, float* row_out) {
95
1.93M
  const HWY_FULL(float) df;
96
1.93M
  const Rebind<pixel_type, HWY_FULL(float)> di;  // assumes pixel_type <= float
97
98
1.93M
  const auto factor_v = Set(df, factor);
99
35.0M
  for (size_t x = 0; x < xsize; x += Lanes(di)) {
100
33.0M
    const auto in = Load(di, row_in + x);
101
33.0M
    const auto out = Mul(ConvertTo(df, in), factor_v);
102
33.0M
    Store(out, df, row_out + x);
103
33.0M
  }
104
1.93M
}
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
61.8k
                              const double factor, float* row_out) {
121
15.3M
  for (size_t x = 0; x < xsize; x++) {
122
15.2M
    row_out[x] = row_in[x] * factor;
123
15.2M
  }
124
61.8k
}
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
114k
                    const int bits, const int exp_bits) {
131
114k
  static_assert(sizeof(pixel_type) == sizeof(float), "32-bit input is assumed");
132
114k
  if (bits == 32) {
133
66.0k
    JXL_ENSURE(exp_bits == 8);
134
66.0k
    memcpy(row_out, row_in, xsize * sizeof(float));
135
66.0k
    return true;
136
66.0k
  }
137
48.8k
  int exp_bias = (1 << (exp_bits - 1)) - 1;
138
48.8k
  int sign_shift = bits - 1;
139
48.8k
  int mant_bits = bits - exp_bits - 1;
140
48.8k
  int mant_shift = 23 - mant_bits;
141
1.73M
  for (size_t x = 0; x < xsize; ++x) {
142
1.68M
    uint32_t f;
143
1.68M
    memcpy(&f, &row_in[x], 4);
144
1.68M
    int signbit = (f >> sign_shift);
145
1.68M
    f &= (1 << sign_shift) - 1;
146
1.68M
    if (f == 0) {
147
754k
      row_out[x] = (signbit ? -0.f : 0.f);
148
754k
      continue;
149
754k
    }
150
933k
    int exp = (f >> mant_bits);
151
933k
    int mantissa = (f & ((1 << mant_bits) - 1));
152
933k
    mantissa <<= mant_shift;
153
    // Try to normalize only if there is space for maneuver.
154
933k
    if (exp == 0 && exp_bits < 8) {
155
      // subnormal number
156
2.23M
      while ((mantissa & 0x800000) == 0) {
157
2.12M
        mantissa <<= 1;
158
2.12M
        exp--;
159
2.12M
      }
160
109k
      exp++;
161
      // remove leading 1 because it is implicit now
162
109k
      mantissa &= 0x7fffff;
163
109k
    }
164
933k
    exp -= exp_bias;
165
    // broke up the arbitrary float into its parts, now reassemble into
166
    // binary32
167
933k
    exp += 127;
168
933k
    JXL_ENSURE(exp >= 0);
169
933k
    f = (signbit ? 0x80000000 : 0);
170
933k
    f |= (exp << 23);
171
933k
    f |= mantissa;
172
933k
    memcpy(&row_out[x], &f, 4);
173
933k
  }
174
48.8k
  return true;
175
48.8k
}
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
24.1k
                                             bool allow_truncated_group) {
204
24.1k
  JxlMemoryManager* memory_manager = this->memory_manager();
205
24.1k
  bool decode_color = frame_header.encoding == FrameEncoding::kModular;
206
24.1k
  const auto& metadata = frame_header.nonserialized_metadata->m;
207
24.1k
  bool is_gray = metadata.color_encoding.IsGray();
208
24.1k
  size_t nb_chans = 3;
209
24.1k
  if (is_gray && frame_header.color_transform == ColorTransform::kNone) {
210
399
    nb_chans = 1;
211
399
  }
212
24.1k
  do_color = decode_color;
213
24.1k
  size_t nb_extra = metadata.extra_channel_info.size();
214
24.1k
  bool has_tree = static_cast<bool>(reader->ReadBits(1));
215
24.1k
  if (!allow_truncated_group ||
216
24.1k
      reader->TotalBitsConsumed() < reader->TotalBytes() * kBitsPerByte) {
217
24.1k
    if (has_tree) {
218
7.37k
      size_t tree_size_limit =
219
7.37k
          std::min(static_cast<size_t>(1 << 22),
220
7.37k
                   1024 + frame_dim.xsize * frame_dim.ysize *
221
7.37k
                              (nb_chans + nb_extra) / 16);
222
7.37k
      JXL_RETURN_IF_ERROR(
223
7.37k
          DecodeTree(memory_manager, reader, &tree, tree_size_limit));
224
7.33k
      JXL_RETURN_IF_ERROR(DecodeHistograms(
225
7.33k
          memory_manager, reader, (tree.size() + 1) / 2, &code, &context_map));
226
7.33k
    }
227
24.1k
  }
228
24.0k
  if (!do_color) nb_chans = 0;
229
230
24.0k
  bool fp = metadata.bit_depth.floating_point_sample;
231
232
  // bits_per_sample is just metadata for XYB images.
233
24.0k
  if (metadata.bit_depth.bits_per_sample >= 32 && do_color &&
234
24.0k
      frame_header.color_transform != ColorTransform::kXYB) {
235
1.67k
    if (metadata.bit_depth.bits_per_sample == 32 && fp == false) {
236
0
      return JXL_FAILURE("uint32_t not supported in dec_modular");
237
1.67k
    } else if (metadata.bit_depth.bits_per_sample > 32) {
238
0
      return JXL_FAILURE("bits_per_sample > 32 not supported");
239
0
    }
240
1.67k
  }
241
242
48.1k
  JXL_ASSIGN_OR_RETURN(
243
48.1k
      Image gi,
244
48.1k
      Image::Create(memory_manager, frame_dim.xsize, frame_dim.ysize,
245
48.1k
                    metadata.bit_depth.bits_per_sample, nb_chans + nb_extra));
246
247
48.1k
  all_same_shift = true;
248
48.1k
  if (frame_header.color_transform == ColorTransform::kYCbCr) {
249
12.9k
    for (size_t c = 0; c < nb_chans; c++) {
250
9.65k
      gi.channel[c].hshift = frame_header.chroma_subsampling.HShift(c);
251
9.65k
      gi.channel[c].vshift = frame_header.chroma_subsampling.VShift(c);
252
9.65k
      size_t xsize_shifted =
253
9.65k
          DivCeil(frame_dim.xsize, 1 << gi.channel[c].hshift);
254
9.65k
      size_t ysize_shifted =
255
9.65k
          DivCeil(frame_dim.ysize, 1 << gi.channel[c].vshift);
256
9.65k
      JXL_RETURN_IF_ERROR(gi.channel[c].shrink(xsize_shifted, ysize_shifted));
257
9.65k
      if (gi.channel[c].hshift != gi.channel[0].hshift ||
258
9.65k
          gi.channel[c].vshift != gi.channel[0].vshift)
259
4.71k
        all_same_shift = false;
260
9.65k
    }
261
3.34k
  }
262
263
32.8k
  for (size_t ec = 0, c = nb_chans; ec < nb_extra; ec++, c++) {
264
8.82k
    size_t ecups = frame_header.extra_channel_upsampling[ec];
265
8.82k
    JXL_RETURN_IF_ERROR(
266
8.82k
        gi.channel[c].shrink(DivCeil(frame_dim.xsize_upsampled, ecups),
267
8.82k
                             DivCeil(frame_dim.ysize_upsampled, ecups)));
268
8.82k
    gi.channel[c].hshift = gi.channel[c].vshift =
269
8.82k
        CeilLog2Nonzero(ecups) - CeilLog2Nonzero(frame_header.upsampling);
270
8.82k
    if (gi.channel[c].hshift != gi.channel[0].hshift ||
271
8.82k
        gi.channel[c].vshift != gi.channel[0].vshift)
272
4.12k
      all_same_shift = false;
273
8.82k
  }
274
275
24.0k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (w/o transforms) %s",
276
24.0k
              gi.DebugString().c_str());
277
24.0k
  ModularOptions options;
278
24.0k
  options.max_chan_size = frame_dim.group_dim;
279
24.0k
  options.group_dim = frame_dim.group_dim;
280
24.0k
  Status dec_status = ModularGenericDecompress(
281
24.0k
      reader, gi, &global_header, ModularStreamId::Global().ID(frame_dim),
282
24.0k
      &options,
283
24.0k
      /*undo_transforms=*/false, &tree, &code, &context_map,
284
24.0k
      allow_truncated_group);
285
24.0k
  if (!allow_truncated_group) JXL_RETURN_IF_ERROR(dec_status);
286
23.9k
  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
23.9k
  have_something = false;
292
172k
  for (size_t c = 0; c < gi.channel.size(); c++) {
293
148k
    Channel& gic = gi.channel[c];
294
148k
    if (c >= gi.nb_meta_channels && gic.w <= frame_dim.group_dim &&
295
148k
        gic.h <= frame_dim.group_dim)
296
143k
      have_something = true;
297
148k
  }
298
  // move global transforms to groups if possible
299
23.9k
  if (!have_something && all_same_shift) {
300
4.35k
    if (gi.transform.size() == 1 && gi.transform[0].id == TransformId::kRCT) {
301
22
      global_transform = gi.transform;
302
22
      gi.transform.clear();
303
      // TODO(jon): also move no-delta-palette out (trickier though)
304
22
    }
305
4.35k
  }
306
23.9k
  full_image = std::move(gi);
307
23.9k
  JXL_DEBUG_V(6, "DecodeGlobalInfo: full_image (with transforms) %s",
308
23.9k
              full_image.DebugString().c_str());
309
23.9k
  return dec_status;
310
23.9k
}
311
312
23.8k
void ModularFrameDecoder::MaybeDropFullImage() {
313
23.8k
  if (full_image.transform.empty() && !have_something && all_same_shift) {
314
4.23k
    use_full_image = false;
315
4.23k
    JXL_DEBUG_V(6, "Dropping full image");
316
4.23k
    for (auto& ch : full_image.channel) {
317
      // keep metadata on channels around, but dealloc their planes
318
636
      ch.plane = Plane<pixel_type>();
319
636
    }
320
4.23k
  }
321
23.8k
}
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
52.2k
    bool allow_truncated, bool* should_run_pipeline) {
328
52.2k
  JXL_DEBUG_V(6, "Decoding %s with rect %s and shift bracket %d..%d %s",
329
52.2k
              stream.DebugString().c_str(), Description(rect).c_str(), minShift,
330
52.2k
              maxShift, zerofill ? "using zerofill" : "");
331
52.2k
  JXL_ENSURE(stream.kind == ModularStreamId::Kind::ModularDC ||
332
52.2k
             stream.kind == ModularStreamId::Kind::ModularAC);
333
52.2k
  const size_t xsize = rect.xsize();
334
52.2k
  const size_t ysize = rect.ysize();
335
52.2k
  JXL_ASSIGN_OR_RETURN(Image gi, Image::Create(memory_manager_, xsize, ysize,
336
52.2k
                                               full_image.bitdepth, 0));
337
  // start at the first bigger-than-groupsize non-metachannel
338
52.2k
  size_t c = full_image.nb_meta_channels;
339
352k
  for (; c < full_image.channel.size(); c++) {
340
305k
    Channel& fc = full_image.channel[c];
341
305k
    if (fc.w > frame_dim.group_dim || fc.h > frame_dim.group_dim) break;
342
305k
  }
343
52.2k
  size_t beginc = c;
344
84.8k
  for (; c < full_image.channel.size(); c++) {
345
32.5k
    Channel& fc = full_image.channel[c];
346
32.5k
    int shift = std::min(fc.hshift, fc.vshift);
347
32.5k
    if (shift > maxShift) continue;
348
30.9k
    if (shift < minShift) continue;
349
14.9k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
350
14.9k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
351
14.9k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
352
14.7k
    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
14.7k
    } else {
358
14.7k
      JXL_ASSIGN_OR_RETURN(
359
14.7k
          Channel gc, Channel::Create(memory_manager_, r.xsize(), r.ysize()));
360
14.7k
      if (zerofill) ZeroFillImage(&gc.plane);
361
14.7k
      gc.hshift = fc.hshift;
362
14.7k
      gc.vshift = fc.vshift;
363
14.7k
      gi.channel.emplace_back(std::move(gc));
364
14.7k
    }
365
14.7k
  }
366
52.2k
  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
52.2k
  if (gi.channel.empty()) {
370
49.9k
    if (dec_state && should_run_pipeline) {
371
26.1k
      const auto* metadata = frame_header.nonserialized_metadata;
372
26.1k
      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.0k
        *should_run_pipeline = false;
376
22.0k
      }
377
26.1k
    }
378
49.9k
    JXL_DEBUG_V(6, "Nothing to decode, returning early.");
379
49.9k
    return true;
380
49.9k
  }
381
2.35k
  ModularOptions options;
382
2.35k
  if (!zerofill) {
383
2.35k
    auto status = ModularGenericDecompress(
384
2.35k
        reader, gi, /*header=*/nullptr, stream.ID(frame_dim), &options,
385
2.35k
        /*undo_transforms=*/true, &tree, &code, &context_map, allow_truncated);
386
2.35k
    if (!allow_truncated) JXL_RETURN_IF_ERROR(status);
387
2.30k
    if (status.IsFatalError()) return status;
388
2.30k
  }
389
  // Undo global transforms that have been pushed to the group level
390
2.30k
  if (!use_full_image) {
391
477
    JXL_ENSURE(render_pipeline_input);
392
477
    for (const auto& t : global_transform) {
393
78
      JXL_RETURN_IF_ERROR(t.Inverse(gi, global_header.wp_header));
394
78
    }
395
477
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
396
477
        frame_header, gi, dec_state, nullptr, *render_pipeline_input,
397
477
        Rect(0, 0, gi.w, gi.h)));
398
477
    return true;
399
477
  }
400
1.83k
  int gic = 0;
401
21.6k
  for (c = beginc; c < full_image.channel.size(); c++) {
402
19.8k
    Channel& fc = full_image.channel[c];
403
19.8k
    int shift = std::min(fc.hshift, fc.vshift);
404
19.8k
    if (shift > maxShift) continue;
405
18.4k
    if (shift < minShift) continue;
406
13.2k
    Rect r(rect.x0() >> fc.hshift, rect.y0() >> fc.vshift,
407
13.2k
           rect.xsize() >> fc.hshift, rect.ysize() >> fc.vshift, fc.w, fc.h);
408
13.2k
    if (r.xsize() == 0 || r.ysize() == 0) continue;
409
13.0k
    JXL_ENSURE(use_full_image);
410
13.0k
    JXL_RETURN_IF_ERROR(
411
13.0k
        CopyImageTo(/*rect_from=*/Rect(0, 0, r.xsize(), r.ysize()),
412
13.0k
                    /*from=*/gi.channel[gic].plane,
413
13.0k
                    /*rect_to=*/r, /*to=*/&fc.plane));
414
13.0k
    gic++;
415
13.0k
  }
416
1.83k
  return true;
417
1.83k
}
418
419
Status ModularFrameDecoder::DecodeVarDCTDC(const FrameHeader& frame_header,
420
                                           size_t group_id, BitReader* reader,
421
4.11k
                                           PassesDecoderState* dec_state) {
422
4.11k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
423
4.11k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
424
4.11k
  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.11k
  JXL_ASSIGN_OR_RETURN(Image image,
432
4.11k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
433
4.11k
                                     full_image.bitdepth, 3));
434
4.11k
  size_t stream_id = ModularStreamId::VarDCTDC(group_id).ID(frame_dim);
435
4.11k
  reader->Refill();
436
4.11k
  size_t extra_precision = reader->ReadFixedBits<2>();
437
4.11k
  float mul = 1.0f / (1 << extra_precision);
438
4.11k
  ModularOptions options;
439
16.4k
  for (size_t c = 0; c < 3; c++) {
440
12.3k
    Channel& ch = image.channel[c < 2 ? c ^ 1 : c];
441
12.3k
    ch.w >>= frame_header.chroma_subsampling.HShift(c);
442
12.3k
    ch.h >>= frame_header.chroma_subsampling.VShift(c);
443
12.3k
    JXL_RETURN_IF_ERROR(ch.shrink());
444
12.3k
  }
445
4.11k
  if (!ModularGenericDecompress(
446
4.11k
          reader, image, /*header=*/nullptr, stream_id, &options,
447
4.11k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
448
36
    return JXL_FAILURE("Failed to decode VarDCT DC group (DC group id %d)",
449
36
                       static_cast<int>(group_id));
450
36
  }
451
4.08k
  DequantDC(r, &dec_state->shared_storage.dc_storage,
452
4.08k
            &dec_state->shared_storage.quant_dc, image,
453
4.08k
            dec_state->shared->quantizer.MulDC(), mul,
454
4.08k
            dec_state->shared->cmap.base().DCFactors(),
455
4.08k
            frame_header.chroma_subsampling, dec_state->shared->block_ctx_map);
456
4.08k
  return true;
457
4.11k
}
458
459
Status ModularFrameDecoder::DecodeAcMetadata(const FrameHeader& frame_header,
460
                                             size_t group_id, BitReader* reader,
461
4.09k
                                             PassesDecoderState* dec_state) {
462
4.09k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
463
4.09k
  const Rect r = dec_state->shared->frame_dim.DCGroupRect(group_id);
464
4.09k
  JXL_DEBUG_V(6, "Decoding AcMetadata with rect %s", Description(r).c_str());
465
4.09k
  size_t upper_bound = r.xsize() * r.ysize();
466
4.09k
  reader->Refill();
467
4.09k
  size_t count = reader->ReadBits(CeilLog2Nonzero(upper_bound)) + 1;
468
4.09k
  size_t stream_id = ModularStreamId::ACMetadata(group_id).ID(frame_dim);
469
  // YToX, YToB, ACS + QF, EPF
470
4.09k
  JXL_ASSIGN_OR_RETURN(Image image,
471
4.09k
                       Image::Create(memory_manager, r.xsize(), r.ysize(),
472
4.09k
                                     full_image.bitdepth, 4));
473
4.09k
  static_assert(kColorTileDimInBlocks == 8, "Color tile size changed");
474
4.09k
  Rect cr(r.x0() >> 3, r.y0() >> 3, (r.xsize() + 7) >> 3, (r.ysize() + 7) >> 3);
475
4.09k
  JXL_ASSIGN_OR_RETURN(
476
4.09k
      image.channel[0],
477
4.09k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
478
4.09k
  JXL_ASSIGN_OR_RETURN(
479
4.09k
      image.channel[1],
480
4.09k
      Channel::Create(memory_manager, cr.xsize(), cr.ysize(), 3, 3));
481
4.09k
  JXL_ASSIGN_OR_RETURN(image.channel[2],
482
4.09k
                       Channel::Create(memory_manager, count, 2, 0, 0));
483
4.09k
  ModularOptions options;
484
4.09k
  if (!ModularGenericDecompress(
485
4.09k
          reader, image, /*header=*/nullptr, stream_id, &options,
486
4.09k
          /*undo_transforms=*/true, &tree, &code, &context_map)) {
487
27
    return JXL_FAILURE("Failed to decode AC metadata");
488
27
  }
489
4.06k
  JXL_RETURN_IF_ERROR(
490
4.06k
      ConvertPlaneAndClamp(Rect(image.channel[0].plane), image.channel[0].plane,
491
4.06k
                           cr, &dec_state->shared_storage.cmap.ytox_map));
492
4.06k
  JXL_RETURN_IF_ERROR(
493
4.06k
      ConvertPlaneAndClamp(Rect(image.channel[1].plane), image.channel[1].plane,
494
4.06k
                           cr, &dec_state->shared_storage.cmap.ytob_map));
495
4.06k
  size_t num = 0;
496
4.06k
  bool is444 = frame_header.chroma_subsampling.Is444();
497
4.06k
  auto& ac_strategy = dec_state->shared_storage.ac_strategy;
498
4.06k
  size_t xlim = std::min(ac_strategy.xsize(), r.x0() + r.xsize());
499
4.06k
  size_t ylim = std::min(ac_strategy.ysize(), r.y0() + r.ysize());
500
4.06k
  uint32_t local_used_acs = 0;
501
18.3k
  for (size_t iy = 0; iy < r.ysize(); iy++) {
502
14.2k
    size_t y = r.y0() + iy;
503
14.2k
    int32_t* row_qf = r.Row(&dec_state->shared_storage.raw_quant_field, iy);
504
14.2k
    uint8_t* row_epf = r.Row(&dec_state->shared_storage.epf_sharpness, iy);
505
14.2k
    int32_t* row_in_1 = image.channel[2].plane.Row(0);
506
14.2k
    int32_t* row_in_2 = image.channel[2].plane.Row(1);
507
14.2k
    int32_t* row_in_3 = image.channel[3].plane.Row(iy);
508
435k
    for (size_t ix = 0; ix < r.xsize(); ix++) {
509
420k
      size_t x = r.x0() + ix;
510
420k
      int sharpness = row_in_3[ix];
511
420k
      if (sharpness < 0 || sharpness >= LoopFilter::kEpfSharpEntries) {
512
6
        return JXL_FAILURE("Corrupted sharpness field");
513
6
      }
514
420k
      row_epf[ix] = sharpness;
515
420k
      if (ac_strategy.IsValid(x, y)) {
516
3.27k
        continue;
517
3.27k
      }
518
519
417k
      if (num >= count) return JXL_FAILURE("Corrupted stream");
520
521
417k
      if (!AcStrategy::IsRawStrategyValid(row_in_1[num])) {
522
5
        return JXL_FAILURE("Invalid AC strategy");
523
5
      }
524
417k
      local_used_acs |= 1u << row_in_1[num];
525
417k
      AcStrategy acs = AcStrategy::FromRawStrategy(row_in_1[num]);
526
417k
      if ((acs.covered_blocks_x() > 1 || acs.covered_blocks_y() > 1) &&
527
417k
          !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
417k
      size_t next_x_ac_block = (x / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
533
417k
      size_t next_y_ac_block = (y / kGroupDimInBlocks + 1) * kGroupDimInBlocks;
534
417k
      size_t next_x_dct_block = x + acs.covered_blocks_x();
535
417k
      size_t next_y_dct_block = y + acs.covered_blocks_y();
536
417k
      if (next_x_dct_block > next_x_ac_block || next_x_dct_block > xlim) {
537
0
        return JXL_FAILURE("Invalid AC strategy, x overflow");
538
0
      }
539
417k
      if (next_y_dct_block > next_y_ac_block || next_y_dct_block > ylim) {
540
1
        return JXL_FAILURE("Invalid AC strategy, y overflow");
541
1
      }
542
417k
      JXL_RETURN_IF_ERROR(
543
417k
          ac_strategy.SetNoBoundsCheck(x, y, AcStrategyType(row_in_1[num])));
544
417k
      row_qf[ix] = 1 + std::max<int32_t>(0, std::min(Quantizer::kQuantMax - 1,
545
417k
                                                     row_in_2[num]));
546
417k
      num++;
547
417k
    }
548
14.2k
  }
549
4.05k
  dec_state->used_acs |= local_used_acs;
550
4.05k
  if (frame_header.loop_filter.epf_iters > 0) {
551
1.45k
    JXL_RETURN_IF_ERROR(ComputeSigma(frame_header.loop_filter, r, dec_state));
552
1.45k
  }
553
4.05k
  return true;
554
4.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
21.0k
    Rect modular_rect) const {
560
21.0k
  const auto* metadata = frame_header.nonserialized_metadata;
561
21.0k
  JXL_ENSURE(gi.transform.empty());
562
563
2.74M
  auto get_row = [&](size_t c, size_t y) {
564
2.74M
    const auto& buffer = render_pipeline_input.GetBuffer(c);
565
2.74M
    return buffer.second.Row(buffer.first, y);
566
2.74M
  };
567
568
21.0k
  size_t c = 0;
569
21.0k
  if (do_color) {
570
21.0k
    const bool rgb_from_gray =
571
21.0k
        metadata->m.color_encoding.IsGray() &&
572
21.0k
        frame_header.color_transform == ColorTransform::kNone;
573
21.0k
    const bool fp = metadata->m.bit_depth.floating_point_sample &&
574
21.0k
                    frame_header.color_transform != ColorTransform::kXYB;
575
82.9k
    for (; c < 3; c++) {
576
62.3k
      double factor = full_image.bitdepth < 32
577
62.3k
                          ? 1.0 / ((1u << full_image.bitdepth) - 1)
578
62.3k
                          : 0;
579
62.3k
      size_t c_in = c;
580
62.3k
      if (frame_header.color_transform == ColorTransform::kXYB) {
581
42.9k
        factor = dec_state->shared->matrices.DCQuants()[c];
582
        // XYB is encoded as YX(B-Y)
583
42.9k
        if (c < 2) c_in = 1 - c;
584
42.9k
      } else if (rgb_from_gray) {
585
430
        c_in = 0;
586
430
      }
587
62.3k
      JXL_ENSURE(c_in < gi.channel.size());
588
62.3k
      Channel& ch_in = gi.channel[c_in];
589
      // TODO(eustas): could we detect it on earlier stage?
590
62.3k
      if (ch_in.w == 0 || ch_in.h == 0) {
591
0
        return JXL_FAILURE("Empty image");
592
0
      }
593
62.3k
      JXL_ENSURE(ch_in.hshift <= 3 && ch_in.vshift <= 3);
594
62.3k
      Rect r = render_pipeline_input.GetBuffer(c).second;
595
62.3k
      Rect mr(modular_rect.x0() >> ch_in.hshift,
596
62.3k
              modular_rect.y0() >> ch_in.vshift,
597
62.3k
              DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
598
62.3k
              DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
599
62.3k
      mr = mr.Crop(ch_in.plane);
600
62.3k
      size_t xsize_shifted = r.xsize();
601
62.3k
      size_t ysize_shifted = r.ysize();
602
62.3k
      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
62.3k
      if (frame_header.color_transform == ColorTransform::kXYB && c == 2) {
610
14.3k
        JXL_ENSURE(!fp);
611
14.3k
        const auto process_row = [&](const uint32_t task,
612
742k
                                     size_t /* thread */) -> Status {
613
742k
          const size_t y = task;
614
742k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
615
742k
          const pixel_type* const JXL_RESTRICT row_in_Y =
616
742k
              mr.Row(&gi.channel[0].plane, y);
617
742k
          float* const JXL_RESTRICT row_out = get_row(c, y);
618
742k
          HWY_DYNAMIC_DISPATCH(MultiplySum)
619
742k
          (xsize_shifted, row_in, row_in_Y, factor, row_out);
620
742k
          return true;
621
742k
        };
622
14.3k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
623
14.3k
                                      ThreadPool::NoInit, process_row,
624
14.3k
                                      "ModularIntToFloat"));
625
47.9k
      } else if (fp) {
626
9.33k
        int bits = metadata->m.bit_depth.bits_per_sample;
627
9.33k
        int exp_bits = metadata->m.bit_depth.exponent_bits_per_sample;
628
9.33k
        const auto process_row = [&](const uint32_t task,
629
110k
                                     size_t /* thread */) -> Status {
630
110k
          const size_t y = task;
631
110k
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
632
110k
          if (rgb_from_gray) {
633
1.42k
            for (size_t cc = 0; cc < 3; cc++) {
634
1.07k
              float* const JXL_RESTRICT row_out = get_row(cc, y);
635
1.07k
              JXL_RETURN_IF_ERROR(
636
1.07k
                  int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
637
1.07k
            }
638
110k
          } else {
639
110k
            float* const JXL_RESTRICT row_out = get_row(c, y);
640
110k
            JXL_RETURN_IF_ERROR(
641
110k
                int_to_float(row_in, row_out, xsize_shifted, bits, exp_bits));
642
110k
          }
643
110k
          return true;
644
110k
        };
645
9.33k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
646
9.33k
                                      ThreadPool::NoInit, process_row,
647
9.33k
                                      "ModularIntToFloat_losslessfloat"));
648
38.6k
      } else {
649
38.6k
        const auto process_row = [&](const uint32_t task,
650
1.80M
                                     size_t /* thread */) -> Status {
651
1.80M
          const size_t y = task;
652
1.80M
          const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
653
1.80M
          if (rgb_from_gray) {
654
45.8k
            if (full_image.bitdepth < 23) {
655
45.8k
              HWY_DYNAMIC_DISPATCH(RgbFromSingle)
656
45.8k
              (xsize_shifted, row_in, factor, get_row(0, y), get_row(1, y),
657
45.8k
               get_row(2, y));
658
45.8k
            } 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.75M
          } else {
667
1.75M
            float* const JXL_RESTRICT row_out = get_row(c, y);
668
1.75M
            if (full_image.bitdepth < 23) {
669
1.72M
              HWY_DYNAMIC_DISPATCH(SingleFromSingle)
670
1.72M
              (xsize_shifted, row_in, factor, row_out);
671
1.72M
            } else {
672
32.7k
              SingleFromSingleAccurate(xsize_shifted, row_in, factor, row_out);
673
32.7k
            }
674
1.75M
          }
675
1.80M
          return true;
676
1.80M
        };
677
38.6k
        JXL_RETURN_IF_ERROR(RunOnPool(pool, 0, ysize_shifted,
678
38.6k
                                      ThreadPool::NoInit, process_row,
679
38.6k
                                      "ModularIntToFloat"));
680
38.6k
      }
681
62.3k
      if (rgb_from_gray) {
682
430
        break;
683
430
      }
684
62.3k
    }
685
21.0k
    if (rgb_from_gray) {
686
430
      c = 1;
687
430
    }
688
21.0k
  }
689
21.0k
  size_t num_extra_channels = metadata->m.num_extra_channels;
690
27.9k
  for (size_t ec = 0; ec < num_extra_channels; ec++, c++) {
691
6.85k
    const ExtraChannelInfo& eci = metadata->m.extra_channel_info[ec];
692
6.85k
    int bits = eci.bit_depth.bits_per_sample;
693
6.85k
    int exp_bits = eci.bit_depth.exponent_bits_per_sample;
694
6.85k
    bool fp = eci.bit_depth.floating_point_sample;
695
6.85k
    JXL_ENSURE(fp || bits < 32);
696
6.85k
    const double factor = fp ? 0 : (1.0 / ((1u << bits) - 1));
697
6.85k
    JXL_ENSURE(c < gi.channel.size());
698
6.85k
    Channel& ch_in = gi.channel[c];
699
6.85k
    const auto& buffer = render_pipeline_input.GetBuffer(3 + ec);
700
6.85k
    Rect r = buffer.second;
701
6.85k
    Rect mr(modular_rect.x0() >> ch_in.hshift,
702
6.85k
            modular_rect.y0() >> ch_in.vshift,
703
6.85k
            DivCeil(modular_rect.xsize(), 1 << ch_in.hshift),
704
6.85k
            DivCeil(modular_rect.ysize(), 1 << ch_in.vshift));
705
6.85k
    mr = mr.Crop(ch_in.plane);
706
6.85k
    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
251k
    for (size_t y = 0; y < r.ysize(); ++y) {
714
245k
      float* const JXL_RESTRICT row_out = r.Row(buffer.first, y);
715
245k
      const pixel_type* const JXL_RESTRICT row_in = mr.Row(&ch_in.plane, y);
716
245k
      if (fp) {
717
3.86k
        JXL_RETURN_IF_ERROR(
718
3.86k
            int_to_float(row_in, row_out, r.xsize(), bits, exp_bits));
719
241k
      } else {
720
241k
        if (full_image.bitdepth < 23) {
721
212k
          HWY_DYNAMIC_DISPATCH(SingleFromSingle)
722
212k
          (r.xsize(), row_in, factor, row_out);
723
212k
        } else {
724
29.1k
          SingleFromSingleAccurate(r.xsize(), row_in, factor, row_out);
725
29.1k
        }
726
241k
      }
727
245k
    }
728
6.85k
  }
729
21.0k
  return true;
730
21.0k
}
731
732
Status ModularFrameDecoder::FinalizeDecoding(const FrameHeader& frame_header,
733
                                             PassesDecoderState* dec_state,
734
                                             jxl::ThreadPool* pool,
735
23.4k
                                             bool inplace) {
736
23.4k
  if (!use_full_image) return true;
737
19.5k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
738
19.5k
  Image gi{memory_manager};
739
19.5k
  if (inplace) {
740
19.5k
    gi = std::move(full_image);
741
19.5k
  } else {
742
0
    JXL_ASSIGN_OR_RETURN(gi, Image::Clone(full_image));
743
0
  }
744
19.5k
  size_t xsize = gi.w;
745
19.5k
  size_t ysize = gi.h;
746
747
19.5k
  JXL_DEBUG_V(3, "Finalizing decoding for modular image: %s",
748
19.5k
              gi.DebugString().c_str());
749
750
  // Don't use threads if total image size is smaller than a group
751
19.5k
  if (xsize * ysize < frame_dim.group_dim * frame_dim.group_dim) pool = nullptr;
752
753
  // Undo the global transforms
754
19.5k
  gi.undo_transforms(global_header.wp_header, pool);
755
19.5k
  JXL_ENSURE(global_transform.empty());
756
19.5k
  if (gi.error) return JXL_FAILURE("Undoing transforms failed");
757
758
40.0k
  for (size_t i = 0; i < dec_state->shared->frame_dim.num_groups; i++) {
759
20.5k
    dec_state->render_pipeline->ClearDone(i);
760
20.5k
  }
761
762
19.5k
  const auto init = [&](size_t num_threads) -> Status {
763
19.5k
    bool use_group_ids = (frame_header.encoding == FrameEncoding::kVarDCT ||
764
19.5k
                          (frame_header.flags & FrameHeader::kNoise));
765
19.5k
    JXL_RETURN_IF_ERROR(dec_state->render_pipeline->PrepareForThreads(
766
19.5k
        num_threads, use_group_ids));
767
19.5k
    return true;
768
19.5k
  };
769
19.5k
  const auto process_group = [&](const uint32_t group,
770
20.5k
                                 size_t thread_id) -> Status {
771
20.5k
    RenderPipelineInput input =
772
20.5k
        dec_state->render_pipeline->GetInputBuffers(group, thread_id);
773
20.5k
    JXL_RETURN_IF_ERROR(ModularImageToDecodedRect(
774
20.5k
        frame_header, gi, dec_state, nullptr, input,
775
20.5k
        dec_state->shared->frame_dim.GroupRect(group)));
776
20.5k
    JXL_RETURN_IF_ERROR(input.Done());
777
20.5k
    return true;
778
20.5k
  };
779
19.5k
  JXL_RETURN_IF_ERROR(RunOnPool(pool, 0,
780
19.5k
                                dec_state->shared->frame_dim.num_groups, init,
781
19.5k
                                process_group, "ModularToRect"));
782
19.5k
  return true;
783
19.5k
}
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
17
    ModularFrameDecoder* modular_frame_decoder) {
791
17
  JXL_RETURN_IF_ERROR(F16Coder::Read(br, &encoding->qraw.qtable_den));
792
17
  if (encoding->qraw.qtable_den < kAlmostZero) {
793
    // qtable[] values are already checked for <= 0 so the denominator may not
794
    // be negative.
795
0
    return JXL_FAILURE("Invalid qtable_den: value too small");
796
0
  }
797
34
  JXL_ASSIGN_OR_RETURN(
798
34
      Image image,
799
34
      Image::Create(memory_manager, required_size_x, required_size_y, 8, 3));
800
34
  ModularOptions options;
801
34
  if (modular_frame_decoder) {
802
17
    JXL_ASSIGN_OR_RETURN(ModularStreamId qt, ModularStreamId::QuantTable(idx));
803
17
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(
804
17
        br, image, /*header=*/nullptr, qt.ID(modular_frame_decoder->frame_dim),
805
17
        &options, /*undo_transforms=*/true, &modular_frame_decoder->tree,
806
17
        &modular_frame_decoder->code, &modular_frame_decoder->context_map));
807
17
  } else {
808
0
    JXL_RETURN_IF_ERROR(ModularGenericDecompress(br, image, /*header=*/nullptr,
809
0
                                                 0, &options,
810
0
                                                 /*undo_transforms=*/true));
811
0
  }
812
15
  if (!encoding->qraw.qtable) {
813
15
    encoding->qraw.qtable =
814
15
        new std::vector<int>(required_size_x * required_size_y * 3);
815
15
  } else {
816
0
    JXL_ENSURE(encoding->qraw.qtable->size() ==
817
0
               required_size_x * required_size_y * 3);
818
0
  }
819
15
  int* qtable = encoding->qraw.qtable->data();
820
39
  for (size_t c = 0; c < 3; c++) {
821
1.00k
    for (size_t y = 0; y < required_size_y; y++) {
822
985
      int32_t* JXL_RESTRICT row = image.channel[c].Row(y);
823
199k
      for (size_t x = 0; x < required_size_x; x++) {
824
198k
        qtable[c * required_size_x * required_size_y + y * required_size_x +
825
198k
               x] = row[x];
826
198k
        if (row[x] <= 0) {
827
12
          return JXL_FAILURE("Invalid raw quantization table");
828
12
        }
829
198k
      }
830
985
    }
831
36
  }
832
3
  return true;
833
15
}
834
835
}  // namespace jxl
836
#endif  // HWY_ONCE