Coverage Report

Created: 2026-06-30 07:12

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