Coverage Report

Created: 2025-11-14 07:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/dec_group.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/dec_group.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <array>
12
#include <cstdint>
13
#include <cstdio>
14
#include <cstdlib>
15
#include <cstring>
16
#include <memory>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/chroma_from_luma.h"
22
#include "lib/jxl/coeff_order_fwd.h"
23
#include "lib/jxl/dct_util.h"
24
#include "lib/jxl/dec_ans.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_ops.h"
29
#include "lib/jxl/jpeg/jpeg_data.h"
30
#include "lib/jxl/render_pipeline/render_pipeline.h"
31
#include "lib/jxl/render_pipeline/render_pipeline_stage.h"
32
33
#undef HWY_TARGET_INCLUDE
34
#define HWY_TARGET_INCLUDE "lib/jxl/dec_group.cc"
35
#include <hwy/foreach_target.h>
36
#include <hwy/highway.h>
37
38
#include "lib/jxl/ac_context.h"
39
#include "lib/jxl/ac_strategy.h"
40
#include "lib/jxl/base/bits.h"
41
#include "lib/jxl/base/common.h"
42
#include "lib/jxl/base/printf_macros.h"
43
#include "lib/jxl/base/rect.h"
44
#include "lib/jxl/base/status.h"
45
#include "lib/jxl/coeff_order.h"
46
#include "lib/jxl/common.h"  // kMaxNumPasses
47
#include "lib/jxl/dec_cache.h"
48
#include "lib/jxl/dec_transforms-inl.h"
49
#include "lib/jxl/dec_xyb.h"
50
#include "lib/jxl/entropy_coder.h"
51
#include "lib/jxl/quant_weights.h"
52
#include "lib/jxl/quantizer-inl.h"
53
#include "lib/jxl/quantizer.h"
54
55
#ifndef LIB_JXL_DEC_GROUP_CC
56
#define LIB_JXL_DEC_GROUP_CC
57
namespace jxl {
58
59
struct AuxOut;
60
61
// Interface for reading groups for DecodeGroupImpl.
62
class GetBlock {
63
 public:
64
  virtual void StartRow(size_t by) = 0;
65
  virtual Status LoadBlock(size_t bx, size_t by, const AcStrategy& acs,
66
                           size_t size, size_t log2_covered_blocks,
67
                           ACPtr block[3], ACType ac_type) = 0;
68
75.7k
  virtual ~GetBlock() {}
69
};
70
71
// Controls whether DecodeGroupImpl renders to pixels or not.
72
enum DrawMode {
73
  // Render to pixels.
74
  kDraw = 0,
75
  // Don't render to pixels.
76
  kDontDraw = 1,
77
};
78
79
}  // namespace jxl
80
#endif  // LIB_JXL_DEC_GROUP_CC
81
82
HWY_BEFORE_NAMESPACE();
83
namespace jxl {
84
namespace HWY_NAMESPACE {
85
86
// These templates are not found via ADL.
87
using hwy::HWY_NAMESPACE::AllFalse;
88
using hwy::HWY_NAMESPACE::Gt;
89
using hwy::HWY_NAMESPACE::Le;
90
using hwy::HWY_NAMESPACE::MaskFromVec;
91
using hwy::HWY_NAMESPACE::Or;
92
using hwy::HWY_NAMESPACE::Rebind;
93
using hwy::HWY_NAMESPACE::ShiftRight;
94
95
using D = HWY_FULL(float);
96
using DU = HWY_FULL(uint32_t);
97
using DI = HWY_FULL(int32_t);
98
using DI16 = Rebind<int16_t, DI>;
99
using DI16_FULL = HWY_CAPPED(int16_t, kDCTBlockSize);
100
constexpr D d;
101
constexpr DI di;
102
constexpr DI16 di16;
103
constexpr DI16_FULL di16_full;
104
105
// TODO(veluca): consider SIMDfying.
106
0
void Transpose8x8InPlace(int32_t* JXL_RESTRICT block) {
107
0
  for (size_t x = 0; x < 8; x++) {
108
0
    for (size_t y = x + 1; y < 8; y++) {
109
0
      std::swap(block[y * 8 + x], block[x * 8 + y]);
110
0
    }
111
0
  }
112
0
}
Unexecuted instantiation: jxl::N_SSE4::Transpose8x8InPlace(int*)
Unexecuted instantiation: jxl::N_AVX2::Transpose8x8InPlace(int*)
Unexecuted instantiation: jxl::N_SSE2::Transpose8x8InPlace(int*)
113
114
template <ACType ac_type>
115
void DequantLane(Vec<D> scaled_dequant_x, Vec<D> scaled_dequant_y,
116
                 Vec<D> scaled_dequant_b,
117
                 const float* JXL_RESTRICT dequant_matrices, size_t size,
118
                 size_t k, Vec<D> x_cc_mul, Vec<D> b_cc_mul,
119
                 const float* JXL_RESTRICT biases, ACPtr qblock[3],
120
115M
                 float* JXL_RESTRICT block) {
121
115M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
115M
  const auto y_mul =
123
115M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
115M
  const auto b_mul =
125
115M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
115M
  Vec<DI> quantized_x_int;
128
115M
  Vec<DI> quantized_y_int;
129
115M
  Vec<DI> quantized_b_int;
130
115M
  if (ac_type == ACType::k16) {
131
3.48M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
3.48M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
3.48M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
112M
  } else {
135
112M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
112M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
112M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
112M
  }
139
140
115M
  const auto dequant_x_cc =
141
115M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
115M
  const auto dequant_y =
143
115M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
115M
  const auto dequant_b_cc =
145
115M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
115M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
115M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
115M
  Store(dequant_x, d, block + k);
150
115M
  Store(dequant_y, d, block + size + k);
151
115M
  Store(dequant_b, d, block + 2 * size + k);
152
115M
}
Unexecuted instantiation: void jxl::N_SSE4::DequantLane<(jxl::ACType)0>(hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, float const*, unsigned long, unsigned long, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, float const*, jxl::ACPtr*, float*)
Unexecuted instantiation: void jxl::N_SSE4::DequantLane<(jxl::ACType)1>(hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, float const*, unsigned long, unsigned long, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, float const*, jxl::ACPtr*, float*)
void jxl::N_AVX2::DequantLane<(jxl::ACType)0>(hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, float const*, unsigned long, unsigned long, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, float const*, jxl::ACPtr*, float*)
Line
Count
Source
120
3.48M
                 float* JXL_RESTRICT block) {
121
3.48M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
3.48M
  const auto y_mul =
123
3.48M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
3.48M
  const auto b_mul =
125
3.48M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
3.48M
  Vec<DI> quantized_x_int;
128
3.48M
  Vec<DI> quantized_y_int;
129
3.48M
  Vec<DI> quantized_b_int;
130
3.48M
  if (ac_type == ACType::k16) {
131
3.48M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
3.48M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
3.48M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
3.48M
  } else {
135
0
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
0
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
0
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
0
  }
139
140
3.48M
  const auto dequant_x_cc =
141
3.48M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
3.48M
  const auto dequant_y =
143
3.48M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
3.48M
  const auto dequant_b_cc =
145
3.48M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
3.48M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
3.48M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
3.48M
  Store(dequant_x, d, block + k);
150
3.48M
  Store(dequant_y, d, block + size + k);
151
3.48M
  Store(dequant_b, d, block + 2 * size + k);
152
3.48M
}
void jxl::N_AVX2::DequantLane<(jxl::ACType)1>(hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, float const*, unsigned long, unsigned long, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, float const*, jxl::ACPtr*, float*)
Line
Count
Source
120
112M
                 float* JXL_RESTRICT block) {
121
112M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
112M
  const auto y_mul =
123
112M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
112M
  const auto b_mul =
125
112M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
112M
  Vec<DI> quantized_x_int;
128
112M
  Vec<DI> quantized_y_int;
129
112M
  Vec<DI> quantized_b_int;
130
112M
  if (ac_type == ACType::k16) {
131
0
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
0
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
0
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
112M
  } else {
135
112M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
112M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
112M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
112M
  }
139
140
112M
  const auto dequant_x_cc =
141
112M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
112M
  const auto dequant_y =
143
112M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
112M
  const auto dequant_b_cc =
145
112M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
112M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
112M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
112M
  Store(dequant_x, d, block + k);
150
112M
  Store(dequant_y, d, block + size + k);
151
112M
  Store(dequant_b, d, block + 2 * size + k);
152
112M
}
Unexecuted instantiation: void jxl::N_SSE2::DequantLane<(jxl::ACType)0>(hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, float const*, unsigned long, unsigned long, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, float const*, jxl::ACPtr*, float*)
Unexecuted instantiation: void jxl::N_SSE2::DequantLane<(jxl::ACType)1>(hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, float const*, unsigned long, unsigned long, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, float const*, jxl::ACPtr*, float*)
153
154
template <ACType ac_type>
155
void DequantBlock(float inv_global_scale, int quant, float x_dm_multiplier,
156
                  float b_dm_multiplier, Vec<D> x_cc_mul, Vec<D> b_cc_mul,
157
                  AcStrategyType kind, size_t size, const Quantizer& quantizer,
158
                  size_t covered_blocks, const size_t* sbx,
159
                  const float* JXL_RESTRICT* JXL_RESTRICT dc_row,
160
                  size_t dc_stride, const float* JXL_RESTRICT biases,
161
                  ACPtr qblock[3], float* JXL_RESTRICT block,
162
6.91M
                  float* JXL_RESTRICT scratch) {
163
6.91M
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
6.91M
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
6.91M
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
6.91M
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
6.91M
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
122M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
115M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
115M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
115M
                         qblock, block);
175
115M
  }
176
27.6M
  for (size_t c = 0; c < 3; c++) {
177
20.7M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
20.7M
                            block + c * size, scratch);
179
20.7M
  }
180
6.91M
}
Unexecuted instantiation: void jxl::N_SSE4::DequantBlock<(jxl::ACType)0>(float, int, float, float, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
Unexecuted instantiation: void jxl::N_SSE4::DequantBlock<(jxl::ACType)1>(float, int, float, float, hwy::N_SSE4::Vec128<float, 4ul>, hwy::N_SSE4::Vec128<float, 4ul>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
void jxl::N_AVX2::DequantBlock<(jxl::ACType)0>(float, int, float, float, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
Line
Count
Source
162
427k
                  float* JXL_RESTRICT scratch) {
163
427k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
427k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
427k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
427k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
427k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
3.90M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
3.48M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
3.48M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
3.48M
                         qblock, block);
175
3.48M
  }
176
1.71M
  for (size_t c = 0; c < 3; c++) {
177
1.28M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
1.28M
                            block + c * size, scratch);
179
1.28M
  }
180
427k
}
void jxl::N_AVX2::DequantBlock<(jxl::ACType)1>(float, int, float, float, hwy::N_AVX2::Vec256<float>, hwy::N_AVX2::Vec256<float>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
Line
Count
Source
162
6.48M
                  float* JXL_RESTRICT scratch) {
163
6.48M
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
6.48M
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
6.48M
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
6.48M
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
6.48M
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
118M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
112M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
112M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
112M
                         qblock, block);
175
112M
  }
176
25.9M
  for (size_t c = 0; c < 3; c++) {
177
19.4M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
19.4M
                            block + c * size, scratch);
179
19.4M
  }
180
6.48M
}
Unexecuted instantiation: void jxl::N_SSE2::DequantBlock<(jxl::ACType)0>(float, int, float, float, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
Unexecuted instantiation: void jxl::N_SSE2::DequantBlock<(jxl::ACType)1>(float, int, float, float, hwy::N_SSE2::Vec128<float, 4ul>, hwy::N_SSE2::Vec128<float, 4ul>, jxl::AcStrategyType, unsigned long, jxl::Quantizer const&, unsigned long, unsigned long const*, float const* restrict*, unsigned long, float const*, jxl::ACPtr*, float*, float*)
181
182
Status DecodeGroupImpl(const FrameHeader& frame_header,
183
                       GetBlock* JXL_RESTRICT get_block,
184
                       GroupDecCache* JXL_RESTRICT group_dec_cache,
185
                       PassesDecoderState* JXL_RESTRICT dec_state,
186
                       size_t thread, size_t group_idx,
187
                       RenderPipelineInput& render_pipeline_input,
188
28.8k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
28.8k
  const Rect block_rect =
191
28.8k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
28.8k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
28.8k
  const size_t xsize_blocks = block_rect.xsize();
195
28.8k
  const size_t ysize_blocks = block_rect.ysize();
196
197
28.8k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
28.8k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
28.8k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
28.8k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
28.8k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
28.8k
  size_t idct_stride[3];
207
115k
  for (size_t c = 0; c < 3; c++) {
208
86.6k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
86.6k
  }
210
211
28.8k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
28.8k
  ACType ac_type = dec_state->coefficients->Type();
214
28.8k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
28.8k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
28.8k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
28.8k
  size_t offset = 0;
221
222
28.8k
  std::array<int, 3> jpeg_c_map;
223
28.8k
  bool jpeg_is_gray = false;
224
28.8k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
28.8k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
28.8k
  if (jpeg_data) {
229
0
    if (!color_correlation.IsJPEGCompatible()) {
230
0
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
0
    }
232
0
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
0
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
0
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
0
    const std::vector<QuantEncoding>& qe =
236
0
        dec_state->shared->matrices.encodings();
237
0
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
0
        std::abs(qe[0].qraw.qtable_den - 1.f / (8 * 255)) > 1e-8f) {
239
0
      return JXL_FAILURE(
240
0
          "Quantization table is not a JPEG quantization table.");
241
0
    }
242
0
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
0
    int* qtable = qe[0].qraw.qtable->data();
244
0
    for (size_t c = 0; c < 3; c++) {
245
0
      if (frame_header.color_transform == ColorTransform::kNone) {
246
0
        dcoff[c] = 1024 / qtable[64 * c];
247
0
      }
248
0
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
0
        int num = qtable[64 + i];
251
0
        int den = qtable[64 * c + i];
252
0
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
0
          return JXL_FAILURE("Invalid JPEG quantization table");
254
0
        }
255
0
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
0
            (1 << kCFLFixedPointPrecision) * num / den;
257
0
      }
258
0
    }
259
0
  }
260
261
28.8k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
28.8k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
28.8k
  Rect r[3];
264
115k
  for (size_t i = 0; i < 3; i++) {
265
86.6k
    r[i] =
266
86.6k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
86.6k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
86.6k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
86.6k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
86.6k
  }
273
274
606k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
577k
    get_block->StartRow(by);
276
577k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
577k
    const int32_t* JXL_RESTRICT row_quant =
279
577k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
577k
    const float* JXL_RESTRICT dc_rows[3] = {
282
577k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
577k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
577k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
577k
    };
286
287
577k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
577k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
577k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
577k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
577k
        nullptr,
293
577k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
577k
    };
295
296
577k
    float* JXL_RESTRICT idct_row[3];
297
577k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
2.31M
    for (size_t c = 0; c < 3; c++) {
299
1.73M
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
1.73M
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
1.73M
      if (jpeg_data) {
302
0
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
0
        jpeg_row[c] =
304
0
            component.coeffs.data() +
305
0
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
0
                kDCTBlockSize;
307
0
      }
308
1.73M
    }
309
310
577k
    size_t bx = 0;
311
2.52M
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
1.94M
         tx++) {
313
1.94M
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
1.94M
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
1.94M
      auto b_cc_mul = Set(d, color_correlation.YtoBRatio(row_cmap[2][abs_tx]));
316
      // Increment bx by llf_x because those iterations would otherwise
317
      // immediately continue (!IsFirstBlock). Reduces mispredictions.
318
10.3M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
8.40M
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
8.40M
        AcStrategy acs = acs_row[bx];
321
8.40M
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
8.40M
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
1.48M
          bx += llf_x;
326
1.48M
          continue;
327
1.48M
        }
328
6.91M
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
6.91M
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
6.91M
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
6.91M
        ACPtr qblock[3];
334
6.91M
        if (accumulate) {
335
4.44k
          for (size_t c = 0; c < 3; c++) {
336
3.33k
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
3.33k
          }
338
6.91M
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
6.91M
          JXL_ENSURE(draw == kDraw);
342
6.91M
          if (ac_type == ACType::k16) {
343
427k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
427k
                   size * 3 * sizeof(int16_t));
345
1.71M
            for (size_t c = 0; c < 3; c++) {
346
1.28M
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
1.28M
            }
348
6.48M
          } else {
349
6.48M
            memset(group_dec_cache->dec_group_qblock, 0,
350
6.48M
                   size * 3 * sizeof(int32_t));
351
25.9M
            for (size_t c = 0; c < 3; c++) {
352
19.4M
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
19.4M
            }
354
6.48M
          }
355
6.91M
        }
356
6.91M
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
6.91M
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
6.91M
        offset += size;
359
6.91M
        if (draw == kDontDraw) {
360
968
          bx += llf_x;
361
968
          continue;
362
968
        }
363
364
6.91M
        if (JXL_UNLIKELY(jpeg_data)) {
365
0
          if (acs.Strategy() != AcStrategyType::DCT) {
366
0
            return JXL_FAILURE(
367
0
                "Can only decode to JPEG if only DCT-8 is used.");
368
0
          }
369
370
0
          HWY_ALIGN int32_t transposed_dct_y[64];
371
0
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
0
            if (jpeg_is_gray && c != 1) {
374
0
              continue;
375
0
            }
376
0
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
0
            int16_t* JXL_RESTRICT jpeg_pos =
380
0
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
0
            auto* transposed_dct = qblock[c].ptr32;
383
0
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
0
            if (!cs.Is444() ||
386
0
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
0
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
0
                const auto ini = Load(di, transposed_dct + i);
389
0
                const auto ini16 = DemoteTo(di16, ini);
390
0
                StoreU(ini16, di16, jpeg_pos + i);
391
0
              }
392
0
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
0
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
0
                const auto ini = Load(di, transposed_dct + i);
396
0
                Store(ini, di, transposed_dct_y + i);
397
0
                const auto ini16 = DemoteTo(di16, ini);
398
0
                StoreU(ini16, di16, jpeg_pos + i);
399
0
              }
400
0
            } else {
401
              // transposed_dct_y contains the y channel block, transposed.
402
0
              const auto scale =
403
0
                  Set(di, ColorCorrelation::RatioJPEG(row_cmap[c][abs_tx]));
404
0
              const auto round = Set(di, 1 << (kCFLFixedPointPrecision - 1));
405
0
              for (int i = 0; i < 64; i += Lanes(d)) {
406
0
                auto in = Load(di, transposed_dct + i);
407
0
                auto in_y = Load(di, transposed_dct_y + i);
408
0
                auto qt = Load(di, scaled_qtable + c * size + i);
409
0
                auto coeff_scale = ShiftRight<kCFLFixedPointPrecision>(
410
0
                    Add(Mul(qt, scale), round));
411
0
                auto cfl_factor = ShiftRight<kCFLFixedPointPrecision>(
412
0
                    Add(Mul(in_y, coeff_scale), round));
413
0
                StoreU(DemoteTo(di16, Add(in, cfl_factor)), di16, jpeg_pos + i);
414
0
              }
415
0
            }
416
0
            jpeg_pos[0] =
417
0
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
0
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
0
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
0
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
0
              auto in = LoadU(di16_full, jpeg_pos + i);
422
0
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
0
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
0
            }
425
0
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
0
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
0
            }
428
0
          }
429
6.91M
        } else {
430
6.91M
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
6.91M
          dequant_block(
433
6.91M
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
6.91M
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
6.91M
              size, dec_state->shared->quantizer,
436
6.91M
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
6.91M
              dc_stride,
438
6.91M
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
6.91M
              block, group_dec_cache->scratch_space);
440
441
20.7M
          for (size_t c : {1, 0, 2}) {
442
20.7M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
249k
              continue;
444
249k
            }
445
            // IDCT
446
20.5M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
20.5M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
20.5M
                              idct_stride[c], group_dec_cache->scratch_space);
449
20.5M
          }
450
6.91M
        }
451
6.91M
        bx += llf_x;
452
6.91M
      }
453
1.94M
    }
454
577k
  }
455
28.7k
  return true;
456
28.8k
}
Unexecuted instantiation: jxl::N_SSE4::DecodeGroupImpl(jxl::FrameHeader const&, jxl::GetBlock*, jxl::GroupDecCache*, jxl::PassesDecoderState*, unsigned long, unsigned long, jxl::RenderPipelineInput&, jxl::jpeg::JPEGData*, jxl::DrawMode)
jxl::N_AVX2::DecodeGroupImpl(jxl::FrameHeader const&, jxl::GetBlock*, jxl::GroupDecCache*, jxl::PassesDecoderState*, unsigned long, unsigned long, jxl::RenderPipelineInput&, jxl::jpeg::JPEGData*, jxl::DrawMode)
Line
Count
Source
188
28.8k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
28.8k
  const Rect block_rect =
191
28.8k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
28.8k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
28.8k
  const size_t xsize_blocks = block_rect.xsize();
195
28.8k
  const size_t ysize_blocks = block_rect.ysize();
196
197
28.8k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
28.8k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
28.8k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
28.8k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
28.8k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
28.8k
  size_t idct_stride[3];
207
115k
  for (size_t c = 0; c < 3; c++) {
208
86.6k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
86.6k
  }
210
211
28.8k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
28.8k
  ACType ac_type = dec_state->coefficients->Type();
214
28.8k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
28.8k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
28.8k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
28.8k
  size_t offset = 0;
221
222
28.8k
  std::array<int, 3> jpeg_c_map;
223
28.8k
  bool jpeg_is_gray = false;
224
28.8k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
28.8k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
28.8k
  if (jpeg_data) {
229
0
    if (!color_correlation.IsJPEGCompatible()) {
230
0
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
0
    }
232
0
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
0
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
0
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
0
    const std::vector<QuantEncoding>& qe =
236
0
        dec_state->shared->matrices.encodings();
237
0
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
0
        std::abs(qe[0].qraw.qtable_den - 1.f / (8 * 255)) > 1e-8f) {
239
0
      return JXL_FAILURE(
240
0
          "Quantization table is not a JPEG quantization table.");
241
0
    }
242
0
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
0
    int* qtable = qe[0].qraw.qtable->data();
244
0
    for (size_t c = 0; c < 3; c++) {
245
0
      if (frame_header.color_transform == ColorTransform::kNone) {
246
0
        dcoff[c] = 1024 / qtable[64 * c];
247
0
      }
248
0
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
0
        int num = qtable[64 + i];
251
0
        int den = qtable[64 * c + i];
252
0
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
0
          return JXL_FAILURE("Invalid JPEG quantization table");
254
0
        }
255
0
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
0
            (1 << kCFLFixedPointPrecision) * num / den;
257
0
      }
258
0
    }
259
0
  }
260
261
28.8k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
28.8k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
28.8k
  Rect r[3];
264
115k
  for (size_t i = 0; i < 3; i++) {
265
86.6k
    r[i] =
266
86.6k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
86.6k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
86.6k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
86.6k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
86.6k
  }
273
274
606k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
577k
    get_block->StartRow(by);
276
577k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
577k
    const int32_t* JXL_RESTRICT row_quant =
279
577k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
577k
    const float* JXL_RESTRICT dc_rows[3] = {
282
577k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
577k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
577k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
577k
    };
286
287
577k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
577k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
577k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
577k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
577k
        nullptr,
293
577k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
577k
    };
295
296
577k
    float* JXL_RESTRICT idct_row[3];
297
577k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
2.31M
    for (size_t c = 0; c < 3; c++) {
299
1.73M
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
1.73M
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
1.73M
      if (jpeg_data) {
302
0
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
0
        jpeg_row[c] =
304
0
            component.coeffs.data() +
305
0
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
0
                kDCTBlockSize;
307
0
      }
308
1.73M
    }
309
310
577k
    size_t bx = 0;
311
2.52M
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
1.94M
         tx++) {
313
1.94M
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
1.94M
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
1.94M
      auto b_cc_mul = Set(d, color_correlation.YtoBRatio(row_cmap[2][abs_tx]));
316
      // Increment bx by llf_x because those iterations would otherwise
317
      // immediately continue (!IsFirstBlock). Reduces mispredictions.
318
10.3M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
8.40M
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
8.40M
        AcStrategy acs = acs_row[bx];
321
8.40M
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
8.40M
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
1.48M
          bx += llf_x;
326
1.48M
          continue;
327
1.48M
        }
328
6.91M
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
6.91M
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
6.91M
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
6.91M
        ACPtr qblock[3];
334
6.91M
        if (accumulate) {
335
4.44k
          for (size_t c = 0; c < 3; c++) {
336
3.33k
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
3.33k
          }
338
6.91M
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
6.91M
          JXL_ENSURE(draw == kDraw);
342
6.91M
          if (ac_type == ACType::k16) {
343
427k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
427k
                   size * 3 * sizeof(int16_t));
345
1.71M
            for (size_t c = 0; c < 3; c++) {
346
1.28M
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
1.28M
            }
348
6.48M
          } else {
349
6.48M
            memset(group_dec_cache->dec_group_qblock, 0,
350
6.48M
                   size * 3 * sizeof(int32_t));
351
25.9M
            for (size_t c = 0; c < 3; c++) {
352
19.4M
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
19.4M
            }
354
6.48M
          }
355
6.91M
        }
356
6.91M
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
6.91M
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
6.91M
        offset += size;
359
6.91M
        if (draw == kDontDraw) {
360
968
          bx += llf_x;
361
968
          continue;
362
968
        }
363
364
6.91M
        if (JXL_UNLIKELY(jpeg_data)) {
365
0
          if (acs.Strategy() != AcStrategyType::DCT) {
366
0
            return JXL_FAILURE(
367
0
                "Can only decode to JPEG if only DCT-8 is used.");
368
0
          }
369
370
0
          HWY_ALIGN int32_t transposed_dct_y[64];
371
0
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
0
            if (jpeg_is_gray && c != 1) {
374
0
              continue;
375
0
            }
376
0
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
0
            int16_t* JXL_RESTRICT jpeg_pos =
380
0
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
0
            auto* transposed_dct = qblock[c].ptr32;
383
0
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
0
            if (!cs.Is444() ||
386
0
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
0
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
0
                const auto ini = Load(di, transposed_dct + i);
389
0
                const auto ini16 = DemoteTo(di16, ini);
390
0
                StoreU(ini16, di16, jpeg_pos + i);
391
0
              }
392
0
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
0
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
0
                const auto ini = Load(di, transposed_dct + i);
396
0
                Store(ini, di, transposed_dct_y + i);
397
0
                const auto ini16 = DemoteTo(di16, ini);
398
0
                StoreU(ini16, di16, jpeg_pos + i);
399
0
              }
400
0
            } else {
401
              // transposed_dct_y contains the y channel block, transposed.
402
0
              const auto scale =
403
0
                  Set(di, ColorCorrelation::RatioJPEG(row_cmap[c][abs_tx]));
404
0
              const auto round = Set(di, 1 << (kCFLFixedPointPrecision - 1));
405
0
              for (int i = 0; i < 64; i += Lanes(d)) {
406
0
                auto in = Load(di, transposed_dct + i);
407
0
                auto in_y = Load(di, transposed_dct_y + i);
408
0
                auto qt = Load(di, scaled_qtable + c * size + i);
409
0
                auto coeff_scale = ShiftRight<kCFLFixedPointPrecision>(
410
0
                    Add(Mul(qt, scale), round));
411
0
                auto cfl_factor = ShiftRight<kCFLFixedPointPrecision>(
412
0
                    Add(Mul(in_y, coeff_scale), round));
413
0
                StoreU(DemoteTo(di16, Add(in, cfl_factor)), di16, jpeg_pos + i);
414
0
              }
415
0
            }
416
0
            jpeg_pos[0] =
417
0
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
0
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
0
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
0
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
0
              auto in = LoadU(di16_full, jpeg_pos + i);
422
0
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
0
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
0
            }
425
0
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
0
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
0
            }
428
0
          }
429
6.91M
        } else {
430
6.91M
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
6.91M
          dequant_block(
433
6.91M
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
6.91M
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
6.91M
              size, dec_state->shared->quantizer,
436
6.91M
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
6.91M
              dc_stride,
438
6.91M
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
6.91M
              block, group_dec_cache->scratch_space);
440
441
20.7M
          for (size_t c : {1, 0, 2}) {
442
20.7M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
249k
              continue;
444
249k
            }
445
            // IDCT
446
20.5M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
20.5M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
20.5M
                              idct_stride[c], group_dec_cache->scratch_space);
449
20.5M
          }
450
6.91M
        }
451
6.91M
        bx += llf_x;
452
6.91M
      }
453
1.94M
    }
454
577k
  }
455
28.7k
  return true;
456
28.8k
}
Unexecuted instantiation: jxl::N_SSE2::DecodeGroupImpl(jxl::FrameHeader const&, jxl::GetBlock*, jxl::GroupDecCache*, jxl::PassesDecoderState*, unsigned long, unsigned long, jxl::RenderPipelineInput&, jxl::jpeg::JPEGData*, jxl::DrawMode)
457
458
// NOLINTNEXTLINE(google-readability-namespace-comments)
459
}  // namespace HWY_NAMESPACE
460
}  // namespace jxl
461
HWY_AFTER_NAMESPACE();
462
463
#if HWY_ONCE
464
namespace jxl {
465
namespace {
466
// Decode quantized AC coefficients of DCT blocks.
467
// LLF components in the output block will not be modified.
468
template <ACType ac_type, bool uses_lz77>
469
Status DecodeACVarBlock(size_t ctx_offset, size_t log2_covered_blocks,
470
                        int32_t* JXL_RESTRICT row_nzeros,
471
                        const int32_t* JXL_RESTRICT row_nzeros_top,
472
                        size_t nzeros_stride, size_t c, size_t bx, size_t by,
473
                        size_t lbx, AcStrategy acs,
474
                        const coeff_order_t* JXL_RESTRICT coeff_order,
475
                        BitReader* JXL_RESTRICT br,
476
                        ANSSymbolReader* JXL_RESTRICT decoder,
477
                        const std::vector<uint8_t>& context_map,
478
                        const uint8_t* qdc_row, const int32_t* qf_row,
479
                        const BlockCtxMap& block_ctx_map, ACPtr block,
480
1.24M
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
1.24M
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
1.24M
  const size_t size = covered_blocks * kDCTBlockSize;
484
1.24M
  int32_t predicted_nzeros =
485
1.24M
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
1.24M
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
1.24M
  const coeff_order_t* JXL_RESTRICT order =
489
1.24M
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
1.24M
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
1.24M
  const int32_t nzero_ctx =
493
1.24M
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
1.24M
  size_t nzeros =
496
1.24M
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
1.24M
  if (nzeros > size - covered_blocks) {
498
104
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
104
                       " 8x8 blocks",
500
104
                       nzeros, covered_blocks);
501
104
  }
502
2.49M
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
2.52M
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
1.27M
      row_nzeros[bx + x + y * nzeros_stride] =
505
1.27M
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
1.27M
    }
507
1.25M
  }
508
509
1.24M
  const size_t histo_offset =
510
1.24M
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
1.24M
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
4.13M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
2.89M
    const size_t ctx =
515
2.89M
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
2.89M
                                          log2_covered_blocks, prev);
517
2.89M
    const size_t u_coeff =
518
2.89M
        decoder->ReadHybridUintInlined<uses_lz77>(ctx, br, context_map);
519
    // Hand-rolled version of UnpackSigned, shifting before the conversion to
520
    // signed integer to avoid undefined behavior of shifting negative numbers.
521
2.89M
    const size_t magnitude = u_coeff >> 1;
522
2.89M
    const size_t neg_sign = (~u_coeff) & 1;
523
2.89M
    const ptrdiff_t coeff =
524
2.89M
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
2.89M
    if (ac_type == ACType::k16) {
526
689k
      block.ptr16[order[k]] += coeff;
527
2.20M
    } else {
528
2.20M
      block.ptr32[order[k]] += coeff;
529
2.20M
    }
530
2.89M
    prev = static_cast<size_t>(u_coeff != 0);
531
2.89M
    nzeros -= prev;
532
2.89M
  }
533
1.24M
  if (JXL_UNLIKELY(nzeros != 0)) {
534
86
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
86
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
86
                       "), channel %" PRIuS,
537
86
                       nzeros, bx, by, c);
538
86
  }
539
540
1.24M
  return true;
541
1.24M
}
dec_group.cc:jxl::Status jxl::(anonymous namespace)::DecodeACVarBlock<(jxl::ACType)0, true>(unsigned long, unsigned long, int*, int const*, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, jxl::AcStrategy, unsigned int const*, jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, unsigned char const*, int const*, jxl::BlockCtxMap const&, jxl::ACPtr, unsigned long)
Line
Count
Source
480
118k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
118k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
118k
  const size_t size = covered_blocks * kDCTBlockSize;
484
118k
  int32_t predicted_nzeros =
485
118k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
118k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
118k
  const coeff_order_t* JXL_RESTRICT order =
489
118k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
118k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
118k
  const int32_t nzero_ctx =
493
118k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
118k
  size_t nzeros =
496
118k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
118k
  if (nzeros > size - covered_blocks) {
498
9
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
9
                       " 8x8 blocks",
500
9
                       nzeros, covered_blocks);
501
9
  }
502
238k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
249k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
129k
      row_nzeros[bx + x + y * nzeros_stride] =
505
129k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
129k
    }
507
120k
  }
508
509
118k
  const size_t histo_offset =
510
118k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
118k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
529k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
411k
    const size_t ctx =
515
411k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
411k
                                          log2_covered_blocks, prev);
517
411k
    const size_t u_coeff =
518
411k
        decoder->ReadHybridUintInlined<uses_lz77>(ctx, br, context_map);
519
    // Hand-rolled version of UnpackSigned, shifting before the conversion to
520
    // signed integer to avoid undefined behavior of shifting negative numbers.
521
411k
    const size_t magnitude = u_coeff >> 1;
522
411k
    const size_t neg_sign = (~u_coeff) & 1;
523
411k
    const ptrdiff_t coeff =
524
411k
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
411k
    if (ac_type == ACType::k16) {
526
411k
      block.ptr16[order[k]] += coeff;
527
411k
    } else {
528
0
      block.ptr32[order[k]] += coeff;
529
0
    }
530
411k
    prev = static_cast<size_t>(u_coeff != 0);
531
411k
    nzeros -= prev;
532
411k
  }
533
118k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
30
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
30
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
30
                       "), channel %" PRIuS,
537
30
                       nzeros, bx, by, c);
538
30
  }
539
540
118k
  return true;
541
118k
}
dec_group.cc:jxl::Status jxl::(anonymous namespace)::DecodeACVarBlock<(jxl::ACType)1, true>(unsigned long, unsigned long, int*, int const*, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, jxl::AcStrategy, unsigned int const*, jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, unsigned char const*, int const*, jxl::BlockCtxMap const&, jxl::ACPtr, unsigned long)
Line
Count
Source
480
33.1k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
33.1k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
33.1k
  const size_t size = covered_blocks * kDCTBlockSize;
484
33.1k
  int32_t predicted_nzeros =
485
33.1k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
33.1k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
33.1k
  const coeff_order_t* JXL_RESTRICT order =
489
33.1k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
33.1k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
33.1k
  const int32_t nzero_ctx =
493
33.1k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
33.1k
  size_t nzeros =
496
33.1k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
33.1k
  if (nzeros > size - covered_blocks) {
498
41
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
41
                       " 8x8 blocks",
500
41
                       nzeros, covered_blocks);
501
41
  }
502
66.6k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
68.7k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
35.2k
      row_nzeros[bx + x + y * nzeros_stride] =
505
35.2k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
35.2k
    }
507
33.5k
  }
508
509
33.0k
  const size_t histo_offset =
510
33.0k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
33.0k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
277k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
244k
    const size_t ctx =
515
244k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
244k
                                          log2_covered_blocks, prev);
517
244k
    const size_t u_coeff =
518
244k
        decoder->ReadHybridUintInlined<uses_lz77>(ctx, br, context_map);
519
    // Hand-rolled version of UnpackSigned, shifting before the conversion to
520
    // signed integer to avoid undefined behavior of shifting negative numbers.
521
244k
    const size_t magnitude = u_coeff >> 1;
522
244k
    const size_t neg_sign = (~u_coeff) & 1;
523
244k
    const ptrdiff_t coeff =
524
244k
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
244k
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
244k
    } else {
528
244k
      block.ptr32[order[k]] += coeff;
529
244k
    }
530
244k
    prev = static_cast<size_t>(u_coeff != 0);
531
244k
    nzeros -= prev;
532
244k
  }
533
33.0k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
8
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
8
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
8
                       "), channel %" PRIuS,
537
8
                       nzeros, bx, by, c);
538
8
  }
539
540
33.0k
  return true;
541
33.0k
}
dec_group.cc:jxl::Status jxl::(anonymous namespace)::DecodeACVarBlock<(jxl::ACType)0, false>(unsigned long, unsigned long, int*, int const*, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, jxl::AcStrategy, unsigned int const*, jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, unsigned char const*, int const*, jxl::BlockCtxMap const&, jxl::ACPtr, unsigned long)
Line
Count
Source
480
932k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
932k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
932k
  const size_t size = covered_blocks * kDCTBlockSize;
484
932k
  int32_t predicted_nzeros =
485
932k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
932k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
932k
  const coeff_order_t* JXL_RESTRICT order =
489
932k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
932k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
932k
  const int32_t nzero_ctx =
493
932k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
932k
  size_t nzeros =
496
932k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
932k
  if (nzeros > size - covered_blocks) {
498
12
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
12
                       " 8x8 blocks",
500
12
                       nzeros, covered_blocks);
501
12
  }
502
1.86M
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
1.88M
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
944k
      row_nzeros[bx + x + y * nzeros_stride] =
505
944k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
944k
    }
507
936k
  }
508
509
932k
  const size_t histo_offset =
510
932k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
932k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
1.21M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
278k
    const size_t ctx =
515
278k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
278k
                                          log2_covered_blocks, prev);
517
278k
    const size_t u_coeff =
518
278k
        decoder->ReadHybridUintInlined<uses_lz77>(ctx, br, context_map);
519
    // Hand-rolled version of UnpackSigned, shifting before the conversion to
520
    // signed integer to avoid undefined behavior of shifting negative numbers.
521
278k
    const size_t magnitude = u_coeff >> 1;
522
278k
    const size_t neg_sign = (~u_coeff) & 1;
523
278k
    const ptrdiff_t coeff =
524
278k
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
278k
    if (ac_type == ACType::k16) {
526
278k
      block.ptr16[order[k]] += coeff;
527
278k
    } else {
528
0
      block.ptr32[order[k]] += coeff;
529
0
    }
530
278k
    prev = static_cast<size_t>(u_coeff != 0);
531
278k
    nzeros -= prev;
532
278k
  }
533
932k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
44
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
44
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
44
                       "), channel %" PRIuS,
537
44
                       nzeros, bx, by, c);
538
44
  }
539
540
932k
  return true;
541
932k
}
dec_group.cc:jxl::Status jxl::(anonymous namespace)::DecodeACVarBlock<(jxl::ACType)1, false>(unsigned long, unsigned long, int*, int const*, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, jxl::AcStrategy, unsigned int const*, jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, unsigned char const*, int const*, jxl::BlockCtxMap const&, jxl::ACPtr, unsigned long)
Line
Count
Source
480
162k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
162k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
162k
  const size_t size = covered_blocks * kDCTBlockSize;
484
162k
  int32_t predicted_nzeros =
485
162k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
162k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
162k
  const coeff_order_t* JXL_RESTRICT order =
489
162k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
162k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
162k
  const int32_t nzero_ctx =
493
162k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
162k
  size_t nzeros =
496
162k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
162k
  if (nzeros > size - covered_blocks) {
498
42
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
42
                       " 8x8 blocks",
500
42
                       nzeros, covered_blocks);
501
42
  }
502
325k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
328k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
165k
      row_nzeros[bx + x + y * nzeros_stride] =
505
165k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
165k
    }
507
162k
  }
508
509
162k
  const size_t histo_offset =
510
162k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
162k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
2.11M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
1.95M
    const size_t ctx =
515
1.95M
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
1.95M
                                          log2_covered_blocks, prev);
517
1.95M
    const size_t u_coeff =
518
1.95M
        decoder->ReadHybridUintInlined<uses_lz77>(ctx, br, context_map);
519
    // Hand-rolled version of UnpackSigned, shifting before the conversion to
520
    // signed integer to avoid undefined behavior of shifting negative numbers.
521
1.95M
    const size_t magnitude = u_coeff >> 1;
522
1.95M
    const size_t neg_sign = (~u_coeff) & 1;
523
1.95M
    const ptrdiff_t coeff =
524
1.95M
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
1.95M
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
1.95M
    } else {
528
1.95M
      block.ptr32[order[k]] += coeff;
529
1.95M
    }
530
1.95M
    prev = static_cast<size_t>(u_coeff != 0);
531
1.95M
    nzeros -= prev;
532
1.95M
  }
533
162k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
4
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
4
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
4
                       "), channel %" PRIuS,
537
4
                       nzeros, bx, by, c);
538
4
  }
539
540
162k
  return true;
541
162k
}
542
543
// Structs used by DecodeGroupImpl to get a quantized block.
544
// GetBlockFromBitstream uses ANS decoding (and thus keeps track of row
545
// pointers in row_nzeros), GetBlockFromEncoder simply reads the coefficient
546
// image provided by the encoder.
547
548
struct GetBlockFromBitstream : public GetBlock {
549
26.1k
  void StartRow(size_t by) override {
550
26.1k
    qf_row = rect.ConstRow(*qf, by);
551
104k
    for (size_t c = 0; c < 3; c++) {
552
78.5k
      size_t sby = by >> vshift[c];
553
78.5k
      quant_dc_row = quant_dc->ConstRow(rect.y0() + by) + rect.x0();
554
157k
      for (size_t i = 0; i < num_passes; i++) {
555
78.9k
        row_nzeros[i][c] = group_dec_cache->num_nzeroes[i].PlaneRow(c, sby);
556
78.9k
        row_nzeros_top[i][c] =
557
78.9k
            sby == 0
558
78.9k
                ? nullptr
559
78.9k
                : group_dec_cache->num_nzeroes[i].ConstPlaneRow(c, sby - 1);
560
78.9k
      }
561
78.5k
    }
562
26.1k
  }
563
564
  Status LoadBlock(size_t bx, size_t by, const AcStrategy& acs, size_t size,
565
                   size_t log2_covered_blocks, ACPtr block[3],
566
498k
                   ACType ac_type) override {
567
498k
    ;
568
1.49M
    for (size_t c : {1, 0, 2}) {
569
1.49M
      size_t sbx = bx >> hshift[c];
570
1.49M
      size_t sby = by >> vshift[c];
571
1.49M
      if (JXL_UNLIKELY((sbx << hshift[c] != bx) || (sby << vshift[c] != by))) {
572
249k
        continue;
573
249k
      }
574
575
2.49M
      for (size_t pass = 0; JXL_UNLIKELY(pass < num_passes); pass++) {
576
1.24M
        auto decode_ac_varblock =
577
1.24M
            decoders[pass].UsesLZ77()
578
1.24M
                ? (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 1>
579
151k
                                          : DecodeACVarBlock<ACType::k32, 1>)
580
1.24M
                : (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 0>
581
1.09M
                                          : DecodeACVarBlock<ACType::k32, 0>);
582
1.24M
        JXL_RETURN_IF_ERROR(decode_ac_varblock(
583
1.24M
            ctx_offset[pass], log2_covered_blocks, row_nzeros[pass][c],
584
1.24M
            row_nzeros_top[pass][c], nzeros_stride, c, sbx, sby, bx, acs,
585
1.24M
            &coeff_orders[pass * coeff_order_size], readers[pass],
586
1.24M
            &decoders[pass], context_map[pass], quant_dc_row, qf_row,
587
1.24M
            *block_ctx_map, block[c], shift_for_pass[pass]));
588
1.24M
      }
589
1.24M
    }
590
498k
    return true;
591
498k
  }
592
593
  Status Init(const FrameHeader& frame_header,
594
              BitReader* JXL_RESTRICT* JXL_RESTRICT readers_,
595
              size_t num_passes_, size_t group_idx, size_t histo_selector_bits,
596
              const Rect& rect_, GroupDecCache* JXL_RESTRICT group_dec_cache_,
597
5.46k
              PassesDecoderState* dec_state, size_t first_pass) {
598
21.8k
    for (size_t i = 0; i < 3; i++) {
599
16.3k
      hshift[i] = frame_header.chroma_subsampling.HShift(i);
600
16.3k
      vshift[i] = frame_header.chroma_subsampling.VShift(i);
601
16.3k
    }
602
5.46k
    coeff_order_size = dec_state->shared->coeff_order_size;
603
5.46k
    coeff_orders =
604
5.46k
        dec_state->shared->coeff_orders.data() + first_pass * coeff_order_size;
605
5.46k
    context_map = dec_state->context_map.data() + first_pass;
606
5.46k
    readers = readers_;
607
5.46k
    num_passes = num_passes_;
608
5.46k
    shift_for_pass = frame_header.passes.shift + first_pass;
609
5.46k
    group_dec_cache = group_dec_cache_;
610
5.46k
    rect = rect_;
611
5.46k
    block_ctx_map = &dec_state->shared->block_ctx_map;
612
5.46k
    qf = &dec_state->shared->raw_quant_field;
613
5.46k
    quant_dc = &dec_state->shared->quant_dc;
614
615
10.9k
    for (size_t pass = 0; pass < num_passes; pass++) {
616
      // Select which histogram set to use among those of the current pass.
617
5.48k
      size_t cur_histogram = 0;
618
5.48k
      if (histo_selector_bits != 0) {
619
98
        cur_histogram = readers[pass]->ReadBits(histo_selector_bits);
620
98
      }
621
5.48k
      if (cur_histogram >= dec_state->shared->num_histograms) {
622
2
        return JXL_FAILURE("Invalid histogram selector");
623
2
      }
624
5.48k
      ctx_offset[pass] = cur_histogram * block_ctx_map->NumACContexts();
625
626
5.48k
      JXL_ASSIGN_OR_RETURN(
627
5.48k
          decoders[pass],
628
5.48k
          ANSSymbolReader::Create(&dec_state->code[pass + first_pass],
629
5.48k
                                  readers[pass]));
630
5.48k
    }
631
5.45k
    nzeros_stride = group_dec_cache->num_nzeroes[0].PixelsPerRow();
632
10.9k
    for (size_t i = 0; i < num_passes; i++) {
633
5.48k
      JXL_ENSURE(
634
5.48k
          nzeros_stride ==
635
5.48k
          static_cast<size_t>(group_dec_cache->num_nzeroes[i].PixelsPerRow()));
636
5.48k
    }
637
5.45k
    return true;
638
5.45k
  }
639
640
  const uint32_t* shift_for_pass = nullptr;  // not owned
641
  const coeff_order_t* JXL_RESTRICT coeff_orders;
642
  size_t coeff_order_size;
643
  const std::vector<uint8_t>* JXL_RESTRICT context_map;
644
  ANSSymbolReader decoders[kMaxNumPasses];
645
  BitReader* JXL_RESTRICT* JXL_RESTRICT readers;
646
  size_t num_passes;
647
  size_t ctx_offset[kMaxNumPasses];
648
  size_t nzeros_stride;
649
  int32_t* JXL_RESTRICT row_nzeros[kMaxNumPasses][3];
650
  const int32_t* JXL_RESTRICT row_nzeros_top[kMaxNumPasses][3];
651
  GroupDecCache* JXL_RESTRICT group_dec_cache;
652
  const BlockCtxMap* block_ctx_map;
653
  const ImageI* qf;
654
  const ImageB* quant_dc;
655
  const int32_t* qf_row;
656
  const uint8_t* quant_dc_row;
657
  Rect rect;
658
  size_t hshift[3], vshift[3];
659
};
660
661
struct GetBlockFromEncoder : public GetBlock {
662
551k
  void StartRow(size_t by) override {}
663
664
  Status LoadBlock(size_t bx, size_t by, const AcStrategy& acs, size_t size,
665
                   size_t log2_covered_blocks, ACPtr block[3],
666
6.41M
                   ACType ac_type) override {
667
6.41M
    JXL_ENSURE(ac_type == ACType::k32);
668
25.6M
    for (size_t c = 0; c < 3; c++) {
669
      // for each pass
670
38.5M
      for (size_t i = 0; i < quantized_ac->size(); i++) {
671
2.69G
        for (size_t k = 0; k < size; k++) {
672
          // TODO(veluca): SIMD.
673
2.67G
          block[c].ptr32[k] +=
674
2.67G
              rows[i][c][offset + k] * (1 << shift_for_pass[i]);
675
2.67G
        }
676
19.2M
      }
677
19.2M
    }
678
6.41M
    offset += size;
679
6.41M
    return true;
680
6.41M
  }
681
682
  static StatusOr<GetBlockFromEncoder> Create(
683
      const std::vector<std::unique_ptr<ACImage>>& ac, size_t group_idx,
684
23.4k
      const uint32_t* shift_for_pass) {
685
23.4k
    GetBlockFromEncoder result(ac, group_idx, shift_for_pass);
686
    // TODO(veluca): not supported with chroma subsampling.
687
46.8k
    for (size_t i = 0; i < ac.size(); i++) {
688
23.4k
      JXL_ENSURE(ac[i]->Type() == ACType::k32);
689
93.7k
      for (size_t c = 0; c < 3; c++) {
690
70.3k
        result.rows[i][c] = ac[i]->PlaneRow(c, group_idx, 0).ptr32;
691
70.3k
      }
692
23.4k
    }
693
23.4k
    return result;
694
23.4k
  }
695
696
  const std::vector<std::unique_ptr<ACImage>>* JXL_RESTRICT quantized_ac;
697
  size_t offset = 0;
698
  const int32_t* JXL_RESTRICT rows[kMaxNumPasses][3];
699
  const uint32_t* shift_for_pass = nullptr;  // not owned
700
701
 private:
702
  GetBlockFromEncoder(const std::vector<std::unique_ptr<ACImage>>& ac,
703
                      size_t group_idx, const uint32_t* shift_for_pass)
704
23.4k
      : quantized_ac(&ac), shift_for_pass(shift_for_pass) {}
705
};
706
707
HWY_EXPORT(DecodeGroupImpl);
708
709
}  // namespace
710
711
Status DecodeGroup(const FrameHeader& frame_header,
712
                   BitReader* JXL_RESTRICT* JXL_RESTRICT readers,
713
                   size_t num_passes, size_t group_idx,
714
                   PassesDecoderState* JXL_RESTRICT dec_state,
715
                   GroupDecCache* JXL_RESTRICT group_dec_cache, size_t thread,
716
                   RenderPipelineInput& render_pipeline_input,
717
                   jpeg::JPEGData* JXL_RESTRICT jpeg_data, size_t first_pass,
718
5.46k
                   bool force_draw, bool dc_only, bool* should_run_pipeline) {
719
5.46k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
720
5.46k
  DrawMode draw =
721
5.46k
      (num_passes + first_pass == frame_header.passes.num_passes) || force_draw
722
5.46k
          ? kDraw
723
5.46k
          : kDontDraw;
724
725
5.46k
  if (should_run_pipeline) {
726
5.46k
    *should_run_pipeline = draw != kDontDraw;
727
5.46k
  }
728
729
5.46k
  if (draw == kDraw && num_passes == 0 && first_pass == 0) {
730
0
    JXL_RETURN_IF_ERROR(group_dec_cache->InitDCBufferOnce(memory_manager));
731
0
    const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
732
0
    for (size_t c : {0, 1, 2}) {
733
0
      size_t hs = cs.HShift(c);
734
0
      size_t vs = cs.VShift(c);
735
      // We reuse filter_input_storage here as it is not currently in use.
736
0
      const Rect src_rect_precs =
737
0
          dec_state->shared->frame_dim.BlockGroupRect(group_idx);
738
0
      const Rect src_rect =
739
0
          Rect(src_rect_precs.x0() >> hs, src_rect_precs.y0() >> vs,
740
0
               src_rect_precs.xsize() >> hs, src_rect_precs.ysize() >> vs);
741
0
      const Rect copy_rect(kRenderPipelineXOffset, 2, src_rect.xsize(),
742
0
                           src_rect.ysize());
743
0
      JXL_RETURN_IF_ERROR(
744
0
          CopyImageToWithPadding(src_rect, dec_state->shared->dc->Plane(c), 2,
745
0
                                 copy_rect, &group_dec_cache->dc_buffer));
746
      // Mirrorpad. Interleaving left and right padding ensures that padding
747
      // works out correctly even for images with DC size of 1.
748
0
      for (size_t y = 0; y < src_rect.ysize() + 4; y++) {
749
0
        size_t xend = kRenderPipelineXOffset +
750
0
                      (dec_state->shared->dc->Plane(c).xsize() >> hs) -
751
0
                      src_rect.x0();
752
0
        for (size_t ix = 0; ix < 2; ix++) {
753
0
          if (src_rect.x0() == 0) {
754
0
            group_dec_cache->dc_buffer.Row(y)[kRenderPipelineXOffset - ix - 1] =
755
0
                group_dec_cache->dc_buffer.Row(y)[kRenderPipelineXOffset + ix];
756
0
          }
757
0
          if (src_rect.x0() + src_rect.xsize() + 2 >=
758
0
              (dec_state->shared->dc->xsize() >> hs)) {
759
0
            group_dec_cache->dc_buffer.Row(y)[xend + ix] =
760
0
                group_dec_cache->dc_buffer.Row(y)[xend - ix - 1];
761
0
          }
762
0
        }
763
0
      }
764
0
      const auto& buffer = render_pipeline_input.GetBuffer(c);
765
0
      Rect dst_rect = buffer.second;
766
0
      ImageF* upsampling_dst = buffer.first;
767
0
      JXL_ENSURE(dst_rect.IsInside(*upsampling_dst));
768
769
0
      RenderPipelineStage::RowInfo input_rows(1, std::vector<float*>(5));
770
0
      RenderPipelineStage::RowInfo output_rows(1, std::vector<float*>(8));
771
0
      for (size_t y = src_rect.y0(); y < src_rect.y0() + src_rect.ysize();
772
0
           y++) {
773
0
        for (ptrdiff_t iy = 0; iy < 5; iy++) {
774
0
          input_rows[0][iy] = group_dec_cache->dc_buffer.Row(
775
0
              Mirror(static_cast<ptrdiff_t>(y) + iy - 2,
776
0
                     dec_state->shared->dc->Plane(c).ysize() >> vs) +
777
0
              2 - src_rect.y0());
778
0
        }
779
0
        for (size_t iy = 0; iy < 8; iy++) {
780
0
          output_rows[0][iy] =
781
0
              dst_rect.Row(upsampling_dst, ((y - src_rect.y0()) << 3) + iy) -
782
0
              kRenderPipelineXOffset;
783
0
        }
784
        // Arguments set to 0/nullptr are not used.
785
0
        JXL_RETURN_IF_ERROR(dec_state->upsampler8x->ProcessRow(
786
0
            input_rows, output_rows,
787
0
            /*xextra=*/0, src_rect.xsize(), 0, 0, thread));
788
0
      }
789
0
    }
790
0
    return true;
791
0
  }
792
793
5.46k
  size_t histo_selector_bits = 0;
794
5.46k
  if (dc_only) {
795
0
    JXL_ENSURE(num_passes == 0);
796
5.46k
  } else {
797
5.46k
    JXL_ENSURE(dec_state->shared->num_histograms > 0);
798
5.46k
    histo_selector_bits = CeilLog2Nonzero(dec_state->shared->num_histograms);
799
5.46k
  }
800
801
5.46k
  auto get_block = jxl::make_unique<GetBlockFromBitstream>();
802
5.46k
  JXL_RETURN_IF_ERROR(get_block->Init(
803
5.46k
      frame_header, readers, num_passes, group_idx, histo_selector_bits,
804
5.46k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx), group_dec_cache,
805
5.46k
      dec_state, first_pass));
806
807
5.45k
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
808
5.45k
      frame_header, get_block.get(), group_dec_cache, dec_state, thread,
809
5.45k
      group_idx, render_pipeline_input, jpeg_data, draw));
810
811
10.5k
  for (size_t pass = 0; pass < num_passes; pass++) {
812
5.28k
    if (!get_block->decoders[pass].CheckANSFinalState()) {
813
0
      return JXL_FAILURE("ANS checksum failure.");
814
0
    }
815
5.28k
  }
816
5.26k
  return true;
817
5.26k
}
818
819
Status DecodeGroupForRoundtrip(const FrameHeader& frame_header,
820
                               const std::vector<std::unique_ptr<ACImage>>& ac,
821
                               size_t group_idx,
822
                               PassesDecoderState* JXL_RESTRICT dec_state,
823
                               GroupDecCache* JXL_RESTRICT group_dec_cache,
824
                               size_t thread,
825
                               RenderPipelineInput& render_pipeline_input,
826
                               jpeg::JPEGData* JXL_RESTRICT jpeg_data,
827
23.4k
                               AuxOut* aux_out) {
828
23.4k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
829
23.4k
  JXL_ASSIGN_OR_RETURN(
830
23.4k
      GetBlockFromEncoder get_block,
831
23.4k
      GetBlockFromEncoder::Create(ac, group_idx, frame_header.passes.shift));
832
23.4k
  JXL_RETURN_IF_ERROR(group_dec_cache->InitOnce(
833
23.4k
      memory_manager,
834
23.4k
      /*num_passes=*/0,
835
23.4k
      /*used_acs=*/(1u << AcStrategy::kNumValidStrategies) - 1));
836
837
23.4k
  return HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
838
23.4k
      frame_header, &get_block, group_dec_cache, dec_state, thread, group_idx,
839
23.4k
      render_pipeline_input, jpeg_data, kDraw);
840
23.4k
}
841
842
}  // namespace jxl
843
#endif  // HWY_ONCE