Coverage Report

Created: 2025-11-16 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/dec_group.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/dec_group.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <array>
12
#include <cstdint>
13
#include <cstdio>
14
#include <cstdlib>
15
#include <cstring>
16
#include <memory>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/base/compiler_specific.h"
21
#include "lib/jxl/chroma_from_luma.h"
22
#include "lib/jxl/coeff_order_fwd.h"
23
#include "lib/jxl/dct_util.h"
24
#include "lib/jxl/dec_ans.h"
25
#include "lib/jxl/frame_dimensions.h"
26
#include "lib/jxl/frame_header.h"
27
#include "lib/jxl/image.h"
28
#include "lib/jxl/image_ops.h"
29
#include "lib/jxl/jpeg/jpeg_data.h"
30
#include "lib/jxl/render_pipeline/render_pipeline.h"
31
#include "lib/jxl/render_pipeline/render_pipeline_stage.h"
32
33
#undef HWY_TARGET_INCLUDE
34
#define HWY_TARGET_INCLUDE "lib/jxl/dec_group.cc"
35
#include <hwy/foreach_target.h>
36
#include <hwy/highway.h>
37
38
#include "lib/jxl/ac_context.h"
39
#include "lib/jxl/ac_strategy.h"
40
#include "lib/jxl/base/bits.h"
41
#include "lib/jxl/base/common.h"
42
#include "lib/jxl/base/printf_macros.h"
43
#include "lib/jxl/base/rect.h"
44
#include "lib/jxl/base/status.h"
45
#include "lib/jxl/coeff_order.h"
46
#include "lib/jxl/common.h"  // kMaxNumPasses
47
#include "lib/jxl/dec_cache.h"
48
#include "lib/jxl/dec_transforms-inl.h"
49
#include "lib/jxl/dec_xyb.h"
50
#include "lib/jxl/entropy_coder.h"
51
#include "lib/jxl/quant_weights.h"
52
#include "lib/jxl/quantizer-inl.h"
53
#include "lib/jxl/quantizer.h"
54
55
#ifndef LIB_JXL_DEC_GROUP_CC
56
#define LIB_JXL_DEC_GROUP_CC
57
namespace jxl {
58
59
struct AuxOut;
60
61
// Interface for reading groups for DecodeGroupImpl.
62
class GetBlock {
63
 public:
64
  virtual void StartRow(size_t by) = 0;
65
  virtual Status LoadBlock(size_t bx, size_t by, const AcStrategy& acs,
66
                           size_t size, size_t log2_covered_blocks,
67
                           ACPtr block[3], ACType ac_type) = 0;
68
28.8k
  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
327
void Transpose8x8InPlace(int32_t* JXL_RESTRICT block) {
107
2.94k
  for (size_t x = 0; x < 8; x++) {
108
11.7k
    for (size_t y = x + 1; y < 8; y++) {
109
9.15k
      std::swap(block[y * 8 + x], block[x * 8 + y]);
110
9.15k
    }
111
2.61k
  }
112
327
}
jxl::N_SSE4::Transpose8x8InPlace(int*)
Line
Count
Source
106
68
void Transpose8x8InPlace(int32_t* JXL_RESTRICT block) {
107
612
  for (size_t x = 0; x < 8; x++) {
108
2.44k
    for (size_t y = x + 1; y < 8; y++) {
109
1.90k
      std::swap(block[y * 8 + x], block[x * 8 + y]);
110
1.90k
    }
111
544
  }
112
68
}
jxl::N_AVX2::Transpose8x8InPlace(int*)
Line
Count
Source
106
235
void Transpose8x8InPlace(int32_t* JXL_RESTRICT block) {
107
2.11k
  for (size_t x = 0; x < 8; x++) {
108
8.46k
    for (size_t y = x + 1; y < 8; y++) {
109
6.58k
      std::swap(block[y * 8 + x], block[x * 8 + y]);
110
6.58k
    }
111
1.88k
  }
112
235
}
jxl::N_SSE2::Transpose8x8InPlace(int*)
Line
Count
Source
106
24
void Transpose8x8InPlace(int32_t* JXL_RESTRICT block) {
107
216
  for (size_t x = 0; x < 8; x++) {
108
864
    for (size_t y = x + 1; y < 8; y++) {
109
672
      std::swap(block[y * 8 + x], block[x * 8 + y]);
110
672
    }
111
192
  }
112
24
}
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
22.6M
                 float* JXL_RESTRICT block) {
121
22.6M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
22.6M
  const auto y_mul =
123
22.6M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
22.6M
  const auto b_mul =
125
22.6M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
22.6M
  Vec<DI> quantized_x_int;
128
22.6M
  Vec<DI> quantized_y_int;
129
22.6M
  Vec<DI> quantized_b_int;
130
22.6M
  if (ac_type == ACType::k16) {
131
13.6M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
13.6M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
13.6M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
13.6M
  } else {
135
9.04M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
9.04M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
9.04M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
9.04M
  }
139
140
22.6M
  const auto dequant_x_cc =
141
22.6M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
22.6M
  const auto dequant_y =
143
22.6M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
22.6M
  const auto dequant_b_cc =
145
22.6M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
22.6M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
22.6M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
22.6M
  Store(dequant_x, d, block + k);
150
22.6M
  Store(dequant_y, d, block + size + k);
151
22.6M
  Store(dequant_b, d, block + 2 * size + k);
152
22.6M
}
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*)
Line
Count
Source
120
3.30M
                 float* JXL_RESTRICT block) {
121
3.30M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
3.30M
  const auto y_mul =
123
3.30M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
3.30M
  const auto b_mul =
125
3.30M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
3.30M
  Vec<DI> quantized_x_int;
128
3.30M
  Vec<DI> quantized_y_int;
129
3.30M
  Vec<DI> quantized_b_int;
130
3.30M
  if (ac_type == ACType::k16) {
131
3.30M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
3.30M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
3.30M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
3.30M
  } else {
135
3.56k
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
3.56k
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
3.56k
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
3.56k
  }
139
140
3.30M
  const auto dequant_x_cc =
141
3.30M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
3.30M
  const auto dequant_y =
143
3.30M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
3.30M
  const auto dequant_b_cc =
145
3.30M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
3.30M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
3.30M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
3.30M
  Store(dequant_x, d, block + k);
150
3.30M
  Store(dequant_y, d, block + size + k);
151
3.30M
  Store(dequant_b, d, block + 2 * size + k);
152
3.30M
}
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*)
Line
Count
Source
120
4.09M
                 float* JXL_RESTRICT block) {
121
4.09M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
4.09M
  const auto y_mul =
123
4.09M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
4.09M
  const auto b_mul =
125
4.09M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
4.09M
  Vec<DI> quantized_x_int;
128
4.09M
  Vec<DI> quantized_y_int;
129
4.09M
  Vec<DI> quantized_b_int;
130
4.09M
  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
4.09M
  } else {
135
4.09M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
4.09M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
4.09M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
4.09M
  }
139
140
4.09M
  const auto dequant_x_cc =
141
4.09M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
4.09M
  const auto dequant_y =
143
4.09M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
4.09M
  const auto dequant_b_cc =
145
4.09M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
4.09M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
4.09M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
4.09M
  Store(dequant_x, d, block + k);
150
4.09M
  Store(dequant_y, d, block + size + k);
151
4.09M
  Store(dequant_b, d, block + 2 * size + k);
152
4.09M
}
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
7.32M
                 float* JXL_RESTRICT block) {
121
7.32M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
7.32M
  const auto y_mul =
123
7.32M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
7.32M
  const auto b_mul =
125
7.32M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
7.32M
  Vec<DI> quantized_x_int;
128
7.32M
  Vec<DI> quantized_y_int;
129
7.32M
  Vec<DI> quantized_b_int;
130
7.32M
  if (ac_type == ACType::k16) {
131
7.32M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
7.32M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
7.32M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
7.32M
  } else {
135
14
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
14
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
14
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
14
  }
139
140
7.32M
  const auto dequant_x_cc =
141
7.32M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
7.32M
  const auto dequant_y =
143
7.32M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
7.32M
  const auto dequant_b_cc =
145
7.32M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
7.32M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
7.32M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
7.32M
  Store(dequant_x, d, block + k);
150
7.32M
  Store(dequant_y, d, block + size + k);
151
7.32M
  Store(dequant_b, d, block + 2 * size + k);
152
7.32M
}
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
2.63M
                 float* JXL_RESTRICT block) {
121
2.63M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
2.63M
  const auto y_mul =
123
2.63M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
2.63M
  const auto b_mul =
125
2.63M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
2.63M
  Vec<DI> quantized_x_int;
128
2.63M
  Vec<DI> quantized_y_int;
129
2.63M
  Vec<DI> quantized_b_int;
130
2.63M
  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
2.63M
  } else {
135
2.63M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
2.63M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
2.63M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
2.63M
  }
139
140
2.63M
  const auto dequant_x_cc =
141
2.63M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
2.63M
  const auto dequant_y =
143
2.63M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
2.63M
  const auto dequant_b_cc =
145
2.63M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
2.63M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
2.63M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
2.63M
  Store(dequant_x, d, block + k);
150
2.63M
  Store(dequant_y, d, block + size + k);
151
2.63M
  Store(dequant_b, d, block + 2 * size + k);
152
2.63M
}
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*)
Line
Count
Source
120
3.02M
                 float* JXL_RESTRICT block) {
121
3.02M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
3.02M
  const auto y_mul =
123
3.02M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
3.02M
  const auto b_mul =
125
3.02M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
3.02M
  Vec<DI> quantized_x_int;
128
3.02M
  Vec<DI> quantized_y_int;
129
3.02M
  Vec<DI> quantized_b_int;
130
3.02M
  if (ac_type == ACType::k16) {
131
3.01M
    quantized_x_int = PromoteTo(di, Load(di16, qblock[0].ptr16 + k));
132
3.01M
    quantized_y_int = PromoteTo(di, Load(di16, qblock[1].ptr16 + k));
133
3.01M
    quantized_b_int = PromoteTo(di, Load(di16, qblock[2].ptr16 + k));
134
3.01M
  } else {
135
4.63k
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
4.63k
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
4.63k
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
4.63k
  }
139
140
3.02M
  const auto dequant_x_cc =
141
3.02M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
3.02M
  const auto dequant_y =
143
3.02M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
3.02M
  const auto dequant_b_cc =
145
3.02M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
3.02M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
3.02M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
3.02M
  Store(dequant_x, d, block + k);
150
3.02M
  Store(dequant_y, d, block + size + k);
151
3.02M
  Store(dequant_b, d, block + 2 * size + k);
152
3.02M
}
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*)
Line
Count
Source
120
2.31M
                 float* JXL_RESTRICT block) {
121
2.31M
  const auto x_mul = Mul(Load(d, dequant_matrices + k), scaled_dequant_x);
122
2.31M
  const auto y_mul =
123
2.31M
      Mul(Load(d, dequant_matrices + size + k), scaled_dequant_y);
124
2.31M
  const auto b_mul =
125
2.31M
      Mul(Load(d, dequant_matrices + 2 * size + k), scaled_dequant_b);
126
127
2.31M
  Vec<DI> quantized_x_int;
128
2.31M
  Vec<DI> quantized_y_int;
129
2.31M
  Vec<DI> quantized_b_int;
130
2.31M
  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
2.31M
  } else {
135
2.31M
    quantized_x_int = Load(di, qblock[0].ptr32 + k);
136
2.31M
    quantized_y_int = Load(di, qblock[1].ptr32 + k);
137
2.31M
    quantized_b_int = Load(di, qblock[2].ptr32 + k);
138
2.31M
  }
139
140
2.31M
  const auto dequant_x_cc =
141
2.31M
      Mul(AdjustQuantBias(di, 0, quantized_x_int, biases), x_mul);
142
2.31M
  const auto dequant_y =
143
2.31M
      Mul(AdjustQuantBias(di, 1, quantized_y_int, biases), y_mul);
144
2.31M
  const auto dequant_b_cc =
145
2.31M
      Mul(AdjustQuantBias(di, 2, quantized_b_int, biases), b_mul);
146
147
2.31M
  const auto dequant_x = MulAdd(x_cc_mul, dequant_y, dequant_x_cc);
148
2.31M
  const auto dequant_b = MulAdd(b_cc_mul, dequant_y, dequant_b_cc);
149
2.31M
  Store(dequant_x, d, block + k);
150
2.31M
  Store(dequant_y, d, block + size + k);
151
2.31M
  Store(dequant_b, d, block + 2 * size + k);
152
2.31M
}
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
1.62M
                  float* JXL_RESTRICT scratch) {
163
1.62M
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
1.62M
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
1.62M
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
1.62M
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
1.62M
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
24.3M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
22.6M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
22.6M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
22.6M
                         qblock, block);
175
22.6M
  }
176
6.49M
  for (size_t c = 0; c < 3; c++) {
177
4.87M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
4.87M
                            block + c * size, scratch);
179
4.87M
  }
180
1.62M
}
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*)
Line
Count
Source
162
119k
                  float* JXL_RESTRICT scratch) {
163
119k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
119k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
119k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
119k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
119k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
3.42M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
3.30M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
3.30M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
3.30M
                         qblock, block);
175
3.30M
  }
176
475k
  for (size_t c = 0; c < 3; c++) {
177
356k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
356k
                            block + c * size, scratch);
179
356k
  }
180
119k
}
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*)
Line
Count
Source
162
239k
                  float* JXL_RESTRICT scratch) {
163
239k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
239k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
239k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
239k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
239k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
4.32M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
4.09M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
4.09M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
4.09M
                         qblock, block);
175
4.09M
  }
176
955k
  for (size_t c = 0; c < 3; c++) {
177
716k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
716k
                            block + c * size, scratch);
179
716k
  }
180
239k
}
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
752k
                  float* JXL_RESTRICT scratch) {
163
752k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
752k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
752k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
752k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
752k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
8.08M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
7.32M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
7.32M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
7.32M
                         qblock, block);
175
7.32M
  }
176
3.00M
  for (size_t c = 0; c < 3; c++) {
177
2.25M
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
2.25M
                            block + c * size, scratch);
179
2.25M
  }
180
752k
}
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
273k
                  float* JXL_RESTRICT scratch) {
163
273k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
273k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
273k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
273k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
273k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
2.90M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
2.63M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
2.63M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
2.63M
                         qblock, block);
175
2.63M
  }
176
1.09M
  for (size_t c = 0; c < 3; c++) {
177
817k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
817k
                            block + c * size, scratch);
179
817k
  }
180
273k
}
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*)
Line
Count
Source
162
116k
                  float* JXL_RESTRICT scratch) {
163
116k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
116k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
116k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
116k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
116k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
3.13M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
3.01M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
3.01M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
3.01M
                         qblock, block);
175
3.01M
  }
176
465k
  for (size_t c = 0; c < 3; c++) {
177
349k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
349k
                            block + c * size, scratch);
179
349k
  }
180
116k
}
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*)
Line
Count
Source
162
124k
                  float* JXL_RESTRICT scratch) {
163
124k
  const auto scaled_dequant_s = inv_global_scale / quant;
164
165
124k
  const auto scaled_dequant_x = Set(d, scaled_dequant_s * x_dm_multiplier);
166
124k
  const auto scaled_dequant_y = Set(d, scaled_dequant_s);
167
124k
  const auto scaled_dequant_b = Set(d, scaled_dequant_s * b_dm_multiplier);
168
169
124k
  const float* dequant_matrices = quantizer.DequantMatrix(kind, 0);
170
171
2.43M
  for (size_t k = 0; k < covered_blocks * kDCTBlockSize; k += Lanes(d)) {
172
2.31M
    DequantLane<ac_type>(scaled_dequant_x, scaled_dequant_y, scaled_dequant_b,
173
2.31M
                         dequant_matrices, size, k, x_cc_mul, b_cc_mul, biases,
174
2.31M
                         qblock, block);
175
2.31M
  }
176
498k
  for (size_t c = 0; c < 3; c++) {
177
373k
    LowestFrequenciesFromDC(kind, dc_row[c] + sbx[c], dc_stride,
178
373k
                            block + c * size, scratch);
179
373k
  }
180
124k
}
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
27.2k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
27.2k
  const Rect block_rect =
191
27.2k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
27.2k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
27.2k
  const size_t xsize_blocks = block_rect.xsize();
195
27.2k
  const size_t ysize_blocks = block_rect.ysize();
196
197
27.2k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
27.2k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
27.2k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
27.2k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
27.2k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
27.2k
  size_t idct_stride[3];
207
109k
  for (size_t c = 0; c < 3; c++) {
208
81.7k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
81.7k
  }
210
211
27.2k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
27.2k
  ACType ac_type = dec_state->coefficients->Type();
214
27.2k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
27.2k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
27.2k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
27.2k
  size_t offset = 0;
221
222
27.2k
  std::array<int, 3> jpeg_c_map;
223
27.2k
  bool jpeg_is_gray = false;
224
27.2k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
27.2k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
27.2k
  if (jpeg_data) {
229
367
    if (!color_correlation.IsJPEGCompatible()) {
230
19
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
19
    }
232
348
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
348
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
348
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
348
    const std::vector<QuantEncoding>& qe =
236
348
        dec_state->shared->matrices.encodings();
237
348
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
348
        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
348
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
348
    int* qtable = qe[0].qraw.qtable->data();
244
1.36k
    for (size_t c = 0; c < 3; c++) {
245
1.03k
      if (frame_header.color_transform == ColorTransform::kNone) {
246
66
        dcoff[c] = 1024 / qtable[64 * c];
247
66
      }
248
66.1k
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
65.1k
        int num = qtable[64 + i];
251
65.1k
        int den = qtable[64 * c + i];
252
65.1k
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
17
          return JXL_FAILURE("Invalid JPEG quantization table");
254
17
        }
255
65.0k
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
65.0k
            (1 << kCFLFixedPointPrecision) * num / den;
257
65.0k
      }
258
1.03k
    }
259
348
  }
260
261
27.2k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
27.2k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
27.2k
  Rect r[3];
264
108k
  for (size_t i = 0; i < 3; i++) {
265
81.6k
    r[i] =
266
81.6k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
81.6k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
81.6k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
81.6k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
81.6k
  }
273
274
263k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
236k
    get_block->StartRow(by);
276
236k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
236k
    const int32_t* JXL_RESTRICT row_quant =
279
236k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
236k
    const float* JXL_RESTRICT dc_rows[3] = {
282
236k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
236k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
236k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
236k
    };
286
287
236k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
236k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
236k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
236k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
236k
        nullptr,
293
236k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
236k
    };
295
296
236k
    float* JXL_RESTRICT idct_row[3];
297
236k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
945k
    for (size_t c = 0; c < 3; c++) {
299
708k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
708k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
708k
      if (jpeg_data) {
302
993
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
993
        jpeg_row[c] =
304
993
            component.coeffs.data() +
305
993
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
993
                kDCTBlockSize;
307
993
      }
308
708k
    }
309
310
236k
    size_t bx = 0;
311
627k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
392k
         tx++) {
313
392k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
392k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
392k
      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
2.12M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
1.73M
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
1.73M
        AcStrategy acs = acs_row[bx];
321
1.73M
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
1.73M
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
102k
          bx += llf_x;
326
102k
          continue;
327
102k
        }
328
1.63M
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
1.63M
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
1.63M
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
1.63M
        ACPtr qblock[3];
334
1.63M
        if (accumulate) {
335
22.9k
          for (size_t c = 0; c < 3; c++) {
336
17.1k
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
17.1k
          }
338
1.62M
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
1.62M
          JXL_ENSURE(draw == kDraw);
342
1.62M
          if (ac_type == ACType::k16) {
343
987k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
987k
                   size * 3 * sizeof(int16_t));
345
3.95M
            for (size_t c = 0; c < 3; c++) {
346
2.96M
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
2.96M
            }
348
987k
          } else {
349
636k
            memset(group_dec_cache->dec_group_qblock, 0,
350
636k
                   size * 3 * sizeof(int32_t));
351
2.54M
            for (size_t c = 0; c < 3; c++) {
352
1.91M
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
1.91M
            }
354
636k
          }
355
1.62M
        }
356
1.63M
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
1.63M
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
1.62M
        offset += size;
359
1.62M
        if (draw == kDontDraw) {
360
4.45k
          bx += llf_x;
361
4.45k
          continue;
362
4.45k
        }
363
364
1.62M
        if (JXL_UNLIKELY(jpeg_data)) {
365
330
          if (acs.Strategy() != AcStrategyType::DCT) {
366
3
            return JXL_FAILURE(
367
3
                "Can only decode to JPEG if only DCT-8 is used.");
368
3
          }
369
370
327
          HWY_ALIGN int32_t transposed_dct_y[64];
371
975
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
975
            if (jpeg_is_gray && c != 1) {
374
648
              continue;
375
648
            }
376
327
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
327
            int16_t* JXL_RESTRICT jpeg_pos =
380
327
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
327
            auto* transposed_dct = qblock[c].ptr32;
383
327
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
327
            if (!cs.Is444() ||
386
327
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
2.91k
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
2.65k
                const auto ini = Load(di, transposed_dct + i);
389
2.65k
                const auto ini16 = DemoteTo(di16, ini);
390
2.65k
                StoreU(ini16, di16, jpeg_pos + i);
391
2.65k
              }
392
257
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
766
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
696
                const auto ini = Load(di, transposed_dct + i);
396
696
                Store(ini, di, transposed_dct_y + i);
397
696
                const auto ini16 = DemoteTo(di16, ini);
398
696
                StoreU(ini16, di16, jpeg_pos + i);
399
696
              }
400
70
            } 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
327
            jpeg_pos[0] =
417
327
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
327
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
327
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
2.00k
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
1.67k
              auto in = LoadU(di16_full, jpeg_pos + i);
422
1.67k
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
1.67k
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
1.67k
            }
425
327
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
3
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
3
            }
428
327
          }
429
1.62M
        } else {
430
1.62M
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
1.62M
          dequant_block(
433
1.62M
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
1.62M
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
1.62M
              size, dec_state->shared->quantizer,
436
1.62M
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
1.62M
              dc_stride,
438
1.62M
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
1.62M
              block, group_dec_cache->scratch_space);
440
441
4.86M
          for (size_t c : {1, 0, 2}) {
442
4.86M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
1.11M
              continue;
444
1.11M
            }
445
            // IDCT
446
3.75M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
3.75M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
3.75M
                              idct_stride[c], group_dec_cache->scratch_space);
449
3.75M
          }
450
1.62M
        }
451
1.62M
        bx += llf_x;
452
1.62M
      }
453
392k
    }
454
236k
  }
455
26.4k
  return true;
456
27.2k
}
jxl::N_SSE4::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
4.96k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
4.96k
  const Rect block_rect =
191
4.96k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
4.96k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
4.96k
  const size_t xsize_blocks = block_rect.xsize();
195
4.96k
  const size_t ysize_blocks = block_rect.ysize();
196
197
4.96k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
4.96k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
4.96k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
4.96k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
4.96k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
4.96k
  size_t idct_stride[3];
207
19.8k
  for (size_t c = 0; c < 3; c++) {
208
14.8k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
14.8k
  }
210
211
4.96k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
4.96k
  ACType ac_type = dec_state->coefficients->Type();
214
4.96k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
4.96k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
4.96k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
4.96k
  size_t offset = 0;
221
222
4.96k
  std::array<int, 3> jpeg_c_map;
223
4.96k
  bool jpeg_is_gray = false;
224
4.96k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
4.96k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
4.96k
  if (jpeg_data) {
229
80
    if (!color_correlation.IsJPEGCompatible()) {
230
5
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
5
    }
232
75
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
75
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
75
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
75
    const std::vector<QuantEncoding>& qe =
236
75
        dec_state->shared->matrices.encodings();
237
75
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
75
        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
75
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
75
    int* qtable = qe[0].qraw.qtable->data();
244
290
    for (size_t c = 0; c < 3; c++) {
245
221
      if (frame_header.color_transform == ColorTransform::kNone) {
246
15
        dcoff[c] = 1024 / qtable[64 * c];
247
15
      }
248
14.0k
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
13.8k
        int num = qtable[64 + i];
251
13.8k
        int den = qtable[64 * c + i];
252
13.8k
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
6
          return JXL_FAILURE("Invalid JPEG quantization table");
254
6
        }
255
13.8k
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
13.8k
            (1 << kCFLFixedPointPrecision) * num / den;
257
13.8k
      }
258
221
    }
259
75
  }
260
261
4.95k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
4.95k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
4.95k
  Rect r[3];
264
19.8k
  for (size_t i = 0; i < 3; i++) {
265
14.8k
    r[i] =
266
14.8k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
14.8k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
14.8k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
14.8k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
14.8k
  }
273
274
71.4k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
66.6k
    get_block->StartRow(by);
276
66.6k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
66.6k
    const int32_t* JXL_RESTRICT row_quant =
279
66.6k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
66.6k
    const float* JXL_RESTRICT dc_rows[3] = {
282
66.6k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
66.6k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
66.6k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
66.6k
    };
286
287
66.6k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
66.6k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
66.6k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
66.6k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
66.6k
        nullptr,
293
66.6k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
66.6k
    };
295
296
66.6k
    float* JXL_RESTRICT idct_row[3];
297
66.6k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
266k
    for (size_t c = 0; c < 3; c++) {
299
199k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
199k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
199k
      if (jpeg_data) {
302
207
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
207
        jpeg_row[c] =
304
207
            component.coeffs.data() +
305
207
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
207
                kDCTBlockSize;
307
207
      }
308
199k
    }
309
310
66.6k
    size_t bx = 0;
311
165k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
99.3k
         tx++) {
313
99.3k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
99.3k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
99.3k
      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
486k
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
387k
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
387k
        AcStrategy acs = acs_row[bx];
321
387k
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
387k
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
29.0k
          bx += llf_x;
326
29.0k
          continue;
327
29.0k
        }
328
358k
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
358k
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
358k
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
358k
        ACPtr qblock[3];
334
358k
        if (accumulate) {
335
100
          for (size_t c = 0; c < 3; c++) {
336
75
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
75
          }
338
358k
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
358k
          JXL_ENSURE(draw == kDraw);
342
358k
          if (ac_type == ACType::k16) {
343
119k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
119k
                   size * 3 * sizeof(int16_t));
345
476k
            for (size_t c = 0; c < 3; c++) {
346
357k
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
357k
            }
348
239k
          } else {
349
239k
            memset(group_dec_cache->dec_group_qblock, 0,
350
239k
                   size * 3 * sizeof(int32_t));
351
956k
            for (size_t c = 0; c < 3; c++) {
352
717k
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
717k
            }
354
239k
          }
355
358k
        }
356
358k
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
358k
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
358k
        offset += size;
359
358k
        if (draw == kDontDraw) {
360
24
          bx += llf_x;
361
24
          continue;
362
24
        }
363
364
358k
        if (JXL_UNLIKELY(jpeg_data)) {
365
69
          if (acs.Strategy() != AcStrategyType::DCT) {
366
1
            return JXL_FAILURE(
367
1
                "Can only decode to JPEG if only DCT-8 is used.");
368
1
          }
369
370
68
          HWY_ALIGN int32_t transposed_dct_y[64];
371
202
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
202
            if (jpeg_is_gray && c != 1) {
374
134
              continue;
375
134
            }
376
68
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
68
            int16_t* JXL_RESTRICT jpeg_pos =
380
68
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
68
            auto* transposed_dct = qblock[c].ptr32;
383
68
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
68
            if (!cs.Is444() ||
386
68
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
1.03k
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
976
                const auto ini = Load(di, transposed_dct + i);
389
976
                const auto ini16 = DemoteTo(di16, ini);
390
976
                StoreU(ini16, di16, jpeg_pos + i);
391
976
              }
392
61
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
119
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
112
                const auto ini = Load(di, transposed_dct + i);
396
112
                Store(ini, di, transposed_dct_y + i);
397
112
                const auto ini16 = DemoteTo(di16, ini);
398
112
                StoreU(ini16, di16, jpeg_pos + i);
399
112
              }
400
7
            } 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
68
            jpeg_pos[0] =
417
68
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
68
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
68
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
612
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
544
              auto in = LoadU(di16_full, jpeg_pos + i);
422
544
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
544
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
544
            }
425
68
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
1
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
1
            }
428
68
          }
429
358k
        } else {
430
358k
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
358k
          dequant_block(
433
358k
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
358k
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
358k
              size, dec_state->shared->quantizer,
436
358k
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
358k
              dc_stride,
438
358k
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
358k
              block, group_dec_cache->scratch_space);
440
441
1.07M
          for (size_t c : {1, 0, 2}) {
442
1.07M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
354k
              continue;
444
354k
            }
445
            // IDCT
446
718k
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
718k
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
718k
                              idct_stride[c], group_dec_cache->scratch_space);
449
718k
          }
450
358k
        }
451
358k
        bx += llf_x;
452
358k
      }
453
99.3k
    }
454
66.6k
  }
455
4.79k
  return true;
456
4.95k
}
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
18.3k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
18.3k
  const Rect block_rect =
191
18.3k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
18.3k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
18.3k
  const size_t xsize_blocks = block_rect.xsize();
195
18.3k
  const size_t ysize_blocks = block_rect.ysize();
196
197
18.3k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
18.3k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
18.3k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
18.3k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
18.3k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
18.3k
  size_t idct_stride[3];
207
73.2k
  for (size_t c = 0; c < 3; c++) {
208
54.9k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
54.9k
  }
210
211
18.3k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
18.3k
  ACType ac_type = dec_state->coefficients->Type();
214
18.3k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
18.3k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
18.3k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
18.3k
  size_t offset = 0;
221
222
18.3k
  std::array<int, 3> jpeg_c_map;
223
18.3k
  bool jpeg_is_gray = false;
224
18.3k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
18.3k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
18.3k
  if (jpeg_data) {
229
249
    if (!color_correlation.IsJPEGCompatible()) {
230
8
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
8
    }
232
241
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
241
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
241
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
241
    const std::vector<QuantEncoding>& qe =
236
241
        dec_state->shared->matrices.encodings();
237
241
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
241
        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
241
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
241
    int* qtable = qe[0].qraw.qtable->data();
244
955
    for (size_t c = 0; c < 3; c++) {
245
719
      if (frame_header.color_transform == ColorTransform::kNone) {
246
21
        dcoff[c] = 1024 / qtable[64 * c];
247
21
      }
248
46.4k
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
45.7k
        int num = qtable[64 + i];
251
45.7k
        int den = qtable[64 * c + i];
252
45.7k
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
5
          return JXL_FAILURE("Invalid JPEG quantization table");
254
5
        }
255
45.7k
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
45.7k
            (1 << kCFLFixedPointPrecision) * num / den;
257
45.7k
      }
258
719
    }
259
241
  }
260
261
18.3k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
18.3k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
18.3k
  Rect r[3];
264
73.2k
  for (size_t i = 0; i < 3; i++) {
265
54.9k
    r[i] =
266
54.9k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
54.9k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
54.9k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
54.9k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
54.9k
  }
273
274
128k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
110k
    get_block->StartRow(by);
276
110k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
110k
    const int32_t* JXL_RESTRICT row_quant =
279
110k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
110k
    const float* JXL_RESTRICT dc_rows[3] = {
282
110k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
110k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
110k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
110k
    };
286
287
110k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
110k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
110k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
110k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
110k
        nullptr,
293
110k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
110k
    };
295
296
110k
    float* JXL_RESTRICT idct_row[3];
297
110k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
443k
    for (size_t c = 0; c < 3; c++) {
299
332k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
332k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
332k
      if (jpeg_data) {
302
708
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
708
        jpeg_row[c] =
304
708
            component.coeffs.data() +
305
708
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
708
                kDCTBlockSize;
307
708
      }
308
332k
    }
309
310
110k
    size_t bx = 0;
311
320k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
209k
         tx++) {
313
209k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
209k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
209k
      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.28M
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
1.07M
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
1.07M
        AcStrategy acs = acs_row[bx];
321
1.07M
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
1.07M
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
45.0k
          bx += llf_x;
326
45.0k
          continue;
327
45.0k
        }
328
1.03M
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
1.03M
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
1.03M
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
1.03M
        ACPtr qblock[3];
334
1.03M
        if (accumulate) {
335
22.6k
          for (size_t c = 0; c < 3; c++) {
336
17.0k
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
17.0k
          }
338
1.02M
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
1.02M
          JXL_ENSURE(draw == kDraw);
342
1.02M
          if (ac_type == ACType::k16) {
343
751k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
751k
                   size * 3 * sizeof(int16_t));
345
3.00M
            for (size_t c = 0; c < 3; c++) {
346
2.25M
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
2.25M
            }
348
751k
          } else {
349
272k
            memset(group_dec_cache->dec_group_qblock, 0,
350
272k
                   size * 3 * sizeof(int32_t));
351
1.09M
            for (size_t c = 0; c < 3; c++) {
352
819k
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
819k
            }
354
272k
          }
355
1.02M
        }
356
1.03M
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
1.03M
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
1.02M
        offset += size;
359
1.02M
        if (draw == kDontDraw) {
360
4.40k
          bx += llf_x;
361
4.40k
          continue;
362
4.40k
        }
363
364
1.02M
        if (JXL_UNLIKELY(jpeg_data)) {
365
236
          if (acs.Strategy() != AcStrategyType::DCT) {
366
1
            return JXL_FAILURE(
367
1
                "Can only decode to JPEG if only DCT-8 is used.");
368
1
          }
369
370
235
          HWY_ALIGN int32_t transposed_dct_y[64];
371
703
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
703
            if (jpeg_is_gray && c != 1) {
374
468
              continue;
375
468
            }
376
235
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
235
            int16_t* JXL_RESTRICT jpeg_pos =
380
235
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
235
            auto* transposed_dct = qblock[c].ptr32;
383
235
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
235
            if (!cs.Is444() ||
386
235
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
1.63k
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
1.45k
                const auto ini = Load(di, transposed_dct + i);
389
1.45k
                const auto ini16 = DemoteTo(di16, ini);
390
1.45k
                StoreU(ini16, di16, jpeg_pos + i);
391
1.45k
              }
392
182
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
477
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
424
                const auto ini = Load(di, transposed_dct + i);
396
424
                Store(ini, di, transposed_dct_y + i);
397
424
                const auto ini16 = DemoteTo(di16, ini);
398
424
                StoreU(ini16, di16, jpeg_pos + i);
399
424
              }
400
53
            } 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
235
            jpeg_pos[0] =
417
235
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
235
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
235
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
1.17k
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
940
              auto in = LoadU(di16_full, jpeg_pos + i);
422
940
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
940
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
940
            }
425
235
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
1
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
1
            }
428
235
          }
429
1.02M
        } else {
430
1.02M
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
1.02M
          dequant_block(
433
1.02M
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
1.02M
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
1.02M
              size, dec_state->shared->quantizer,
436
1.02M
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
1.02M
              dc_stride,
438
1.02M
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
1.02M
              block, group_dec_cache->scratch_space);
440
441
3.07M
          for (size_t c : {1, 0, 2}) {
442
3.07M
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
615k
              continue;
444
615k
            }
445
            // IDCT
446
2.45M
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
2.45M
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
2.45M
                              idct_stride[c], group_dec_cache->scratch_space);
449
2.45M
          }
450
1.02M
        }
451
1.02M
        bx += llf_x;
452
1.02M
      }
453
209k
    }
454
110k
  }
455
17.8k
  return true;
456
18.3k
}
jxl::N_SSE2::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.97k
                       jpeg::JPEGData* jpeg_data, DrawMode draw) {
189
  // TODO(veluca): investigate cache usage in this function.
190
3.97k
  const Rect block_rect =
191
3.97k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx);
192
3.97k
  const AcStrategyImage& ac_strategy = dec_state->shared->ac_strategy;
193
194
3.97k
  const size_t xsize_blocks = block_rect.xsize();
195
3.97k
  const size_t ysize_blocks = block_rect.ysize();
196
197
3.97k
  const size_t dc_stride = dec_state->shared->dc->PixelsPerRow();
198
199
3.97k
  const float inv_global_scale = dec_state->shared->quantizer.InvGlobalScale();
200
201
3.97k
  const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
202
203
3.97k
  const auto kJpegDctMin = Set(di16_full, -4095);
204
3.97k
  const auto kJpegDctMax = Set(di16_full, 4095);
205
206
3.97k
  size_t idct_stride[3];
207
15.8k
  for (size_t c = 0; c < 3; c++) {
208
11.9k
    idct_stride[c] = render_pipeline_input.GetBuffer(c).first->PixelsPerRow();
209
11.9k
  }
210
211
3.97k
  HWY_ALIGN int32_t scaled_qtable[64 * 3];
212
213
3.97k
  ACType ac_type = dec_state->coefficients->Type();
214
3.97k
  auto dequant_block = ac_type == ACType::k16 ? DequantBlock<ACType::k16>
215
3.97k
                                              : DequantBlock<ACType::k32>;
216
  // Whether or not coefficients should be stored for future usage, and/or read
217
  // from past usage.
218
3.97k
  bool accumulate = !dec_state->coefficients->IsEmpty();
219
  // Offset of the current block in the group.
220
3.97k
  size_t offset = 0;
221
222
3.97k
  std::array<int, 3> jpeg_c_map;
223
3.97k
  bool jpeg_is_gray = false;
224
3.97k
  std::array<int, 3> dcoff = {};
225
226
  // TODO(veluca): all of this should be done only once per image.
227
3.97k
  const ColorCorrelation& color_correlation = dec_state->shared->cmap.base();
228
3.97k
  if (jpeg_data) {
229
38
    if (!color_correlation.IsJPEGCompatible()) {
230
6
      return JXL_FAILURE("The CfL map is not JPEG-compatible");
231
6
    }
232
32
    jpeg_is_gray = (jpeg_data->components.size() == 1);
233
32
    JXL_ENSURE(frame_header.color_transform != ColorTransform::kXYB);
234
32
    jpeg_c_map = JpegOrder(frame_header.color_transform, jpeg_is_gray);
235
32
    const std::vector<QuantEncoding>& qe =
236
32
        dec_state->shared->matrices.encodings();
237
32
    if (qe.empty() || qe[0].mode != QuantEncoding::Mode::kQuantModeRAW ||
238
32
        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
32
    JXL_ENSURE(qe[0].qraw.qtable->size() == 3 * 8 * 8);
243
32
    int* qtable = qe[0].qraw.qtable->data();
244
118
    for (size_t c = 0; c < 3; c++) {
245
92
      if (frame_header.color_transform == ColorTransform::kNone) {
246
30
        dcoff[c] = 1024 / qtable[64 * c];
247
30
      }
248
5.66k
      for (size_t i = 0; i < 64; i++) {
249
        // Transpose the matrix, as it will be used on the transposed block.
250
5.57k
        int num = qtable[64 + i];
251
5.57k
        int den = qtable[64 * c + i];
252
5.57k
        if (num <= 0 || den <= 0 || num >= 65536 || den >= 65536) {
253
6
          return JXL_FAILURE("Invalid JPEG quantization table");
254
6
        }
255
5.56k
        scaled_qtable[64 * c + (i % 8) * 8 + (i / 8)] =
256
5.56k
            (1 << kCFLFixedPointPrecision) * num / den;
257
5.56k
      }
258
92
    }
259
32
  }
260
261
3.95k
  size_t hshift[3] = {cs.HShift(0), cs.HShift(1), cs.HShift(2)};
262
3.95k
  size_t vshift[3] = {cs.VShift(0), cs.VShift(1), cs.VShift(2)};
263
3.95k
  Rect r[3];
264
15.8k
  for (size_t i = 0; i < 3; i++) {
265
11.8k
    r[i] =
266
11.8k
        Rect(block_rect.x0() >> hshift[i], block_rect.y0() >> vshift[i],
267
11.8k
             block_rect.xsize() >> hshift[i], block_rect.ysize() >> vshift[i]);
268
11.8k
    if (!r[i].IsInside({0, 0, dec_state->shared->dc->Plane(i).xsize(),
269
11.8k
                        dec_state->shared->dc->Plane(i).ysize()})) {
270
0
      return JXL_FAILURE("Frame dimensions are too big for the image.");
271
0
    }
272
11.8k
  }
273
274
62.9k
  for (size_t by = 0; by < ysize_blocks; ++by) {
275
59.1k
    get_block->StartRow(by);
276
59.1k
    size_t sby[3] = {by >> vshift[0], by >> vshift[1], by >> vshift[2]};
277
278
59.1k
    const int32_t* JXL_RESTRICT row_quant =
279
59.1k
        block_rect.ConstRow(dec_state->shared->raw_quant_field, by);
280
281
59.1k
    const float* JXL_RESTRICT dc_rows[3] = {
282
59.1k
        r[0].ConstPlaneRow(*dec_state->shared->dc, 0, sby[0]),
283
59.1k
        r[1].ConstPlaneRow(*dec_state->shared->dc, 1, sby[1]),
284
59.1k
        r[2].ConstPlaneRow(*dec_state->shared->dc, 2, sby[2]),
285
59.1k
    };
286
287
59.1k
    const size_t ty = (block_rect.y0() + by) / kColorTileDimInBlocks;
288
59.1k
    AcStrategyRow acs_row = ac_strategy.ConstRow(block_rect, by);
289
290
59.1k
    const int8_t* JXL_RESTRICT row_cmap[3] = {
291
59.1k
        dec_state->shared->cmap.ytox_map.ConstRow(ty),
292
59.1k
        nullptr,
293
59.1k
        dec_state->shared->cmap.ytob_map.ConstRow(ty),
294
59.1k
    };
295
296
59.1k
    float* JXL_RESTRICT idct_row[3];
297
59.1k
    int16_t* JXL_RESTRICT jpeg_row[3];
298
236k
    for (size_t c = 0; c < 3; c++) {
299
176k
      const auto& buffer = render_pipeline_input.GetBuffer(c);
300
176k
      idct_row[c] = buffer.second.Row(buffer.first, sby[c] * kBlockDim);
301
176k
      if (jpeg_data) {
302
78
        auto& component = jpeg_data->components[jpeg_c_map[c]];
303
78
        jpeg_row[c] =
304
78
            component.coeffs.data() +
305
78
            (component.width_in_blocks * (r[c].y0() + sby[c]) + r[c].x0()) *
306
78
                kDCTBlockSize;
307
78
      }
308
176k
    }
309
310
59.1k
    size_t bx = 0;
311
141k
    for (size_t tx = 0; tx < DivCeil(xsize_blocks, kColorTileDimInBlocks);
312
82.8k
         tx++) {
313
82.8k
      size_t abs_tx = tx + block_rect.x0() / kColorTileDimInBlocks;
314
82.8k
      auto x_cc_mul = Set(d, color_correlation.YtoXRatio(row_cmap[0][abs_tx]));
315
82.8k
      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
352k
      for (; bx < xsize_blocks && bx < (tx + 1) * kColorTileDimInBlocks;) {
319
269k
        size_t sbx[3] = {bx >> hshift[0], bx >> hshift[1], bx >> hshift[2]};
320
269k
        AcStrategy acs = acs_row[bx];
321
269k
        const size_t llf_x = acs.covered_blocks_x();
322
323
        // Can only happen in the second or lower rows of a varblock.
324
269k
        if (JXL_UNLIKELY(!acs.IsFirstBlock())) {
325
27.9k
          bx += llf_x;
326
27.9k
          continue;
327
27.9k
        }
328
241k
        const size_t log2_covered_blocks = acs.log2_covered_blocks();
329
330
241k
        const size_t covered_blocks = 1 << log2_covered_blocks;
331
241k
        const size_t size = covered_blocks * kDCTBlockSize;
332
333
241k
        ACPtr qblock[3];
334
241k
        if (accumulate) {
335
124
          for (size_t c = 0; c < 3; c++) {
336
93
            qblock[c] = dec_state->coefficients->PlaneRow(c, group_idx, offset);
337
93
          }
338
241k
        } else {
339
          // No point in reading from bitstream without accumulating and not
340
          // drawing.
341
241k
          JXL_ENSURE(draw == kDraw);
342
241k
          if (ac_type == ACType::k16) {
343
116k
            memset(group_dec_cache->dec_group_qblock16, 0,
344
116k
                   size * 3 * sizeof(int16_t));
345
466k
            for (size_t c = 0; c < 3; c++) {
346
350k
              qblock[c].ptr16 = group_dec_cache->dec_group_qblock16 + c * size;
347
350k
            }
348
124k
          } else {
349
124k
            memset(group_dec_cache->dec_group_qblock, 0,
350
124k
                   size * 3 * sizeof(int32_t));
351
499k
            for (size_t c = 0; c < 3; c++) {
352
374k
              qblock[c].ptr32 = group_dec_cache->dec_group_qblock + c * size;
353
374k
            }
354
124k
          }
355
241k
        }
356
241k
        JXL_RETURN_IF_ERROR(get_block->LoadBlock(
357
241k
            bx, by, acs, size, log2_covered_blocks, qblock, ac_type));
358
241k
        offset += size;
359
241k
        if (draw == kDontDraw) {
360
29
          bx += llf_x;
361
29
          continue;
362
29
        }
363
364
241k
        if (JXL_UNLIKELY(jpeg_data)) {
365
25
          if (acs.Strategy() != AcStrategyType::DCT) {
366
1
            return JXL_FAILURE(
367
1
                "Can only decode to JPEG if only DCT-8 is used.");
368
1
          }
369
370
24
          HWY_ALIGN int32_t transposed_dct_y[64];
371
70
          for (size_t c : {1, 0, 2}) {
372
            // Propagate only Y for grayscale.
373
70
            if (jpeg_is_gray && c != 1) {
374
46
              continue;
375
46
            }
376
24
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
377
0
              continue;
378
0
            }
379
24
            int16_t* JXL_RESTRICT jpeg_pos =
380
24
                jpeg_row[c] + sbx[c] * kDCTBlockSize;
381
            // JPEG XL is transposed, JPEG is not.
382
24
            auto* transposed_dct = qblock[c].ptr32;
383
24
            Transpose8x8InPlace(transposed_dct);
384
            // No CfL - no need to store the y block converted to integers.
385
24
            if (!cs.Is444() ||
386
24
                (row_cmap[0][abs_tx] == 0 && row_cmap[2][abs_tx] == 0)) {
387
238
              for (size_t i = 0; i < 64; i += Lanes(d)) {
388
224
                const auto ini = Load(di, transposed_dct + i);
389
224
                const auto ini16 = DemoteTo(di16, ini);
390
224
                StoreU(ini16, di16, jpeg_pos + i);
391
224
              }
392
14
            } else if (c == 1) {
393
              // Y channel: save for restoring X/B, but nothing else to do.
394
170
              for (size_t i = 0; i < 64; i += Lanes(d)) {
395
160
                const auto ini = Load(di, transposed_dct + i);
396
160
                Store(ini, di, transposed_dct_y + i);
397
160
                const auto ini16 = DemoteTo(di16, ini);
398
160
                StoreU(ini16, di16, jpeg_pos + i);
399
160
              }
400
10
            } 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
24
            jpeg_pos[0] =
417
24
                Clamp1<float>(dc_rows[c][sbx[c]] - dcoff[c], -2047, 2047);
418
24
            auto overflow = MaskFromVec(Set(di16_full, 0));
419
24
            auto underflow = MaskFromVec(Set(di16_full, 0));
420
216
            for (int i = 0; i < 64; i += Lanes(di16_full)) {
421
192
              auto in = LoadU(di16_full, jpeg_pos + i);
422
192
              overflow = Or(overflow, Gt(in, kJpegDctMax));
423
192
              underflow = Or(underflow, Lt(in, kJpegDctMin));
424
192
            }
425
24
            if (!AllFalse(di16_full, Or(overflow, underflow))) {
426
1
              return JXL_FAILURE("JPEG DCT coefficients out of range");
427
1
            }
428
24
          }
429
241k
        } else {
430
241k
          HWY_ALIGN float* const block = group_dec_cache->dec_group_block;
431
          // Dequantize and add predictions.
432
241k
          dequant_block(
433
241k
              inv_global_scale, row_quant[bx], dec_state->x_dm_multiplier,
434
241k
              dec_state->b_dm_multiplier, x_cc_mul, b_cc_mul, acs.Strategy(),
435
241k
              size, dec_state->shared->quantizer,
436
241k
              acs.covered_blocks_y() * acs.covered_blocks_x(), sbx, dc_rows,
437
241k
              dc_stride,
438
241k
              dec_state->output_encoding_info.opsin_params.quant_biases, qblock,
439
241k
              block, group_dec_cache->scratch_space);
440
441
722k
          for (size_t c : {1, 0, 2}) {
442
722k
            if ((sbx[c] << hshift[c] != bx) || (sby[c] << vshift[c] != by)) {
443
145k
              continue;
444
145k
            }
445
            // IDCT
446
577k
            float* JXL_RESTRICT idct_pos = idct_row[c] + sbx[c] * kBlockDim;
447
577k
            TransformToPixels(acs.Strategy(), block + c * size, idct_pos,
448
577k
                              idct_stride[c], group_dec_cache->scratch_space);
449
577k
          }
450
241k
        }
451
241k
        bx += llf_x;
452
241k
      }
453
82.8k
    }
454
59.1k
  }
455
3.81k
  return true;
456
3.95k
}
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
3.78M
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
3.78M
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
3.78M
  const size_t size = covered_blocks * kDCTBlockSize;
484
3.78M
  int32_t predicted_nzeros =
485
3.78M
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
3.78M
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
3.78M
  const coeff_order_t* JXL_RESTRICT order =
489
3.78M
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
3.78M
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
3.78M
  const int32_t nzero_ctx =
493
3.78M
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
3.78M
  size_t nzeros =
496
3.78M
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
3.78M
  if (nzeros > size - covered_blocks) {
498
328
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
328
                       " 8x8 blocks",
500
328
                       nzeros, covered_blocks);
501
328
  }
502
7.87M
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
9.18M
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
5.09M
      row_nzeros[bx + x + y * nzeros_stride] =
505
5.09M
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
5.09M
    }
507
4.09M
  }
508
509
3.78M
  const size_t histo_offset =
510
3.78M
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
3.78M
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
22.5M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
18.7M
    const size_t ctx =
515
18.7M
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
18.7M
                                          log2_covered_blocks, prev);
517
18.7M
    const size_t u_coeff =
518
18.7M
        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
18.7M
    const size_t magnitude = u_coeff >> 1;
522
18.7M
    const size_t neg_sign = (~u_coeff) & 1;
523
18.7M
    const ptrdiff_t coeff =
524
18.7M
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
18.7M
    if (ac_type == ACType::k16) {
526
7.56M
      block.ptr16[order[k]] += coeff;
527
11.1M
    } else {
528
11.1M
      block.ptr32[order[k]] += coeff;
529
11.1M
    }
530
18.7M
    prev = static_cast<size_t>(u_coeff != 0);
531
18.7M
    nzeros -= prev;
532
18.7M
  }
533
3.78M
  if (JXL_UNLIKELY(nzeros != 0)) {
534
469
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
469
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
469
                       "), channel %" PRIuS,
537
469
                       nzeros, bx, by, c);
538
469
  }
539
540
3.78M
  return true;
541
3.78M
}
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
370k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
370k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
370k
  const size_t size = covered_blocks * kDCTBlockSize;
484
370k
  int32_t predicted_nzeros =
485
370k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
370k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
370k
  const coeff_order_t* JXL_RESTRICT order =
489
370k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
370k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
370k
  const int32_t nzero_ctx =
493
370k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
370k
  size_t nzeros =
496
370k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
370k
  if (nzeros > size - covered_blocks) {
498
37
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
37
                       " 8x8 blocks",
500
37
                       nzeros, covered_blocks);
501
37
  }
502
755k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
901k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
515k
      row_nzeros[bx + x + y * nzeros_stride] =
505
515k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
515k
    }
507
385k
  }
508
509
370k
  const size_t histo_offset =
510
370k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
370k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
841k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
471k
    const size_t ctx =
515
471k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
471k
                                          log2_covered_blocks, prev);
517
471k
    const size_t u_coeff =
518
471k
        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
471k
    const size_t magnitude = u_coeff >> 1;
522
471k
    const size_t neg_sign = (~u_coeff) & 1;
523
471k
    const ptrdiff_t coeff =
524
471k
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
471k
    if (ac_type == ACType::k16) {
526
471k
      block.ptr16[order[k]] += coeff;
527
471k
    } else {
528
0
      block.ptr32[order[k]] += coeff;
529
0
    }
530
471k
    prev = static_cast<size_t>(u_coeff != 0);
531
471k
    nzeros -= prev;
532
471k
  }
533
370k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
67
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
67
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
67
                       "), channel %" PRIuS,
537
67
                       nzeros, bx, by, c);
538
67
  }
539
540
369k
  return true;
541
370k
}
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
66.1k
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
66.1k
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
66.1k
  const size_t size = covered_blocks * kDCTBlockSize;
484
66.1k
  int32_t predicted_nzeros =
485
66.1k
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
66.1k
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
66.1k
  const coeff_order_t* JXL_RESTRICT order =
489
66.1k
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
66.1k
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
66.1k
  const int32_t nzero_ctx =
493
66.1k
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
66.1k
  size_t nzeros =
496
66.1k
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
66.1k
  if (nzeros > size - covered_blocks) {
498
95
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
95
                       " 8x8 blocks",
500
95
                       nzeros, covered_blocks);
501
95
  }
502
143k
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
178k
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
101k
      row_nzeros[bx + x + y * nzeros_stride] =
505
101k
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
101k
    }
507
77.5k
  }
508
509
66.0k
  const size_t histo_offset =
510
66.0k
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
66.0k
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
525k
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
459k
    const size_t ctx =
515
459k
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
459k
                                          log2_covered_blocks, prev);
517
459k
    const size_t u_coeff =
518
459k
        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
459k
    const size_t magnitude = u_coeff >> 1;
522
459k
    const size_t neg_sign = (~u_coeff) & 1;
523
459k
    const ptrdiff_t coeff =
524
459k
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
459k
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
459k
    } else {
528
459k
      block.ptr32[order[k]] += coeff;
529
459k
    }
530
459k
    prev = static_cast<size_t>(u_coeff != 0);
531
459k
    nzeros -= prev;
532
459k
  }
533
66.0k
  if (JXL_UNLIKELY(nzeros != 0)) {
534
35
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
35
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
35
                       "), channel %" PRIuS,
537
35
                       nzeros, bx, by, c);
538
35
  }
539
540
66.0k
  return true;
541
66.0k
}
dec_group.cc:jxl::Status jxl::(anonymous namespace)::DecodeACVarBlock<(jxl::ACType)0, false>(unsigned long, unsigned long, int*, int const*, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, jxl::AcStrategy, unsigned int const*, jxl::BitReader*, jxl::ANSSymbolReader*, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&, unsigned char const*, int const*, jxl::BlockCtxMap const&, jxl::ACPtr, unsigned long)
Line
Count
Source
480
2.14M
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
2.14M
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
2.14M
  const size_t size = covered_blocks * kDCTBlockSize;
484
2.14M
  int32_t predicted_nzeros =
485
2.14M
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
2.14M
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
2.14M
  const coeff_order_t* JXL_RESTRICT order =
489
2.14M
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
2.14M
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
2.14M
  const int32_t nzero_ctx =
493
2.14M
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
2.14M
  size_t nzeros =
496
2.14M
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
2.14M
  if (nzeros > size - covered_blocks) {
498
55
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
55
                       " 8x8 blocks",
500
55
                       nzeros, covered_blocks);
501
55
  }
502
4.45M
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
5.33M
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
3.01M
      row_nzeros[bx + x + y * nzeros_stride] =
505
3.01M
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
3.01M
    }
507
2.31M
  }
508
509
2.14M
  const size_t histo_offset =
510
2.14M
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
2.14M
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
9.23M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
7.09M
    const size_t ctx =
515
7.09M
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
7.09M
                                          log2_covered_blocks, prev);
517
7.09M
    const size_t u_coeff =
518
7.09M
        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
7.09M
    const size_t magnitude = u_coeff >> 1;
522
7.09M
    const size_t neg_sign = (~u_coeff) & 1;
523
7.09M
    const ptrdiff_t coeff =
524
7.09M
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
7.09M
    if (ac_type == ACType::k16) {
526
7.08M
      block.ptr16[order[k]] += coeff;
527
7.08M
    } else {
528
1.77k
      block.ptr32[order[k]] += coeff;
529
1.77k
    }
530
7.09M
    prev = static_cast<size_t>(u_coeff != 0);
531
7.09M
    nzeros -= prev;
532
7.09M
  }
533
2.14M
  if (JXL_UNLIKELY(nzeros != 0)) {
534
328
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
328
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
328
                       "), channel %" PRIuS,
537
328
                       nzeros, bx, by, c);
538
328
  }
539
540
2.13M
  return true;
541
2.14M
}
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
1.20M
                        size_t shift = 0) {
481
  // Equal to number of LLF coefficients.
482
1.20M
  const size_t covered_blocks = 1 << log2_covered_blocks;
483
1.20M
  const size_t size = covered_blocks * kDCTBlockSize;
484
1.20M
  int32_t predicted_nzeros =
485
1.20M
      PredictFromTopAndLeft(row_nzeros_top, row_nzeros, bx, 32);
486
487
1.20M
  size_t ord = kStrategyOrder[acs.RawStrategy()];
488
1.20M
  const coeff_order_t* JXL_RESTRICT order =
489
1.20M
      &coeff_order[CoeffOrderOffset(ord, c)];
490
491
1.20M
  size_t block_ctx = block_ctx_map.Context(qdc_row[lbx], qf_row[bx], ord, c);
492
1.20M
  const int32_t nzero_ctx =
493
1.20M
      block_ctx_map.NonZeroContext(predicted_nzeros, block_ctx) + ctx_offset;
494
495
1.20M
  size_t nzeros =
496
1.20M
      decoder->ReadHybridUintInlined<uses_lz77>(nzero_ctx, br, context_map);
497
1.20M
  if (nzeros > size - covered_blocks) {
498
141
    return JXL_FAILURE("Invalid AC: nzeros %" PRIuS " too large for %" PRIuS
499
141
                       " 8x8 blocks",
500
141
                       nzeros, covered_blocks);
501
141
  }
502
2.52M
  for (size_t y = 0; y < acs.covered_blocks_y(); y++) {
503
2.77M
    for (size_t x = 0; x < acs.covered_blocks_x(); x++) {
504
1.45M
      row_nzeros[bx + x + y * nzeros_stride] =
505
1.45M
          (nzeros + covered_blocks - 1) >> log2_covered_blocks;
506
1.45M
    }
507
1.31M
  }
508
509
1.20M
  const size_t histo_offset =
510
1.20M
      ctx_offset + block_ctx_map.ZeroDensityContextsOffset(block_ctx);
511
512
1.20M
  size_t prev = (nzeros > size / 16 ? 0 : 1);
513
11.9M
  for (size_t k = covered_blocks; k < size && nzeros != 0; ++k) {
514
10.7M
    const size_t ctx =
515
10.7M
        histo_offset + ZeroDensityContext(nzeros, k, covered_blocks,
516
10.7M
                                          log2_covered_blocks, prev);
517
10.7M
    const size_t u_coeff =
518
10.7M
        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
10.7M
    const size_t magnitude = u_coeff >> 1;
522
10.7M
    const size_t neg_sign = (~u_coeff) & 1;
523
10.7M
    const ptrdiff_t coeff =
524
10.7M
        static_cast<ptrdiff_t>((magnitude ^ (neg_sign - 1)) << shift);
525
10.7M
    if (ac_type == ACType::k16) {
526
0
      block.ptr16[order[k]] += coeff;
527
10.7M
    } else {
528
10.7M
      block.ptr32[order[k]] += coeff;
529
10.7M
    }
530
10.7M
    prev = static_cast<size_t>(u_coeff != 0);
531
10.7M
    nzeros -= prev;
532
10.7M
  }
533
1.20M
  if (JXL_UNLIKELY(nzeros != 0)) {
534
39
    return JXL_FAILURE("Invalid AC: nzeros at end of block is %" PRIuS
535
39
                       ", should be 0. Block (%" PRIuS ", %" PRIuS
536
39
                       "), channel %" PRIuS,
537
39
                       nzeros, bx, by, c);
538
39
  }
539
540
1.20M
  return true;
541
1.20M
}
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
235k
  void StartRow(size_t by) override {
550
235k
    qf_row = rect.ConstRow(*qf, by);
551
942k
    for (size_t c = 0; c < 3; c++) {
552
706k
      size_t sby = by >> vshift[c];
553
706k
      quant_dc_row = quant_dc->ConstRow(rect.y0() + by) + rect.x0();
554
1.41M
      for (size_t i = 0; i < num_passes; i++) {
555
707k
        row_nzeros[i][c] = group_dec_cache->num_nzeroes[i].PlaneRow(c, sby);
556
707k
        row_nzeros_top[i][c] =
557
707k
            sby == 0
558
707k
                ? nullptr
559
707k
                : group_dec_cache->num_nzeroes[i].ConstPlaneRow(c, sby - 1);
560
707k
      }
561
706k
    }
562
235k
  }
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
1.63M
                   ACType ac_type) override {
567
1.63M
    ;
568
4.87M
    for (size_t c : {1, 0, 2}) {
569
4.87M
      size_t sbx = bx >> hshift[c];
570
4.87M
      size_t sby = by >> vshift[c];
571
4.87M
      if (JXL_UNLIKELY((sbx << hshift[c] != bx) || (sby << vshift[c] != by))) {
572
1.11M
        continue;
573
1.11M
      }
574
575
7.54M
      for (size_t pass = 0; JXL_UNLIKELY(pass < num_passes); pass++) {
576
3.78M
        auto decode_ac_varblock =
577
3.78M
            decoders[pass].UsesLZ77()
578
3.78M
                ? (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 1>
579
435k
                                          : DecodeACVarBlock<ACType::k32, 1>)
580
3.78M
                : (ac_type == ACType::k16 ? DecodeACVarBlock<ACType::k16, 0>
581
3.34M
                                          : DecodeACVarBlock<ACType::k32, 0>);
582
3.78M
        JXL_RETURN_IF_ERROR(decode_ac_varblock(
583
3.78M
            ctx_offset[pass], log2_covered_blocks, row_nzeros[pass][c],
584
3.78M
            row_nzeros_top[pass][c], nzeros_stride, c, sbx, sby, bx, acs,
585
3.78M
            &coeff_orders[pass * coeff_order_size], readers[pass],
586
3.78M
            &decoders[pass], context_map[pass], quant_dc_row, qf_row,
587
3.78M
            *block_ctx_map, block[c], shift_for_pass[pass]));
588
3.78M
      }
589
3.76M
    }
590
1.62M
    return true;
591
1.63M
  }
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
26.5k
              PassesDecoderState* dec_state, size_t first_pass) {
598
105k
    for (size_t i = 0; i < 3; i++) {
599
79.4k
      hshift[i] = frame_header.chroma_subsampling.HShift(i);
600
79.4k
      vshift[i] = frame_header.chroma_subsampling.VShift(i);
601
79.4k
    }
602
26.5k
    coeff_order_size = dec_state->shared->coeff_order_size;
603
26.5k
    coeff_orders =
604
26.5k
        dec_state->shared->coeff_orders.data() + first_pass * coeff_order_size;
605
26.5k
    context_map = dec_state->context_map.data() + first_pass;
606
26.5k
    readers = readers_;
607
26.5k
    num_passes = num_passes_;
608
26.5k
    shift_for_pass = frame_header.passes.shift + first_pass;
609
26.5k
    group_dec_cache = group_dec_cache_;
610
26.5k
    rect = rect_;
611
26.5k
    block_ctx_map = &dec_state->shared->block_ctx_map;
612
26.5k
    qf = &dec_state->shared->raw_quant_field;
613
26.5k
    quant_dc = &dec_state->shared->quant_dc;
614
615
53.0k
    for (size_t pass = 0; pass < num_passes; pass++) {
616
      // Select which histogram set to use among those of the current pass.
617
26.5k
      size_t cur_histogram = 0;
618
26.5k
      if (histo_selector_bits != 0) {
619
8.08k
        cur_histogram = readers[pass]->ReadBits(histo_selector_bits);
620
8.08k
      }
621
26.5k
      if (cur_histogram >= dec_state->shared->num_histograms) {
622
14
        return JXL_FAILURE("Invalid histogram selector");
623
14
      }
624
26.5k
      ctx_offset[pass] = cur_histogram * block_ctx_map->NumACContexts();
625
626
26.5k
      JXL_ASSIGN_OR_RETURN(
627
26.5k
          decoders[pass],
628
26.5k
          ANSSymbolReader::Create(&dec_state->code[pass + first_pass],
629
26.5k
                                  readers[pass]));
630
26.5k
    }
631
26.4k
    nzeros_stride = group_dec_cache->num_nzeroes[0].PixelsPerRow();
632
53.0k
    for (size_t i = 0; i < num_passes; i++) {
633
26.5k
      JXL_ENSURE(
634
26.5k
          nzeros_stride ==
635
26.5k
          static_cast<size_t>(group_dec_cache->num_nzeroes[i].PixelsPerRow()));
636
26.5k
    }
637
26.4k
    return true;
638
26.4k
  }
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
786
  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
786
                   ACType ac_type) override {
667
786
    JXL_ENSURE(ac_type == ACType::k32);
668
3.14k
    for (size_t c = 0; c < 3; c++) {
669
      // for each pass
670
4.71k
      for (size_t i = 0; i < quantized_ac->size(); i++) {
671
153k
        for (size_t k = 0; k < size; k++) {
672
          // TODO(veluca): SIMD.
673
150k
          block[c].ptr32[k] +=
674
150k
              rows[i][c][offset + k] * (1 << shift_for_pass[i]);
675
150k
        }
676
2.35k
      }
677
2.35k
    }
678
786
    offset += size;
679
786
    return true;
680
786
  }
681
682
  static StatusOr<GetBlockFromEncoder> Create(
683
      const std::vector<std::unique_ptr<ACImage>>& ac, size_t group_idx,
684
786
      const uint32_t* shift_for_pass) {
685
786
    GetBlockFromEncoder result(ac, group_idx, shift_for_pass);
686
    // TODO(veluca): not supported with chroma subsampling.
687
1.57k
    for (size_t i = 0; i < ac.size(); i++) {
688
786
      JXL_ENSURE(ac[i]->Type() == ACType::k32);
689
3.14k
      for (size_t c = 0; c < 3; c++) {
690
2.35k
        result.rows[i][c] = ac[i]->PlaneRow(c, group_idx, 0).ptr32;
691
2.35k
      }
692
786
    }
693
786
    return result;
694
786
  }
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
786
      : 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
26.4k
                   bool force_draw, bool dc_only, bool* should_run_pipeline) {
719
26.4k
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
720
26.4k
  DrawMode draw =
721
26.4k
      (num_passes + first_pass == frame_header.passes.num_passes) || force_draw
722
26.4k
          ? kDraw
723
26.4k
          : kDontDraw;
724
725
26.4k
  if (should_run_pipeline) {
726
26.4k
    *should_run_pipeline = draw != kDontDraw;
727
26.4k
  }
728
729
26.4k
  if (draw == kDraw && num_passes == 0 && first_pass == 0) {
730
1
    JXL_RETURN_IF_ERROR(group_dec_cache->InitDCBufferOnce(memory_manager));
731
1
    const YCbCrChromaSubsampling& cs = frame_header.chroma_subsampling;
732
3
    for (size_t c : {0, 1, 2}) {
733
3
      size_t hs = cs.HShift(c);
734
3
      size_t vs = cs.VShift(c);
735
      // We reuse filter_input_storage here as it is not currently in use.
736
3
      const Rect src_rect_precs =
737
3
          dec_state->shared->frame_dim.BlockGroupRect(group_idx);
738
3
      const Rect src_rect =
739
3
          Rect(src_rect_precs.x0() >> hs, src_rect_precs.y0() >> vs,
740
3
               src_rect_precs.xsize() >> hs, src_rect_precs.ysize() >> vs);
741
3
      const Rect copy_rect(kRenderPipelineXOffset, 2, src_rect.xsize(),
742
3
                           src_rect.ysize());
743
3
      JXL_RETURN_IF_ERROR(
744
3
          CopyImageToWithPadding(src_rect, dec_state->shared->dc->Plane(c), 2,
745
3
                                 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
21
      for (size_t y = 0; y < src_rect.ysize() + 4; y++) {
749
18
        size_t xend = kRenderPipelineXOffset +
750
18
                      (dec_state->shared->dc->Plane(c).xsize() >> hs) -
751
18
                      src_rect.x0();
752
54
        for (size_t ix = 0; ix < 2; ix++) {
753
36
          if (src_rect.x0() == 0) {
754
36
            group_dec_cache->dc_buffer.Row(y)[kRenderPipelineXOffset - ix - 1] =
755
36
                group_dec_cache->dc_buffer.Row(y)[kRenderPipelineXOffset + ix];
756
36
          }
757
36
          if (src_rect.x0() + src_rect.xsize() + 2 >=
758
36
              (dec_state->shared->dc->xsize() >> hs)) {
759
36
            group_dec_cache->dc_buffer.Row(y)[xend + ix] =
760
36
                group_dec_cache->dc_buffer.Row(y)[xend - ix - 1];
761
36
          }
762
36
        }
763
18
      }
764
3
      const auto& buffer = render_pipeline_input.GetBuffer(c);
765
3
      Rect dst_rect = buffer.second;
766
3
      ImageF* upsampling_dst = buffer.first;
767
3
      JXL_ENSURE(dst_rect.IsInside(*upsampling_dst));
768
769
3
      RenderPipelineStage::RowInfo input_rows(1, std::vector<float*>(5));
770
3
      RenderPipelineStage::RowInfo output_rows(1, std::vector<float*>(8));
771
9
      for (size_t y = src_rect.y0(); y < src_rect.y0() + src_rect.ysize();
772
6
           y++) {
773
36
        for (ptrdiff_t iy = 0; iy < 5; iy++) {
774
30
          input_rows[0][iy] = group_dec_cache->dc_buffer.Row(
775
30
              Mirror(static_cast<ptrdiff_t>(y) + iy - 2,
776
30
                     dec_state->shared->dc->Plane(c).ysize() >> vs) +
777
30
              2 - src_rect.y0());
778
30
        }
779
54
        for (size_t iy = 0; iy < 8; iy++) {
780
48
          output_rows[0][iy] =
781
48
              dst_rect.Row(upsampling_dst, ((y - src_rect.y0()) << 3) + iy) -
782
48
              kRenderPipelineXOffset;
783
48
        }
784
        // Arguments set to 0/nullptr are not used.
785
6
        JXL_RETURN_IF_ERROR(dec_state->upsampler8x->ProcessRow(
786
6
            input_rows, output_rows,
787
6
            /*xextra=*/0, src_rect.xsize(), 0, 0, thread));
788
6
      }
789
3
    }
790
1
    return true;
791
1
  }
792
793
26.4k
  size_t histo_selector_bits = 0;
794
26.4k
  if (dc_only) {
795
0
    JXL_ENSURE(num_passes == 0);
796
26.4k
  } else {
797
26.4k
    JXL_ENSURE(dec_state->shared->num_histograms > 0);
798
26.4k
    histo_selector_bits = CeilLog2Nonzero(dec_state->shared->num_histograms);
799
26.4k
  }
800
801
26.4k
  auto get_block = jxl::make_unique<GetBlockFromBitstream>();
802
26.4k
  JXL_RETURN_IF_ERROR(get_block->Init(
803
26.4k
      frame_header, readers, num_passes, group_idx, histo_selector_bits,
804
26.4k
      dec_state->shared->frame_dim.BlockGroupRect(group_idx), group_dec_cache,
805
26.4k
      dec_state, first_pass));
806
807
26.4k
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
808
26.4k
      frame_header, get_block.get(), group_dec_cache, dec_state, thread,
809
26.4k
      group_idx, render_pipeline_input, jpeg_data, draw));
810
811
51.3k
  for (size_t pass = 0; pass < num_passes; pass++) {
812
25.6k
    if (!get_block->decoders[pass].CheckANSFinalState()) {
813
0
      return JXL_FAILURE("ANS checksum failure.");
814
0
    }
815
25.6k
  }
816
25.6k
  return true;
817
25.6k
}
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
786
                               AuxOut* aux_out) {
828
786
  JxlMemoryManager* memory_manager = dec_state->memory_manager();
829
786
  JXL_ASSIGN_OR_RETURN(
830
786
      GetBlockFromEncoder get_block,
831
786
      GetBlockFromEncoder::Create(ac, group_idx, frame_header.passes.shift));
832
786
  JXL_RETURN_IF_ERROR(group_dec_cache->InitOnce(
833
786
      memory_manager,
834
786
      /*num_passes=*/0,
835
786
      /*used_acs=*/(1u << AcStrategy::kNumValidStrategies) - 1));
836
837
786
  return HWY_DYNAMIC_DISPATCH(DecodeGroupImpl)(
838
786
      frame_header, &get_block, group_dec_cache, dec_state, thread, group_idx,
839
786
      render_pipeline_input, jpeg_data, kDraw);
840
786
}
841
842
}  // namespace jxl
843
#endif  // HWY_ONCE