Coverage Report

Created: 2025-06-16 07:00

/src/libjxl/lib/jxl/dec_group.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_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
7.05k
  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
10.3M
                 float* JXL_RESTRICT block) {
121
10.3M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
10.3M
  const auto y_mul =
123
10.3M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
10.3M
  const auto b_mul =
125
10.3M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
10.3M
  Vec<DI> quantized_x_int;
128
10.3M
  Vec<DI> quantized_y_int;
129
10.3M
  Vec<DI> quantized_b_int;
130
10.3M
  if (ac_type == ACType::k16) {
131
644k
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
644k
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
644k
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
9.66M
  } else {
135
9.66M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
9.66M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
9.66M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
9.66M
  }
139
140
10.3M
  const auto dequant_x_cc =
141
10.3M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
10.3M
  const auto dequant_y =
143
10.3M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
10.3M
  const auto dequant_b_cc =
145
10.3M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
10.3M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
10.3M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
10.3M
  Store(dequant_x, d, block + k);
150
10.3M
  Store(dequant_y, d, block + size + k);
151
10.3M
  Store(dequant_b, d, block + 2 * size + k);
152
10.3M
}
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
644k
                 float* JXL_RESTRICT block) {
121
644k
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
644k
  const auto y_mul =
123
644k
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
644k
  const auto b_mul =
125
644k
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
644k
  Vec<DI> quantized_x_int;
128
644k
  Vec<DI> quantized_y_int;
129
644k
  Vec<DI> quantized_b_int;
130
644k
  if (ac_type == ACType::k16) {
131
644k
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
644k
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
644k
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
644k
  } 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
644k
  const auto dequant_x_cc =
141
644k
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
644k
  const auto dequant_y =
143
644k
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
644k
  const auto dequant_b_cc =
145
644k
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
644k
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
644k
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
644k
  Store(dequant_x, d, block + k);
150
644k
  Store(dequant_y, d, block + size + k);
151
644k
  Store(dequant_b, d, block + 2 * size + k);
152
644k
}
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
9.66M
                 float* JXL_RESTRICT block) {
121
9.66M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
9.66M
  const auto y_mul =
123
9.66M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
9.66M
  const auto b_mul =
125
9.66M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
9.66M
  Vec<DI> quantized_x_int;
128
9.66M
  Vec<DI> quantized_y_int;
129
9.66M
  Vec<DI> quantized_b_int;
130
9.66M
  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
9.66M
  } else {
135
9.66M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
9.66M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
9.66M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
9.66M
  }
139
140
9.66M
  const auto dequant_x_cc =
141
9.66M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
9.66M
  const auto dequant_y =
143
9.66M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
9.66M
  const auto dequant_b_cc =
145
9.66M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
9.66M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
9.66M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
9.66M
  Store(dequant_x, d, block + k);
150
9.66M
  Store(dequant_y, d, block + size + k);
151
9.66M
  Store(dequant_b, d, block + 2 * size + k);
152
9.66M
}
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
817k
                  float* JXL_RESTRICT scratch) {
163
817k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
817k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
817k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
817k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
817k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
11.1M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
10.3M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
10.3M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
10.3M
                         qblock, block);
175
10.3M
  }
176
3.26M
  for (size_t c = 0; c < 3; c++) {
177
2.45M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
2.45M
                            block + c * size, scratch);
179
2.45M
  }
180
817k
}
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
78.0k
                  float* JXL_RESTRICT scratch) {
163
78.0k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
78.0k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
78.0k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
78.0k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
78.0k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
722k
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
644k
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
644k
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
644k
                         qblock, block);
175
644k
  }
176
312k
  for (size_t c = 0; c < 3; c++) {
177
234k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
234k
                            block + c * size, scratch);
179
234k
  }
180
78.0k
}
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
739k
                  float* JXL_RESTRICT scratch) {
163
739k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
739k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
739k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
739k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
739k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
10.4M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
9.66M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
9.66M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
9.66M
                         qblock, block);
175
9.66M
  }
176
2.95M
  for (size_t c = 0; c < 3; c++) {
177
2.21M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
2.21M
                            block + c * size, scratch);
179
2.21M
  }
180
739k
}
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
3.48k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
3.48k
  const Rect block_rect =
191
3.48k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
3.48k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
3.48k
  const size_t xsize_blocks = block_rect.xsize();
195
3.48k
  const size_t ysize_blocks = block_rect.ysize();
196
197
3.48k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
3.48k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
3.48k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
3.48k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
3.48k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
3.48k
  size_t idct_stride[3];
207
13.9k
  for (size_t c = 0; c < 3; c++) {
208
10.4k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
10.4k
  }
210
211
3.48k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
3.48k
  ACType ac_type = dec_state->coefficients->Type();
214
3.48k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
3.48k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
3.48k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
3.48k
  size_t offset = 0;
221
222
3.48k
  std::array<int, 3> jpeg_c_map;
223
3.48k
  bool jpeg_is_gray = false;
224
3.48k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
3.48k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
3.48k
  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
3.48k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
3.48k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
3.48k
  Rect r[3];
264
13.9k
  for (size_t i = 0; i < 3; i++) {
265
10.4k
    r[i] =
266
10.4k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
10.4k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
10.4k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
10.4k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
10.4k
  }
273
274
52.3k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
49.0k
    get_block->StartRow(by);
276
49.0k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
49.0k
    const int32_t* JXL_RESTRICT row_quant =
279
49.0k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
49.0k
    const float* JXL_RESTRICT dc_rows[3] = {
282
49.0k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
49.0k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
49.0k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
49.0k
    };
286
287
49.0k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
49.0k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
49.0k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
49.0k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
49.0k
        nullptr,
293
49.0k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
49.0k
    };
295
296
49.0k
    float* JXL_RESTRICT idct_row[3];
297
49.0k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
196k
    for (size_t c = 0; c < 3; c++) {
299
147k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
147k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
147k
      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
147k
    }
309
310
49.0k
    size_t bx = 0;
311
224k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
175k
         tx++) {
313
175k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
175k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
175k
      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
1.10M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
933k
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
933k
        AcStrategy acs = acs_row[bx];
321
933k
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
933k
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
116k
          bx += llf_x;
326
116k
          continue;
327
116k
        }
328
817k
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
817k
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
817k
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
817k
        ACPtr qblock[3];
334
817k
        if (accumulate) {
335
20
          for (size_t c = 0; c < 3; c++) {
336
15
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
15
          }
338
817k
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
817k
          JXL_ENSURE(draw == kDraw);
342
817k
          if (ac_type == ACType::k16) {
343
78.0k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
78.0k
                   size * 3 * sizeof(int16_t));
345
312k
            for (size_t c = 0; c < 3; c++) {
346
234k
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
234k
            }
348
739k
          } else {
349
739k
            memset(group_dec_cache->dec_group_qblock, 0,
350
739k
                   size * 3 * sizeof(int32_t));
351
2.95M
            for (size_t c = 0; c < 3; c++) {
352
2.21M
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
2.21M
            }
354
739k
          }
355
817k
        }
356
817k
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
817k
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
817k
        offset += size;
359
817k
        if (draw == kDontDraw) {
360
3
          bx += llf_x;
361
3
          continue;
362
3
        }
363
364
817k
        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
817k
        } else {
430
817k
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
817k
          dequant_block(
433
817k
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
817k
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
817k
              size, dec_state->shared->quantizer,
436
817k
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
817k
              dc_stride,
438
817k
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
817k
              block, group_dec_cache->scratch_space);
440
441
2.45M
          for (size_t c : {1, 0, 2}) {
442
2.45M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
2.83k
              continue;
444
2.83k
            }
445
            // IDCT
446
2.44M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
2.44M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
2.44M
                              idct_stride[c], group_dec_cache->scratch_space);
449
2.44M
          }
450
817k
        }
451
817k
        bx += llf_x;
452
817k
      }
453
175k
    }
454
49.0k
  }
455
3.28k
  return true;
456
3.48k
}
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
3.48k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
3.48k
  const Rect block_rect =
191
3.48k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
3.48k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
3.48k
  const size_t xsize_blocks = block_rect.xsize();
195
3.48k
  const size_t ysize_blocks = block_rect.ysize();
196
197
3.48k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
3.48k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
3.48k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
3.48k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
3.48k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
3.48k
  size_t idct_stride[3];
207
13.9k
  for (size_t c = 0; c < 3; c++) {
208
10.4k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
10.4k
  }
210
211
3.48k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
3.48k
  ACType ac_type = dec_state->coefficients->Type();
214
3.48k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
3.48k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
3.48k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
3.48k
  size_t offset = 0;
221
222
3.48k
  std::array<int, 3> jpeg_c_map;
223
3.48k
  bool jpeg_is_gray = false;
224
3.48k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
3.48k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
3.48k
  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
3.48k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
3.48k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
3.48k
  Rect r[3];
264
13.9k
  for (size_t i = 0; i < 3; i++) {
265
10.4k
    r[i] =
266
10.4k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
10.4k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
10.4k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
10.4k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
10.4k
  }
273
274
52.3k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
49.0k
    get_block->StartRow(by);
276
49.0k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
49.0k
    const int32_t* JXL_RESTRICT row_quant =
279
49.0k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
49.0k
    const float* JXL_RESTRICT dc_rows[3] = {
282
49.0k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
49.0k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
49.0k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
49.0k
    };
286
287
49.0k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
49.0k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
49.0k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
49.0k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
49.0k
        nullptr,
293
49.0k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
49.0k
    };
295
296
49.0k
    float* JXL_RESTRICT idct_row[3];
297
49.0k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
196k
    for (size_t c = 0; c < 3; c++) {
299
147k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
147k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
147k
      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
147k
    }
309
310
49.0k
    size_t bx = 0;
311
224k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
175k
         tx++) {
313
175k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
175k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
175k
      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
1.10M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
933k
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
933k
        AcStrategy acs = acs_row[bx];
321
933k
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
933k
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
116k
          bx += llf_x;
326
116k
          continue;
327
116k
        }
328
817k
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
817k
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
817k
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
817k
        ACPtr qblock[3];
334
817k
        if (accumulate) {
335
20
          for (size_t c = 0; c < 3; c++) {
336
15
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
15
          }
338
817k
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
817k
          JXL_ENSURE(draw == kDraw);
342
817k
          if (ac_type == ACType::k16) {
343
78.0k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
78.0k
                   size * 3 * sizeof(int16_t));
345
312k
            for (size_t c = 0; c < 3; c++) {
346
234k
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
234k
            }
348
739k
          } else {
349
739k
            memset(group_dec_cache->dec_group_qblock, 0,
350
739k
                   size * 3 * sizeof(int32_t));
351
2.95M
            for (size_t c = 0; c < 3; c++) {
352
2.21M
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
2.21M
            }
354
739k
          }
355
817k
        }
356
817k
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
817k
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
817k
        offset += size;
359
817k
        if (draw == kDontDraw) {
360
3
          bx += llf_x;
361
3
          continue;
362
3
        }
363
364
817k
        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
817k
        } else {
430
817k
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
817k
          dequant_block(
433
817k
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
817k
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
817k
              size, dec_state->shared->quantizer,
436
817k
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
817k
              dc_stride,
438
817k
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
817k
              block, group_dec_cache->scratch_space);
440
441
2.45M
          for (size_t c : {1, 0, 2}) {
442
2.45M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
2.83k
              continue;
444
2.83k
            }
445
            // IDCT
446
2.44M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
2.44M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
2.44M
                              idct_stride[c], group_dec_cache->scratch_space);
449
2.44M
          }
450
817k
        }
451
817k
        bx += llf_x;
452
817k
      }
453
175k
    }
454
49.0k
  }
455
3.28k
  return true;
456
3.48k
}
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
272k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
272k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
272k
  const size_t size = covered_blocks * kDCTBlockSize;
484
272k
  int32_t predicted_nzeros =
485
272k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
272k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
272k
  const coeff_order_t* JXL_RESTRICT order =
489
272k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
272k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
272k
  const int32_t nzero_ctx =
493
272k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
272k
  size_t nzeros =
496
272k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
272k
  if (nzeros > size - covered_blocks) {
498
110
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
110
                       " 8x8 blocks",
500
110
                       nzeros, covered_blocks);
501
110
  }
502
551k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
559k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
281k
      row_nzeros[bx + x + y * nzeros_stride] =
505
281k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
281k
    }
507
278k
  }
508
509
272k
  const size_t histo_offset =
510
272k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
272k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
768k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
496k
    const size_t ctx =
515
496k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
496k
                                          log2_covered_blocks, prev);
517
496k
    const size_t u_coeff =
518
496k
        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
496k
    const size_t magnitude = u_coeff >> 1;
522
496k
    const size_t neg_sign = (~u_coeff) & 1;
523
496k
    const intptr_t coeff =
524
496k
        static_cast<intptr_t>((magnitude ^ (neg_sign - 1)) << shift);
525
496k
    if (ac_type == ACType::k16) {
526
322k
      block.ptr16[order[k]] += coeff;
527
322k
    } else {
528
173k
      block.ptr32[order[k]] += coeff;
529
173k
    }
530
496k
    prev = static_cast<size_t>(u_coeff != 0);
531
496k
    nzeros -= prev;
532
496k
  }
533
272k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
84
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
84
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
84
                       "), channel %" PRIuS,
537
84
                       nzeros, bx, by, c);
538
84
  }
539
540
272k
  return true;
541
272k
}
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
77.3k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
77.3k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
77.3k
  const size_t size = covered_blocks * kDCTBlockSize;
484
77.3k
  int32_t predicted_nzeros =
485
77.3k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
77.3k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
77.3k
  const coeff_order_t* JXL_RESTRICT order =
489
77.3k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
77.3k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
77.3k
  const int32_t nzero_ctx =
493
77.3k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
77.3k
  size_t nzeros =
496
77.3k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
77.3k
  if (nzeros > size - covered_blocks) {
498
7
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
7
                       " 8x8 blocks",
500
7
                       nzeros, covered_blocks);
501
7
  }
502
157k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
160k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
80.8k
      row_nzeros[bx + x + y * nzeros_stride] =
505
80.8k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
80.8k
    }
507
80.0k
  }
508
509
77.3k
  const size_t histo_offset =
510
77.3k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
77.3k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
322k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
245k
    const size_t ctx =
515
245k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
245k
                                          log2_covered_blocks, prev);
517
245k
    const size_t u_coeff =
518
245k
        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
245k
    const size_t magnitude = u_coeff >> 1;
522
245k
    const size_t neg_sign = (~u_coeff) & 1;
523
245k
    const intptr_t coeff =
524
245k
        static_cast<intptr_t>((magnitude ^ (neg_sign - 1)) << shift);
525
245k
    if (ac_type == ACType::k16) {
526
245k
      block.ptr16[order[k]] += coeff;
527
245k
    } else {
528
0
      block.ptr32[order[k]] += coeff;
529
0
    }
530
245k
    prev = static_cast<size_t>(u_coeff != 0);
531
245k
    nzeros -= prev;
532
245k
  }
533
77.3k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
32
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
32
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
32
                       "), channel %" PRIuS,
537
32
                       nzeros, bx, by, c);
538
32
  }
539
540
77.2k
  return true;
541
77.3k
}
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
15.1k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
15.1k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
15.1k
  const size_t size = covered_blocks * kDCTBlockSize;
484
15.1k
  int32_t predicted_nzeros =
485
15.1k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
15.1k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
15.1k
  const coeff_order_t* JXL_RESTRICT order =
489
15.1k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
15.1k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
15.1k
  const int32_t nzero_ctx =
493
15.1k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
15.1k
  size_t nzeros =
496
15.1k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
15.1k
  if (nzeros > size - covered_blocks) {
498
46
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
46
                       " 8x8 blocks",
500
46
                       nzeros, covered_blocks);
501
46
  }
502
30.3k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
30.8k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
15.6k
      row_nzeros[bx + x + y * nzeros_stride] =
505
15.6k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
15.6k
    }
507
15.1k
  }
508
509
15.1k
  const size_t histo_offset =
510
15.1k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
15.1k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
117k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
102k
    const size_t ctx =
515
102k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
102k
                                          log2_covered_blocks, prev);
517
102k
    const size_t u_coeff =
518
102k
        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
102k
    const size_t magnitude = u_coeff >> 1;
522
102k
    const size_t neg_sign = (~u_coeff) & 1;
523
102k
    const intptr_t coeff =
524
102k
        static_cast<intptr_t>((magnitude ^ (neg_sign - 1)) << shift);
525
102k
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
102k
    } else {
528
102k
      block.ptr32[order[k]] += coeff;
529
102k
    }
530
102k
    prev = static_cast<size_t>(u_coeff != 0);
531
102k
    nzeros -= prev;
532
102k
  }
533
15.1k
  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
15.1k
  return true;
541
15.1k
}
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
154k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
154k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
154k
  const size_t size = covered_blocks * kDCTBlockSize;
484
154k
  int32_t predicted_nzeros =
485
154k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
154k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
154k
  const coeff_order_t* JXL_RESTRICT order =
489
154k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
154k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
154k
  const int32_t nzero_ctx =
493
154k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
154k
  size_t nzeros =
496
154k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
154k
  if (nzeros > size - covered_blocks) {
498
16
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
16
                       " 8x8 blocks",
500
16
                       nzeros, covered_blocks);
501
16
  }
502
310k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
314k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
158k
      row_nzeros[bx + x + y * nzeros_stride] =
505
158k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
158k
    }
507
156k
  }
508
509
154k
  const size_t histo_offset =
510
154k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
154k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
230k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
76.7k
    const size_t ctx =
515
76.7k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
76.7k
                                          log2_covered_blocks, prev);
517
76.7k
    const size_t u_coeff =
518
76.7k
        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
76.7k
    const size_t magnitude = u_coeff >> 1;
522
76.7k
    const size_t neg_sign = (~u_coeff) & 1;
523
76.7k
    const intptr_t coeff =
524
76.7k
        static_cast<intptr_t>((magnitude ^ (neg_sign - 1)) << shift);
525
76.7k
    if (ac_type == ACType::k16) {
526
76.7k
      block.ptr16[order[k]] += coeff;
527
76.7k
    } else {
528
0
      block.ptr32[order[k]] += coeff;
529
0
    }
530
76.7k
    prev = static_cast<size_t>(u_coeff != 0);
531
76.7k
    nzeros -= prev;
532
76.7k
  }
533
154k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
33
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
33
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
33
                       "), channel %" PRIuS,
537
33
                       nzeros, bx, by, c);
538
33
  }
539
540
153k
  return true;
541
154k
}
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
26.1k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
26.1k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
26.1k
  const size_t size = covered_blocks * kDCTBlockSize;
484
26.1k
  int32_t predicted_nzeros =
485
26.1k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
26.1k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
26.1k
  const coeff_order_t* JXL_RESTRICT order =
489
26.1k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
26.1k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
26.1k
  const int32_t nzero_ctx =
493
26.1k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
26.1k
  size_t nzeros =
496
26.1k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
26.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
52.7k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
53.5k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
26.9k
      row_nzeros[bx + x + y * nzeros_stride] =
505
26.9k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
26.9k
    }
507
26.6k
  }
508
509
26.1k
  const size_t histo_offset =
510
26.1k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
26.1k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
97.2k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
71.1k
    const size_t ctx =
515
71.1k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
71.1k
                                          log2_covered_blocks, prev);
517
71.1k
    const size_t u_coeff =
518
71.1k
        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
71.1k
    const size_t magnitude = u_coeff >> 1;
522
71.1k
    const size_t neg_sign = (~u_coeff) & 1;
523
71.1k
    const intptr_t coeff =
524
71.1k
        static_cast<intptr_t>((magnitude ^ (neg_sign - 1)) << shift);
525
71.1k
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
71.1k
    } else {
528
71.1k
      block.ptr32[order[k]] += coeff;
529
71.1k
    }
530
71.1k
    prev = static_cast<size_t>(u_coeff != 0);
531
71.1k
    nzeros -= prev;
532
71.1k
  }
533
26.1k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
11
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
11
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
11
                       "), channel %" PRIuS,
537
11
                       nzeros, bx, by, c);
538
11
  }
539
540
26.1k
  return true;
541
26.1k
}
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
5.57k
  void StartRow(size_t by) override {
550
5.57k
    qf_row = rect.ConstRow(*qf, by);
551
22.3k
    for (size_t c = 0; c < 3; c++) {
552
16.7k
      size_t sby = by >> vshift[c];
553
16.7k
      quant_dc_row = quant_dc->ConstRow(rect.y0() + by) + rect.x0();
554
33.4k
      for (size_t i = 0; i < num_passes; i++) {
555
16.7k
        row_nzeros[i][c] = group_dec_cache->num_nzeroes[i].PlaneRow(c, sby);
556
16.7k
        row_nzeros_top[i][c] =
557
16.7k
            sby == 0
558
16.7k
                ? nullptr
559
16.7k
                : group_dec_cache->num_nzeroes[i].ConstPlaneRow(c, sby - 1);
560
16.7k
      }
561
16.7k
    }
562
5.57k
  }
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
91.9k
                   ACType ac_type) override {
567
91.9k
    ;
568
275k
    for (size_t c : {1, 0, 2}) {
569
275k
      size_t sbx = bx >> hshift[c];
570
275k
      size_t sby = by >> vshift[c];
571
275k
      if (JXL_UNLIKELY((sbx << hshift[c] != bx) || (sby << vshift[c] != by))) {
572
2.84k
        continue;
573
2.84k
      }
574
575
545k
      for (size_t pass = 0; JXL_UNLIKELY(pass < num_passes); pass++) {
576
272k
        auto decode_ac_varblock =
577
272k
            decoders[pass].UsesLZ77()
578
272k
                ? (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 1>
579
92.5k
                                          : DecodeACVarBlock<ACType::k32, 1>)
580
272k
                : (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 0>
581
180k
                                          : DecodeACVarBlock<ACType::k32, 0>);
582
272k
        JXL_RETURN_IF_ERROR(decode_ac_varblock(
583
272k
            ctx_offset[pass], log2_covered_blocks, row_nzeros[pass][c],
584
272k
            row_nzeros_top[pass][c], nzeros_stride, c, sbx, sby, bx, acs,
585
272k
            &coeff_orders[pass * coeff_order_size], readers[pass],
586
272k
            &decoders[pass], context_map[pass], quant_dc_row, qf_row,
587
272k
            *block_ctx_map, block[c], shift_for_pass[pass]));
588
272k
      }
589
272k
    }
590
91.7k
    return true;
591
91.9k
  }
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
1.69k
              PassesDecoderState* dec_state, size_t first_pass) {
598
6.79k
    for (size_t i = 0; i < 3; i++) {
599
5.09k
      hshift[i] = frame_header.chroma_subsampling.HShift(i);
600
5.09k
      vshift[i] = frame_header.chroma_subsampling.VShift(i);
601
5.09k
    }
602
1.69k
    coeff_order_size = dec_state->shared->coeff_order_size;
603
1.69k
    coeff_orders =
604
1.69k
        dec_state->shared->coeff_orders.data() + first_pass * coeff_order_size;
605
1.69k
    context_map = dec_state->context_map.data() + first_pass;
606
1.69k
    readers = readers_;
607
1.69k
    num_passes = num_passes_;
608
1.69k
    shift_for_pass = frame_header.passes.shift + first_pass;
609
1.69k
    group_dec_cache = group_dec_cache_;
610
1.69k
    rect = rect_;
611
1.69k
    block_ctx_map = &dec_state->shared->block_ctx_map;
612
1.69k
    qf = &dec_state->shared->raw_quant_field;
613
1.69k
    quant_dc = &dec_state->shared->quant_dc;
614
615
3.40k
    for (size_t pass = 0; pass < num_passes; pass++) {
616
      // Select which histogram set to use among those of the current pass.
617
1.70k
      size_t cur_histogram = 0;
618
1.70k
      if (histo_selector_bits != 0) {
619
9
        cur_histogram = readers[pass]->ReadBits(histo_selector_bits);
620
9
      }
621
1.70k
      if (cur_histogram >= dec_state->shared->num_histograms) {
622
0
        return JXL_FAILURE("Invalid histogram selector");
623
0
      }
624
1.70k
      ctx_offset[pass] = cur_histogram * block_ctx_map->NumACContexts();
625
626
1.70k
      JXL_ASSIGN_OR_RETURN(
627
1.70k
          decoders[pass],
628
1.70k
          ANSSymbolReader::Create(&dec_state->code[pass + first_pass],
629
1.70k
                                  readers[pass]));
630
1.70k
    }
631
1.69k
    nzeros_stride = group_dec_cache->num_nzeroes[0].PixelsPerRow();
632
3.40k
    for (size_t i = 0; i < num_passes; i++) {
633
1.70k
      JXL_ENSURE(
634
1.70k
          nzeros_stride ==
635
1.70k
          static_cast<size_t>(group_dec_cache->num_nzeroes[i].PixelsPerRow()));
636
1.70k
    }
637
1.69k
    return true;
638
1.69k
  }
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
43.4k
  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
725k
                   ACType ac_type) override {
667
725k
    JXL_ENSURE(ac_type == ACType::k32);
668
2.90M
    for (size_t c = 0; c < 3; c++) {
669
      // for each pass
670
4.35M
      for (size_t i = 0; i < quantized_ac->size(); i++) {
671
231M
        for (size_t k = 0; k < size; k++) {
672
          // TODO(veluca): SIMD.
673
229M
          block[c].ptr32[k] +=
674
229M
              rows[i][c][offset + k] * (1 << shift_for_pass[i]);
675
229M
        }
676
2.17M
      }
677
2.17M
    }
678
725k
    offset += size;
679
725k
    return true;
680
725k
  }
681
682
  static StatusOr<GetBlockFromEncoder> Create(
683
      const std::vector<std::unique_ptr<ACImage>>& ac, size_t group_idx,
684
1.78k
      const uint32_t* shift_for_pass) {
685
1.78k
    GetBlockFromEncoder result(ac, group_idx, shift_for_pass);
686
    // TODO(veluca): not supported with chroma subsampling.
687
3.57k
    for (size_t i = 0; i < ac.size(); i++) {
688
1.78k
      JXL_ENSURE(ac[i]->Type() == ACType::k32);
689
7.14k
      for (size_t c = 0; c < 3; c++) {
690
5.35k
        result.rows[i][c] = ac[i]->PlaneRow(c, group_idx, 0).ptr32;
691
5.35k
      }
692
1.78k
    }
693
1.78k
    return result;
694
1.78k
  }
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
1.78k
      : 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
1.69k
                   bool force_draw, bool dc_only, bool* should_run_pipeline) {
719
1.69k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
720
1.69k
  DrawMode draw =
721
1.69k
      (num_passes + first_pass == frame_header.passes.num_passes) || force_draw
722
1.69k
          ? kDraw
723
1.69k
          : kDontDraw;
724
725
1.69k
  if (should_run_pipeline) {
726
1.69k
    *should_run_pipeline = draw != kDontDraw;
727
1.69k
  }
728
729
1.69k
  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 (ssize_t iy = 0; iy < 5; iy++) {
774
0
          input_rows[0][iy] = group_dec_cache->dc_buffer.Row(
775
0
              Mirror(static_cast<ssize_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
1.69k
  size_t histo_selector_bits = 0;
794
1.69k
  if (dc_only) {
795
0
    JXL_ENSURE(num_passes == 0);
796
1.69k
  } else {
797
1.69k
    JXL_ENSURE(dec_state->shared->num_histograms > 0);
798
1.69k
    histo_selector_bits = CeilLog2Nonzero(dec_state->shared->num_histograms);
799
1.69k
  }
800
801
1.69k
  auto get_block = jxl::make_unique<GetBlockFromBitstream>();
802
1.69k
  JXL_RETURN_IF_ERROR(get_block->Init(
803
1.69k
      frame_header, readers, num_passes, group_idx, histo_selector_bits,
804
1.69k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx), group_dec_cache,
805
1.69k
      dec_state, first_pass));
806
807
1.69k
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
808
1.69k
      frame_header, get_block.get(), group_dec_cache, dec_state, thread,
809
1.69k
      group_idx, render_pipeline_input, jpeg_data, draw));
810
811
3.01k
  for (size_t pass = 0; pass < num_passes; pass++) {
812
1.50k
    if (!get_block->decoders[pass].CheckANSFinalState()) {
813
0
      return JXL_FAILURE("ANS checksum failure.");
814
0
    }
815
1.50k
  }
816
1.50k
  return true;
817
1.50k
}
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
1.78k
                               AuxOut* aux_out) {
828
1.78k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
829
1.78k
  JXL_ASSIGN_OR_RETURN(
830
1.78k
      GetBlockFromEncoder get_block,
831
1.78k
      GetBlockFromEncoder::Create(ac, group_idx, frame_header.passes.shift));
832
1.78k
  JXL_RETURN_IF_ERROR(group_dec_cache->InitOnce(
833
1.78k
      memory_manager,
834
1.78k
      /*num_passes=*/0,
835
1.78k
      /*used_acs=*/(1u << AcStrategy::kNumValidStrategies) - 1));
836
837
1.78k
  return HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
838
1.78k
      frame_header, &get_block, group_dec_cache, dec_state, thread, group_idx,
839
1.78k
      render_pipeline_input, jpeg_data, kDraw);
840
1.78k
}
841
842
}  // namespace jxl
843
#endif  // HWY_ONCE