Coverage Report

Created: 2025-07-23 08:18

/src/libjxl/lib/jxl/splines.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include "lib/jxl/splines.h"
7
8
#include <jxl/memory_manager.h>
9
10
#include <algorithm>
11
#include <cinttypes>  // PRIu64
12
#include <cmath>
13
#include <cstddef>
14
#include <cstdint>
15
#include <cstring>
16
#include <limits>
17
#include <utility>
18
#include <vector>
19
20
#include "lib/jxl/base/bits.h"
21
#include "lib/jxl/base/common.h"
22
#include "lib/jxl/base/compiler_specific.h"  // ssize_t
23
#include "lib/jxl/base/printf_macros.h"
24
#include "lib/jxl/base/rect.h"
25
#include "lib/jxl/base/status.h"
26
#include "lib/jxl/chroma_from_luma.h"
27
#include "lib/jxl/common.h"  // JXL_HIGH_PRECISION
28
#include "lib/jxl/dct_scales.h"
29
#include "lib/jxl/dec_ans.h"
30
#include "lib/jxl/dec_bit_reader.h"
31
#include "lib/jxl/image.h"
32
#include "lib/jxl/pack_signed.h"
33
34
#undef HWY_TARGET_INCLUDE
35
#define HWY_TARGET_INCLUDE "lib/jxl/splines.cc"
36
#include <hwy/foreach_target.h>
37
#include <hwy/highway.h>
38
39
#include "lib/jxl/base/fast_math-inl.h"
40
HWY_BEFORE_NAMESPACE();
41
namespace jxl {
42
namespace HWY_NAMESPACE {
43
namespace {
44
45
// These templates are not found via ADL.
46
using hwy::HWY_NAMESPACE::Mul;
47
using hwy::HWY_NAMESPACE::MulAdd;
48
using hwy::HWY_NAMESPACE::MulSub;
49
using hwy::HWY_NAMESPACE::Sqrt;
50
using hwy::HWY_NAMESPACE::Sub;
51
52
// Given a set of DCT coefficients, this returns the result of performing cosine
53
// interpolation on the original samples.
54
31.4M
float ContinuousIDCT(const Dct32& dct, const float t) {
55
  // We compute here the DCT-3 of the `dct` vector, rescaled by a factor of
56
  // sqrt(32). This is such that an input vector vector {x, 0, ..., 0} produces
57
  // a constant result of x. dct[0] was scaled in Dequantize() to allow uniform
58
  // treatment of all the coefficients.
59
31.4M
  constexpr float kMultipliers[32] = {
60
31.4M
      kPi / 32 * 0,  kPi / 32 * 1,  kPi / 32 * 2,  kPi / 32 * 3,  kPi / 32 * 4,
61
31.4M
      kPi / 32 * 5,  kPi / 32 * 6,  kPi / 32 * 7,  kPi / 32 * 8,  kPi / 32 * 9,
62
31.4M
      kPi / 32 * 10, kPi / 32 * 11, kPi / 32 * 12, kPi / 32 * 13, kPi / 32 * 14,
63
31.4M
      kPi / 32 * 15, kPi / 32 * 16, kPi / 32 * 17, kPi / 32 * 18, kPi / 32 * 19,
64
31.4M
      kPi / 32 * 20, kPi / 32 * 21, kPi / 32 * 22, kPi / 32 * 23, kPi / 32 * 24,
65
31.4M
      kPi / 32 * 25, kPi / 32 * 26, kPi / 32 * 27, kPi / 32 * 28, kPi / 32 * 29,
66
31.4M
      kPi / 32 * 30, kPi / 32 * 31,
67
31.4M
  };
68
31.4M
  HWY_CAPPED(float, 32) df;
69
31.4M
  auto result = Zero(df);
70
31.4M
  const auto tandhalf = Set(df, t + 0.5f);
71
157M
  for (int i = 0; i < 32; i += Lanes(df)) {
72
125M
    auto cos_arg = Mul(LoadU(df, kMultipliers + i), tandhalf);
73
125M
    auto cos = FastCosf(df, cos_arg);
74
125M
    auto local_res = Mul(LoadU(df, dct.data() + i), cos);
75
125M
    result = MulAdd(Set(df, kSqrt2), local_res, result);
76
125M
  }
77
31.4M
  return GetLane(SumOfLanes(df, result));
78
31.4M
}
Unexecuted instantiation: splines.cc:jxl::N_AVX3_SPR::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
Unexecuted instantiation: splines.cc:jxl::N_AVX3_ZEN4::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
Unexecuted instantiation: splines.cc:jxl::N_AVX3::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
splines.cc:jxl::N_AVX2::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
Line
Count
Source
54
31.4M
float ContinuousIDCT(const Dct32& dct, const float t) {
55
  // We compute here the DCT-3 of the `dct` vector, rescaled by a factor of
56
  // sqrt(32). This is such that an input vector vector {x, 0, ..., 0} produces
57
  // a constant result of x. dct[0] was scaled in Dequantize() to allow uniform
58
  // treatment of all the coefficients.
59
31.4M
  constexpr float kMultipliers[32] = {
60
31.4M
      kPi / 32 * 0,  kPi / 32 * 1,  kPi / 32 * 2,  kPi / 32 * 3,  kPi / 32 * 4,
61
31.4M
      kPi / 32 * 5,  kPi / 32 * 6,  kPi / 32 * 7,  kPi / 32 * 8,  kPi / 32 * 9,
62
31.4M
      kPi / 32 * 10, kPi / 32 * 11, kPi / 32 * 12, kPi / 32 * 13, kPi / 32 * 14,
63
31.4M
      kPi / 32 * 15, kPi / 32 * 16, kPi / 32 * 17, kPi / 32 * 18, kPi / 32 * 19,
64
31.4M
      kPi / 32 * 20, kPi / 32 * 21, kPi / 32 * 22, kPi / 32 * 23, kPi / 32 * 24,
65
31.4M
      kPi / 32 * 25, kPi / 32 * 26, kPi / 32 * 27, kPi / 32 * 28, kPi / 32 * 29,
66
31.4M
      kPi / 32 * 30, kPi / 32 * 31,
67
31.4M
  };
68
31.4M
  HWY_CAPPED(float, 32) df;
69
31.4M
  auto result = Zero(df);
70
31.4M
  const auto tandhalf = Set(df, t + 0.5f);
71
157M
  for (int i = 0; i < 32; i += Lanes(df)) {
72
125M
    auto cos_arg = Mul(LoadU(df, kMultipliers + i), tandhalf);
73
125M
    auto cos = FastCosf(df, cos_arg);
74
125M
    auto local_res = Mul(LoadU(df, dct.data() + i), cos);
75
125M
    result = MulAdd(Set(df, kSqrt2), local_res, result);
76
125M
  }
77
31.4M
  return GetLane(SumOfLanes(df, result));
78
31.4M
}
Unexecuted instantiation: splines.cc:jxl::N_SSE4::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
Unexecuted instantiation: splines.cc:jxl::N_SSE2::(anonymous namespace)::ContinuousIDCT(std::__1::array<float, 32ul> const&, float)
79
80
template <typename DF>
81
void DrawSegment(DF df, const SplineSegment& segment, const bool add,
82
                 const size_t y, const size_t x, const size_t x0,
83
2.20M
                 float* JXL_RESTRICT rows[3]) {
84
2.20M
  Rebind<int32_t, DF> di;
85
2.20M
  const auto inv_sigma = Set(df, segment.inv_sigma);
86
2.20M
  const auto half = Set(df, 0.5f);
87
2.20M
  const auto one_over_2s2 = Set(df, 0.353553391f);
88
2.20M
  const auto sigma_over_4_times_intensity =
89
2.20M
      Set(df, segment.sigma_over_4_times_intensity);
90
2.20M
  const auto dx =
91
2.20M
      Sub(ConvertTo(df, Iota(di, x + x0)), Set(df, segment.center_x));
92
2.20M
  const auto dy = Set(df, y - segment.center_y);
93
2.20M
  const auto sqd = MulAdd(dx, dx, Mul(dy, dy));
94
2.20M
  const auto distance = Sqrt(sqd);
95
2.20M
  const auto one_dimensional_factor =
96
2.20M
      Sub(FastErff(df, Mul(MulAdd(distance, half, one_over_2s2), inv_sigma)),
97
2.20M
          FastErff(df, Mul(MulSub(distance, half, one_over_2s2), inv_sigma)));
98
2.20M
  auto local_intensity =
99
2.20M
      Mul(sigma_over_4_times_intensity,
100
2.20M
          Mul(one_dimensional_factor, one_dimensional_factor));
101
8.83M
  for (size_t c = 0; c < 3; ++c) {
102
6.62M
    const auto cm = Set(df, add ? segment.color[c] : -segment.color[c]);
103
6.62M
    const auto in = LoadU(df, rows[c] + x);
104
6.62M
    StoreU(MulAdd(cm, local_intensity, in), df, rows[c] + x);
105
6.62M
  }
106
2.20M
}
Unexecuted instantiation: splines.cc:void jxl::N_AVX3_SPR::(anonymous namespace)::DrawSegment<hwy::N_AVX3_SPR::Simd<float, 16ul, 0> >(hwy::N_AVX3_SPR::Simd<float, 16ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_AVX3_SPR::(anonymous namespace)::DrawSegment<hwy::N_AVX3_SPR::Simd<float, 1ul, 0> >(hwy::N_AVX3_SPR::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_AVX3_ZEN4::(anonymous namespace)::DrawSegment<hwy::N_AVX3_ZEN4::Simd<float, 16ul, 0> >(hwy::N_AVX3_ZEN4::Simd<float, 16ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_AVX3_ZEN4::(anonymous namespace)::DrawSegment<hwy::N_AVX3_ZEN4::Simd<float, 1ul, 0> >(hwy::N_AVX3_ZEN4::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_AVX3::(anonymous namespace)::DrawSegment<hwy::N_AVX3::Simd<float, 16ul, 0> >(hwy::N_AVX3::Simd<float, 16ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_AVX3::(anonymous namespace)::DrawSegment<hwy::N_AVX3::Simd<float, 1ul, 0> >(hwy::N_AVX3::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
splines.cc:void jxl::N_AVX2::(anonymous namespace)::DrawSegment<hwy::N_AVX2::Simd<float, 8ul, 0> >(hwy::N_AVX2::Simd<float, 8ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Line
Count
Source
83
263k
                 float* JXL_RESTRICT rows[3]) {
84
263k
  Rebind<int32_t, DF> di;
85
263k
  const auto inv_sigma = Set(df, segment.inv_sigma);
86
263k
  const auto half = Set(df, 0.5f);
87
263k
  const auto one_over_2s2 = Set(df, 0.353553391f);
88
263k
  const auto sigma_over_4_times_intensity =
89
263k
      Set(df, segment.sigma_over_4_times_intensity);
90
263k
  const auto dx =
91
263k
      Sub(ConvertTo(df, Iota(di, x + x0)), Set(df, segment.center_x));
92
263k
  const auto dy = Set(df, y - segment.center_y);
93
263k
  const auto sqd = MulAdd(dx, dx, Mul(dy, dy));
94
263k
  const auto distance = Sqrt(sqd);
95
263k
  const auto one_dimensional_factor =
96
263k
      Sub(FastErff(df, Mul(MulAdd(distance, half, one_over_2s2), inv_sigma)),
97
263k
          FastErff(df, Mul(MulSub(distance, half, one_over_2s2), inv_sigma)));
98
263k
  auto local_intensity =
99
263k
      Mul(sigma_over_4_times_intensity,
100
263k
          Mul(one_dimensional_factor, one_dimensional_factor));
101
1.05M
  for (size_t c = 0; c < 3; ++c) {
102
791k
    const auto cm = Set(df, add ? segment.color[c] : -segment.color[c]);
103
791k
    const auto in = LoadU(df, rows[c] + x);
104
791k
    StoreU(MulAdd(cm, local_intensity, in), df, rows[c] + x);
105
791k
  }
106
263k
}
splines.cc:void jxl::N_AVX2::(anonymous namespace)::DrawSegment<hwy::N_AVX2::Simd<float, 1ul, 0> >(hwy::N_AVX2::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Line
Count
Source
83
1.94M
                 float* JXL_RESTRICT rows[3]) {
84
1.94M
  Rebind<int32_t, DF> di;
85
1.94M
  const auto inv_sigma = Set(df, segment.inv_sigma);
86
1.94M
  const auto half = Set(df, 0.5f);
87
1.94M
  const auto one_over_2s2 = Set(df, 0.353553391f);
88
1.94M
  const auto sigma_over_4_times_intensity =
89
1.94M
      Set(df, segment.sigma_over_4_times_intensity);
90
1.94M
  const auto dx =
91
1.94M
      Sub(ConvertTo(df, Iota(di, x + x0)), Set(df, segment.center_x));
92
1.94M
  const auto dy = Set(df, y - segment.center_y);
93
1.94M
  const auto sqd = MulAdd(dx, dx, Mul(dy, dy));
94
1.94M
  const auto distance = Sqrt(sqd);
95
1.94M
  const auto one_dimensional_factor =
96
1.94M
      Sub(FastErff(df, Mul(MulAdd(distance, half, one_over_2s2), inv_sigma)),
97
1.94M
          FastErff(df, Mul(MulSub(distance, half, one_over_2s2), inv_sigma)));
98
1.94M
  auto local_intensity =
99
1.94M
      Mul(sigma_over_4_times_intensity,
100
1.94M
          Mul(one_dimensional_factor, one_dimensional_factor));
101
7.77M
  for (size_t c = 0; c < 3; ++c) {
102
5.83M
    const auto cm = Set(df, add ? segment.color[c] : -segment.color[c]);
103
5.83M
    const auto in = LoadU(df, rows[c] + x);
104
5.83M
    StoreU(MulAdd(cm, local_intensity, in), df, rows[c] + x);
105
5.83M
  }
106
1.94M
}
Unexecuted instantiation: splines.cc:void jxl::N_SSE4::(anonymous namespace)::DrawSegment<hwy::N_SSE4::Simd<float, 4ul, 0> >(hwy::N_SSE4::Simd<float, 4ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_SSE4::(anonymous namespace)::DrawSegment<hwy::N_SSE4::Simd<float, 1ul, 0> >(hwy::N_SSE4::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_SSE2::(anonymous namespace)::DrawSegment<hwy::N_SSE2::Simd<float, 4ul, 0> >(hwy::N_SSE2::Simd<float, 4ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:void jxl::N_SSE2::(anonymous namespace)::DrawSegment<hwy::N_SSE2::Simd<float, 1ul, 0> >(hwy::N_SSE2::Simd<float, 1ul, 0>, jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
107
108
void DrawSegment(const SplineSegment& segment, const bool add, const size_t y,
109
                 const size_t x0, const size_t x1,
110
5.50M
                 float* JXL_RESTRICT rows[3]) {
111
5.50M
  ssize_t start = std::llround(segment.center_x - segment.maximum_distance);
112
5.50M
  ssize_t end = std::llround(segment.center_x + segment.maximum_distance);
113
5.50M
  if (end < static_cast<ssize_t>(x0) || start >= static_cast<ssize_t>(x1)) {
114
4.75M
    return;  // span does not intersect scan
115
4.75M
  }
116
749k
  size_t span_x0 = std::max<ssize_t>(x0, start) - x0;
117
749k
  size_t span_x1 = std::min<ssize_t>(x1, end + 1) - x0;  // exclusive
118
749k
  HWY_FULL(float) df;
119
749k
  size_t x = span_x0;
120
1.01M
  for (; x + Lanes(df) <= span_x1; x += Lanes(df)) {
121
263k
    DrawSegment(df, segment, add, y, x, x0, rows);
122
263k
  }
123
2.69M
  for (; x < span_x1; ++x) {
124
1.94M
    DrawSegment(HWY_CAPPED(float, 1)(), segment, add, y, x, x0, rows);
125
1.94M
  }
126
749k
}
Unexecuted instantiation: splines.cc:jxl::N_AVX3_SPR::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:jxl::N_AVX3_ZEN4::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:jxl::N_AVX3::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
splines.cc:jxl::N_AVX2::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Line
Count
Source
110
5.50M
                 float* JXL_RESTRICT rows[3]) {
111
5.50M
  ssize_t start = std::llround(segment.center_x - segment.maximum_distance);
112
5.50M
  ssize_t end = std::llround(segment.center_x + segment.maximum_distance);
113
5.50M
  if (end < static_cast<ssize_t>(x0) || start >= static_cast<ssize_t>(x1)) {
114
4.75M
    return;  // span does not intersect scan
115
4.75M
  }
116
749k
  size_t span_x0 = std::max<ssize_t>(x0, start) - x0;
117
749k
  size_t span_x1 = std::min<ssize_t>(x1, end + 1) - x0;  // exclusive
118
749k
  HWY_FULL(float) df;
119
749k
  size_t x = span_x0;
120
1.01M
  for (; x + Lanes(df) <= span_x1; x += Lanes(df)) {
121
263k
    DrawSegment(df, segment, add, y, x, x0, rows);
122
263k
  }
123
2.69M
  for (; x < span_x1; ++x) {
124
1.94M
    DrawSegment(HWY_CAPPED(float, 1)(), segment, add, y, x, x0, rows);
125
1.94M
  }
126
749k
}
Unexecuted instantiation: splines.cc:jxl::N_SSE4::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
Unexecuted instantiation: splines.cc:jxl::N_SSE2::(anonymous namespace)::DrawSegment(jxl::SplineSegment const&, bool, unsigned long, unsigned long, unsigned long, float* restrict*)
127
128
void ComputeSegments(const Spline::Point& center, const float intensity,
129
                     const float color[3], const float sigma,
130
                     std::vector<SplineSegment>& segments,
131
7.87M
                     std::vector<std::pair<size_t, size_t>>& segments_by_y) {
132
  // Sanity check sigma, inverse sigma and intensity
133
7.87M
  if (!(std::isfinite(sigma) && sigma != 0.0f && std::isfinite(1.0f / sigma) &&
134
7.87M
        std::isfinite(intensity))) {
135
47.5k
    return;
136
47.5k
  }
137
7.82M
#if JXL_HIGH_PRECISION
138
7.82M
  constexpr float kDistanceExp = 5;
139
#else
140
  // About 30% faster.
141
  constexpr float kDistanceExp = 3;
142
#endif
143
  // We cap from below colors to at least 0.01.
144
7.82M
  float max_color = 0.01f;
145
31.2M
  for (size_t c = 0; c < 3; c++) {
146
23.4M
    max_color = std::max(max_color, std::abs(color[c] * intensity));
147
23.4M
  }
148
  // Distance beyond which max_color*intensity*exp(-d^2 / (2 * sigma^2)) drops
149
  // below 10^-kDistanceExp.
150
7.82M
  const float maximum_distance =
151
7.82M
      std::sqrt(-2 * sigma * sigma *
152
7.82M
                (std::log(0.1) * kDistanceExp - std::log(max_color)));
153
7.82M
  SplineSegment segment;
154
7.82M
  segment.center_y = center.y;
155
7.82M
  segment.center_x = center.x;
156
7.82M
  memcpy(segment.color, color, sizeof(segment.color));
157
7.82M
  segment.inv_sigma = 1.0f / sigma;
158
7.82M
  segment.sigma_over_4_times_intensity = .25f * sigma * intensity;
159
7.82M
  segment.maximum_distance = maximum_distance;
160
7.82M
  ssize_t y0 = std::llround(center.y - maximum_distance);
161
7.82M
  ssize_t y1 =
162
7.82M
      std::llround(center.y + maximum_distance) + 1;  // one-past-the-end
163
32.9M
  for (ssize_t y = std::max<ssize_t>(y0, 0); y < y1; y++) {
164
25.1M
    segments_by_y.emplace_back(y, segments.size());
165
25.1M
  }
166
7.82M
  segments.push_back(segment);
167
7.82M
}
Unexecuted instantiation: splines.cc:jxl::N_AVX3_SPR::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_AVX3_ZEN4::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_AVX3::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
splines.cc:jxl::N_AVX2::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Line
Count
Source
131
7.87M
                     std::vector<std::pair<size_t, size_t>>& segments_by_y) {
132
  // Sanity check sigma, inverse sigma and intensity
133
7.87M
  if (!(std::isfinite(sigma) && sigma != 0.0f && std::isfinite(1.0f / sigma) &&
134
7.87M
        std::isfinite(intensity))) {
135
47.5k
    return;
136
47.5k
  }
137
7.82M
#if JXL_HIGH_PRECISION
138
7.82M
  constexpr float kDistanceExp = 5;
139
#else
140
  // About 30% faster.
141
  constexpr float kDistanceExp = 3;
142
#endif
143
  // We cap from below colors to at least 0.01.
144
7.82M
  float max_color = 0.01f;
145
31.2M
  for (size_t c = 0; c < 3; c++) {
146
23.4M
    max_color = std::max(max_color, std::abs(color[c] * intensity));
147
23.4M
  }
148
  // Distance beyond which max_color*intensity*exp(-d^2 / (2 * sigma^2)) drops
149
  // below 10^-kDistanceExp.
150
7.82M
  const float maximum_distance =
151
7.82M
      std::sqrt(-2 * sigma * sigma *
152
7.82M
                (std::log(0.1) * kDistanceExp - std::log(max_color)));
153
7.82M
  SplineSegment segment;
154
7.82M
  segment.center_y = center.y;
155
7.82M
  segment.center_x = center.x;
156
7.82M
  memcpy(segment.color, color, sizeof(segment.color));
157
7.82M
  segment.inv_sigma = 1.0f / sigma;
158
7.82M
  segment.sigma_over_4_times_intensity = .25f * sigma * intensity;
159
7.82M
  segment.maximum_distance = maximum_distance;
160
7.82M
  ssize_t y0 = std::llround(center.y - maximum_distance);
161
7.82M
  ssize_t y1 =
162
7.82M
      std::llround(center.y + maximum_distance) + 1;  // one-past-the-end
163
32.9M
  for (ssize_t y = std::max<ssize_t>(y0, 0); y < y1; y++) {
164
25.1M
    segments_by_y.emplace_back(y, segments.size());
165
25.1M
  }
166
7.82M
  segments.push_back(segment);
167
7.82M
}
Unexecuted instantiation: splines.cc:jxl::N_SSE4::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_SSE2::(anonymous namespace)::ComputeSegments(jxl::Spline::Point const&, float, float const*, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
168
169
void DrawSegments(float* JXL_RESTRICT row_x, float* JXL_RESTRICT row_y,
170
                  float* JXL_RESTRICT row_b, size_t y, size_t x0, size_t x1,
171
                  const bool add, const SplineSegment* segments,
172
                  const size_t* segment_indices,
173
532k
                  const size_t* segment_y_start) {
174
532k
  float* JXL_RESTRICT rows[3] = {row_x, row_y, row_b};
175
6.03M
  for (size_t i = segment_y_start[y]; i < segment_y_start[y + 1]; i++) {
176
5.50M
    DrawSegment(segments[segment_indices[i]], add, y, x0, x1, rows);
177
5.50M
  }
178
532k
}
Unexecuted instantiation: splines.cc:jxl::N_AVX3_SPR::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
Unexecuted instantiation: splines.cc:jxl::N_AVX3_ZEN4::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
Unexecuted instantiation: splines.cc:jxl::N_AVX3::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
splines.cc:jxl::N_AVX2::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
Line
Count
Source
173
532k
                  const size_t* segment_y_start) {
174
532k
  float* JXL_RESTRICT rows[3] = {row_x, row_y, row_b};
175
6.03M
  for (size_t i = segment_y_start[y]; i < segment_y_start[y + 1]; i++) {
176
5.50M
    DrawSegment(segments[segment_indices[i]], add, y, x0, x1, rows);
177
5.50M
  }
178
532k
}
Unexecuted instantiation: splines.cc:jxl::N_SSE4::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
Unexecuted instantiation: splines.cc:jxl::N_SSE2::(anonymous namespace)::DrawSegments(float*, float*, float*, unsigned long, unsigned long, unsigned long, bool, jxl::SplineSegment const*, unsigned long const*, unsigned long const*)
179
180
void SegmentsFromPoints(
181
    const Spline& spline,
182
    const std::vector<std::pair<Spline::Point, float>>& points_to_draw,
183
    const float arc_length, std::vector<SplineSegment>& segments,
184
21.0k
    std::vector<std::pair<size_t, size_t>>& segments_by_y) {
185
21.0k
  const float inv_arc_length = 1.0f / arc_length;
186
21.0k
  int k = 0;
187
7.87M
  for (const auto& point_to_draw : points_to_draw) {
188
7.87M
    const Spline::Point& point = point_to_draw.first;
189
7.87M
    const float multiplier = point_to_draw.second;
190
7.87M
    const float progress_along_arc =
191
7.87M
        std::min(1.f, (k * kDesiredRenderingDistance) * inv_arc_length);
192
7.87M
    ++k;
193
7.87M
    float color[3];
194
31.4M
    for (size_t c = 0; c < 3; ++c) {
195
23.6M
      color[c] =
196
23.6M
          ContinuousIDCT(spline.color_dct[c], (32 - 1) * progress_along_arc);
197
23.6M
    }
198
7.87M
    const float sigma =
199
7.87M
        ContinuousIDCT(spline.sigma_dct, (32 - 1) * progress_along_arc);
200
7.87M
    ComputeSegments(point, multiplier, color, sigma, segments, segments_by_y);
201
7.87M
  }
202
21.0k
}
Unexecuted instantiation: splines.cc:jxl::N_AVX3_SPR::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_AVX3_ZEN4::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_AVX3::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
splines.cc:jxl::N_AVX2::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Line
Count
Source
184
21.0k
    std::vector<std::pair<size_t, size_t>>& segments_by_y) {
185
21.0k
  const float inv_arc_length = 1.0f / arc_length;
186
21.0k
  int k = 0;
187
7.87M
  for (const auto& point_to_draw : points_to_draw) {
188
7.87M
    const Spline::Point& point = point_to_draw.first;
189
7.87M
    const float multiplier = point_to_draw.second;
190
7.87M
    const float progress_along_arc =
191
7.87M
        std::min(1.f, (k * kDesiredRenderingDistance) * inv_arc_length);
192
7.87M
    ++k;
193
7.87M
    float color[3];
194
31.4M
    for (size_t c = 0; c < 3; ++c) {
195
23.6M
      color[c] =
196
23.6M
          ContinuousIDCT(spline.color_dct[c], (32 - 1) * progress_along_arc);
197
23.6M
    }
198
7.87M
    const float sigma =
199
7.87M
        ContinuousIDCT(spline.sigma_dct, (32 - 1) * progress_along_arc);
200
7.87M
    ComputeSegments(point, multiplier, color, sigma, segments, segments_by_y);
201
7.87M
  }
202
21.0k
}
Unexecuted instantiation: splines.cc:jxl::N_SSE4::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
Unexecuted instantiation: splines.cc:jxl::N_SSE2::(anonymous namespace)::SegmentsFromPoints(jxl::Spline const&, std::__1::vector<std::__1::pair<jxl::Spline::Point, float>, std::__1::allocator<std::__1::pair<jxl::Spline::Point, float> > > const&, float, std::__1::vector<jxl::SplineSegment, std::__1::allocator<jxl::SplineSegment> >&, std::__1::vector<std::__1::pair<unsigned long, unsigned long>, std::__1::allocator<std::__1::pair<unsigned long, unsigned long> > >&)
203
}  // namespace
204
// NOLINTNEXTLINE(google-readability-namespace-comments)
205
}  // namespace HWY_NAMESPACE
206
}  // namespace jxl
207
HWY_AFTER_NAMESPACE();
208
209
#if HWY_ONCE
210
namespace jxl {
211
HWY_EXPORT(SegmentsFromPoints);
212
HWY_EXPORT(DrawSegments);
213
214
namespace {
215
216
// It is not in spec, but reasonable limit to avoid overflows.
217
template <typename T>
218
1.53M
Status ValidateSplinePointPos(const T& x, const T& y) {
219
1.53M
  constexpr T kSplinePosLimit = 1u << 23;
220
1.53M
  if ((x >= kSplinePosLimit) || (x <= -kSplinePosLimit) ||
221
1.53M
      (y >= kSplinePosLimit) || (y <= -kSplinePosLimit)) {
222
48
    return JXL_FAILURE("Spline coordinates out of bounds");
223
48
  }
224
1.53M
  return true;
225
1.53M
}
splines.cc:jxl::Status jxl::(anonymous namespace)::ValidateSplinePointPos<long>(long const&, long const&)
Line
Count
Source
218
1.03M
Status ValidateSplinePointPos(const T& x, const T& y) {
219
1.03M
  constexpr T kSplinePosLimit = 1u << 23;
220
1.03M
  if ((x >= kSplinePosLimit) || (x <= -kSplinePosLimit) ||
221
1.03M
      (y >= kSplinePosLimit) || (y <= -kSplinePosLimit)) {
222
24
    return JXL_FAILURE("Spline coordinates out of bounds");
223
24
  }
224
1.03M
  return true;
225
1.03M
}
splines.cc:jxl::Status jxl::(anonymous namespace)::ValidateSplinePointPos<float>(float const&, float const&)
Line
Count
Source
218
37.0k
Status ValidateSplinePointPos(const T& x, const T& y) {
219
37.0k
  constexpr T kSplinePosLimit = 1u << 23;
220
37.0k
  if ((x >= kSplinePosLimit) || (x <= -kSplinePosLimit) ||
221
37.0k
      (y >= kSplinePosLimit) || (y <= -kSplinePosLimit)) {
222
0
    return JXL_FAILURE("Spline coordinates out of bounds");
223
0
  }
224
37.0k
  return true;
225
37.0k
}
splines.cc:jxl::Status jxl::(anonymous namespace)::ValidateSplinePointPos<int>(int const&, int const&)
Line
Count
Source
218
468k
Status ValidateSplinePointPos(const T& x, const T& y) {
219
468k
  constexpr T kSplinePosLimit = 1u << 23;
220
468k
  if ((x >= kSplinePosLimit) || (x <= -kSplinePosLimit) ||
221
468k
      (y >= kSplinePosLimit) || (y <= -kSplinePosLimit)) {
222
24
    return JXL_FAILURE("Spline coordinates out of bounds");
223
24
  }
224
468k
  return true;
225
468k
}
226
227
// Maximum number of spline control points per frame is
228
//   std::min(kMaxNumControlPoints, xsize * ysize / 2)
229
constexpr size_t kMaxNumControlPoints = 1u << 20u;
230
constexpr size_t kMaxNumControlPointsPerPixelRatio = 2;
231
232
0
float AdjustedQuant(const int32_t adjustment) {
233
0
  return (adjustment >= 0) ? (1.f + .125f * adjustment)
234
0
                           : 1.f / (1.f - .125f * adjustment);
235
0
}
236
237
37.0k
float InvAdjustedQuant(const int32_t adjustment) {
238
37.0k
  return (adjustment >= 0) ? 1.f / (1.f + .125f * adjustment)
239
37.0k
                           : (1.f - .125f * adjustment);
240
37.0k
}
241
242
// X, Y, B, sigma.
243
constexpr float kChannelWeight[] = {0.0042f, 0.075f, 0.07f, .3333f};
244
245
Status DecodeAllStartingPoints(std::vector<Spline::Point>* const points,
246
                               BitReader* const br, ANSSymbolReader* reader,
247
                               const std::vector<uint8_t>& context_map,
248
22.6k
                               const size_t num_splines) {
249
22.6k
  points->clear();
250
22.6k
  points->reserve(num_splines);
251
22.6k
  int64_t last_x = 0;
252
22.6k
  int64_t last_y = 0;
253
1.05M
  for (size_t i = 0; i < num_splines; i++) {
254
1.03M
    size_t dx =
255
1.03M
        reader->ReadHybridUint(kStartingPositionContext, br, context_map);
256
1.03M
    size_t dy =
257
1.03M
        reader->ReadHybridUint(kStartingPositionContext, br, context_map);
258
1.03M
    int64_t x;
259
1.03M
    int64_t y;
260
1.03M
    if (i != 0) {
261
1.01M
      x = UnpackSigned(dx) + last_x;
262
1.01M
      y = UnpackSigned(dy) + last_y;
263
1.01M
    } else {
264
22.6k
      x = dx;
265
22.6k
      y = dy;
266
22.6k
    }
267
1.03M
    JXL_RETURN_IF_ERROR(ValidateSplinePointPos(x, y));
268
1.03M
    points->emplace_back(static_cast<float>(x), static_cast<float>(y));
269
1.03M
    last_x = x;
270
1.03M
    last_y = y;
271
1.03M
  }
272
22.6k
  return true;
273
22.6k
}
274
275
struct Vector {
276
  float x, y;
277
0
  Vector operator-() const { return {-x, -y}; }
278
0
  Vector operator+(const Vector& other) const {
279
0
    return {x + other.x, y + other.y};
280
0
  }
281
11.5M
  float SquaredNorm() const { return x * x + y * y; }
282
};
283
28.5M
Vector operator*(const float k, const Vector& vec) {
284
28.5M
  return {k * vec.x, k * vec.y};
285
28.5M
}
286
287
28.6M
Spline::Point operator+(const Spline::Point& p, const Vector& vec) {
288
28.6M
  return {p.x + vec.x, p.y + vec.y};
289
28.6M
}
290
40.1M
Vector operator-(const Spline::Point& a, const Spline::Point& b) {
291
40.1M
  return {a.x - b.x, a.y - b.y};
292
40.1M
}
293
294
// TODO(eustas): avoid making a copy of "points".
295
void DrawCentripetalCatmullRomSpline(std::vector<Spline::Point> points,
296
36.5k
                                     std::vector<Spline::Point>& result) {
297
36.5k
  if (points.empty()) return;
298
36.5k
  if (points.size() == 1) {
299
15.4k
    result.push_back(points[0]);
300
15.4k
    return;
301
15.4k
  }
302
  // Number of points to compute between each control point.
303
21.0k
  static constexpr int kNumPoints = 16;
304
21.0k
  result.reserve((points.size() - 1) * kNumPoints + 1);
305
21.0k
  points.insert(points.begin(), points[0] + (points[0] - points[1]));
306
21.0k
  points.push_back(points[points.size() - 1] +
307
21.0k
                   (points[points.size() - 1] - points[points.size() - 2]));
308
  // points has at least 4 elements at this point.
309
251k
  for (size_t start = 0; start < points.size() - 3; ++start) {
310
    // 4 of them are used, and we draw from p[1] to p[2].
311
230k
    const Spline::Point* const p = &points[start];
312
230k
    result.push_back(p[1]);
313
230k
    float d[3];
314
230k
    float t[4];
315
230k
    t[0] = 0;
316
922k
    for (int k = 0; k < 3; ++k) {
317
      // TODO(eustas): for each segment delta is calculated 3 times...
318
      // TODO(eustas): restrict d[k] with reasonable limit and spec it.
319
692k
      d[k] = std::sqrt(hypotf(p[k + 1].x - p[k].x, p[k + 1].y - p[k].y));
320
692k
      t[k + 1] = t[k] + d[k];
321
692k
    }
322
3.69M
    for (int i = 1; i < kNumPoints; ++i) {
323
3.46M
      const float tt = d[0] + (static_cast<float>(i) / kNumPoints) * d[1];
324
3.46M
      Spline::Point a[3];
325
13.8M
      for (int k = 0; k < 3; ++k) {
326
        // TODO(eustas): reciprocal multiplication would be faster.
327
10.3M
        a[k] = p[k] + ((tt - t[k]) / d[k]) * (p[k + 1] - p[k]);
328
10.3M
      }
329
3.46M
      Spline::Point b[2];
330
10.3M
      for (int k = 0; k < 2; ++k) {
331
6.92M
        b[k] = a[k] + ((tt - t[k]) / (d[k] + d[k + 1])) * (a[k + 1] - a[k]);
332
6.92M
      }
333
3.46M
      result.push_back(b[0] + ((tt - t[1]) / d[1]) * (b[1] - b[0]));
334
3.46M
    }
335
230k
  }
336
21.0k
  result.push_back(points[points.size() - 2]);
337
21.0k
}
338
339
// Move along the line segments defined by `points`, `kDesiredRenderingDistance`
340
// pixels at a time, and call `functor` with each point and the actual distance
341
// to the previous point (which will always be kDesiredRenderingDistance except
342
// possibly for the very last point).
343
// TODO(eustas): this method always adds the last point, but never the first
344
//               (unless those are one); I believe both ends matter.
345
template <typename Points, typename Functor>
346
36.5k
Status ForEachEquallySpacedPoint(const Points& points, const Functor& functor) {
347
36.5k
  JXL_ENSURE(!points.empty());
348
36.5k
  Spline::Point current = points.front();
349
36.5k
  functor(current, kDesiredRenderingDistance);
350
36.5k
  auto next = points.begin();
351
7.86M
  while (next != points.end()) {
352
7.86M
    const Spline::Point* previous = &current;
353
7.86M
    float arclength_from_previous = 0.f;
354
11.5M
    for (;;) {
355
11.5M
      if (next == points.end()) {
356
36.5k
        functor(*previous, arclength_from_previous);
357
36.5k
        return true;
358
36.5k
      }
359
11.5M
      const float arclength_to_next =
360
11.5M
          std::sqrt((*next - *previous).SquaredNorm());
361
11.5M
      if (arclength_from_previous + arclength_to_next >=
362
11.5M
          kDesiredRenderingDistance) {
363
7.82M
        current =
364
7.82M
            *previous + ((kDesiredRenderingDistance - arclength_from_previous) /
365
7.82M
                         arclength_to_next) *
366
7.82M
                            (*next - *previous);
367
7.82M
        functor(current, kDesiredRenderingDistance);
368
7.82M
        break;
369
7.82M
      }
370
3.72M
      arclength_from_previous += arclength_to_next;
371
3.72M
      previous = &*next;
372
3.72M
      ++next;
373
3.72M
    }
374
7.86M
  }
375
0
  return true;
376
36.5k
}
377
378
}  // namespace
379
380
StatusOr<QuantizedSpline> QuantizedSpline::Create(
381
    const Spline& original, const int32_t quantization_adjustment,
382
0
    const float y_to_x, const float y_to_b) {
383
0
  JXL_ENSURE(!original.control_points.empty());
384
0
  QuantizedSpline result;
385
0
  result.control_points_.reserve(original.control_points.size() - 1);
386
0
  const Spline::Point& starting_point = original.control_points.front();
387
0
  int previous_x = static_cast<int>(std::round(starting_point.x));
388
0
  int previous_y = static_cast<int>(std::round(starting_point.y));
389
0
  int previous_delta_x = 0;
390
0
  int previous_delta_y = 0;
391
0
  for (auto it = original.control_points.begin() + 1;
392
0
       it != original.control_points.end(); ++it) {
393
0
    const int new_x = static_cast<int>(std::round(it->x));
394
0
    const int new_y = static_cast<int>(std::round(it->y));
395
0
    const int new_delta_x = new_x - previous_x;
396
0
    const int new_delta_y = new_y - previous_y;
397
0
    result.control_points_.emplace_back(new_delta_x - previous_delta_x,
398
0
                                        new_delta_y - previous_delta_y);
399
0
    previous_delta_x = new_delta_x;
400
0
    previous_delta_y = new_delta_y;
401
0
    previous_x = new_x;
402
0
    previous_y = new_y;
403
0
  }
404
405
0
  const auto to_int = [](float v) -> int {
406
    // Maximal int representable with float.
407
0
    constexpr float kMax = std::numeric_limits<int>::max() - 127;
408
0
    constexpr float kMin = -kMax;
409
0
    return static_cast<int>(std::round(Clamp1(v, kMin, kMax)));
410
0
  };
411
412
0
  const auto quant = AdjustedQuant(quantization_adjustment);
413
0
  const auto inv_quant = InvAdjustedQuant(quantization_adjustment);
414
0
  for (int c : {1, 0, 2}) {
415
0
    float factor = (c == 0) ? y_to_x : (c == 1) ? 0 : y_to_b;
416
0
    for (int i = 0; i < 32; ++i) {
417
0
      const float dct_factor = (i == 0) ? kSqrt2 : 1.0f;
418
0
      const float inv_dct_factor = (i == 0) ? kSqrt0_5 : 1.0f;
419
0
      auto restored_y = result.color_dct_[1][i] * inv_dct_factor *
420
0
                        kChannelWeight[1] * inv_quant;
421
0
      auto decorrelated = original.color_dct[c][i] - factor * restored_y;
422
0
      result.color_dct_[c][i] =
423
0
          to_int(decorrelated * dct_factor * quant / kChannelWeight[c]);
424
0
    }
425
0
  }
426
0
  for (int i = 0; i < 32; ++i) {
427
0
    const float dct_factor = (i == 0) ? kSqrt2 : 1.0f;
428
0
    result.sigma_dct_[i] =
429
0
        to_int(original.sigma_dct[i] * dct_factor * quant / kChannelWeight[3]);
430
0
  }
431
0
  return result;
432
0
}
433
434
Status QuantizedSpline::Dequantize(const Spline::Point& starting_point,
435
                                   const int32_t quantization_adjustment,
436
                                   const float y_to_x, const float y_to_b,
437
                                   const uint64_t image_size,
438
                                   uint64_t* total_estimated_area_reached,
439
37.0k
                                   Spline& result) const {
440
37.0k
  constexpr uint64_t kOne = static_cast<uint64_t>(1);
441
37.0k
  const uint64_t area_limit =
442
37.0k
      std::min(1024 * image_size + (kOne << 32), kOne << 42);
443
444
37.0k
  result.control_points.clear();
445
37.0k
  result.control_points.reserve(control_points_.size() + 1);
446
37.0k
  float px = std::round(starting_point.x);
447
37.0k
  float py = std::round(starting_point.y);
448
37.0k
  JXL_RETURN_IF_ERROR(ValidateSplinePointPos(px, py));
449
37.0k
  int current_x = static_cast<int>(px);
450
37.0k
  int current_y = static_cast<int>(py);
451
37.0k
  result.control_points.emplace_back(static_cast<float>(current_x),
452
37.0k
                                     static_cast<float>(current_y));
453
37.0k
  int current_delta_x = 0;
454
37.0k
  int current_delta_y = 0;
455
37.0k
  uint64_t manhattan_distance = 0;
456
234k
  for (const auto& point : control_points_) {
457
234k
    current_delta_x += point.first;
458
234k
    current_delta_y += point.second;
459
234k
    manhattan_distance += std::abs(current_delta_x) + std::abs(current_delta_y);
460
234k
    if (manhattan_distance > area_limit) {
461
0
      return JXL_FAILURE("Too large manhattan_distance reached: %" PRIu64,
462
0
                         manhattan_distance);
463
0
    }
464
234k
    JXL_RETURN_IF_ERROR(
465
234k
        ValidateSplinePointPos(current_delta_x, current_delta_y));
466
234k
    current_x += current_delta_x;
467
234k
    current_y += current_delta_y;
468
234k
    JXL_RETURN_IF_ERROR(ValidateSplinePointPos(current_x, current_y));
469
234k
    result.control_points.emplace_back(static_cast<float>(current_x),
470
234k
                                       static_cast<float>(current_y));
471
234k
  }
472
473
37.0k
  const auto inv_quant = InvAdjustedQuant(quantization_adjustment);
474
148k
  for (int c = 0; c < 3; ++c) {
475
3.66M
    for (int i = 0; i < 32; ++i) {
476
3.55M
      const float inv_dct_factor = (i == 0) ? kSqrt0_5 : 1.0f;
477
3.55M
      result.color_dct[c][i] =
478
3.55M
          color_dct_[c][i] * inv_dct_factor * kChannelWeight[c] * inv_quant;
479
3.55M
    }
480
111k
  }
481
1.22M
  for (int i = 0; i < 32; ++i) {
482
1.18M
    result.color_dct[0][i] += y_to_x * result.color_dct[1][i];
483
1.18M
    result.color_dct[2][i] += y_to_b * result.color_dct[1][i];
484
1.18M
  }
485
37.0k
  uint64_t width_estimate = 0;
486
487
37.0k
  uint64_t color[3] = {};
488
148k
  for (int c = 0; c < 3; ++c) {
489
3.66M
    for (int i = 0; i < 32; ++i) {
490
3.55M
      color[c] += static_cast<uint64_t>(
491
3.55M
          std::ceil(inv_quant * std::abs(color_dct_[c][i])));
492
3.55M
    }
493
111k
  }
494
37.0k
  color[0] += static_cast<uint64_t>(std::ceil(std::abs(y_to_x))) * color[1];
495
37.0k
  color[2] += static_cast<uint64_t>(std::ceil(std::abs(y_to_b))) * color[1];
496
  // This is not taking kChannelWeight into account, but up to constant factors
497
  // it gives an indication of the influence of the color values on the area
498
  // that will need to be rendered.
499
37.0k
  const uint64_t max_color = std::max({color[1], color[0], color[2]});
500
37.0k
  uint64_t logcolor =
501
37.0k
      std::max(kOne, static_cast<uint64_t>(CeilLog2Nonzero(kOne + max_color)));
502
503
37.0k
  const float weight_limit =
504
37.0k
      std::ceil(std::sqrt((static_cast<float>(area_limit) / logcolor) /
505
37.0k
                          std::max<size_t>(1, manhattan_distance)));
506
507
1.22M
  for (int i = 0; i < 32; ++i) {
508
1.18M
    const float inv_dct_factor = (i == 0) ? kSqrt0_5 : 1.0f;
509
1.18M
    result.sigma_dct[i] =
510
1.18M
        sigma_dct_[i] * inv_dct_factor * kChannelWeight[3] * inv_quant;
511
    // If we include the factor kChannelWeight[3]=.3333f here, we get a
512
    // realistic area estimate. We leave it out to simplify the calculations,
513
    // and understand that this way we underestimate the area by a factor of
514
    // 1/(0.3333*0.3333). This is taken into account in the limits below.
515
1.18M
    float weight_f = std::ceil(inv_quant * std::abs(sigma_dct_[i]));
516
1.18M
    uint64_t weight =
517
1.18M
        static_cast<uint64_t>(std::min(weight_limit, std::max(1.0f, weight_f)));
518
1.18M
    width_estimate += weight * weight * logcolor;
519
1.18M
  }
520
37.0k
  *total_estimated_area_reached += (width_estimate * manhattan_distance);
521
37.0k
  if (*total_estimated_area_reached > area_limit) {
522
18
    return JXL_FAILURE("Too large total_estimated_area eached: %" PRIu64,
523
18
                       *total_estimated_area_reached);
524
18
  }
525
526
36.9k
  return true;
527
37.0k
}
528
529
Status QuantizedSpline::Decode(const std::vector<uint8_t>& context_map,
530
                               ANSSymbolReader* const decoder,
531
                               BitReader* const br,
532
                               const size_t max_control_points,
533
967k
                               size_t* total_num_control_points) {
534
967k
  const size_t num_control_points =
535
967k
      decoder->ReadHybridUint(kNumControlPointsContext, br, context_map);
536
967k
  if (num_control_points > max_control_points) {
537
1.29k
    return JXL_FAILURE("Too many control points: %" PRIuS, num_control_points);
538
1.29k
  }
539
965k
  *total_num_control_points += num_control_points;
540
965k
  if (*total_num_control_points > max_control_points) {
541
59
    return JXL_FAILURE("Too many control points: %" PRIuS,
542
59
                       *total_num_control_points);
543
59
  }
544
965k
  control_points_.resize(num_control_points);
545
  // Maximal image dimension.
546
965k
  constexpr int64_t kDeltaLimit = 1u << 30;
547
965k
  for (std::pair<int64_t, int64_t>& control_point : control_points_) {
548
766k
    control_point.first = UnpackSigned(
549
766k
        decoder->ReadHybridUint(kControlPointsContext, br, context_map));
550
766k
    control_point.second = UnpackSigned(
551
766k
        decoder->ReadHybridUint(kControlPointsContext, br, context_map));
552
    // Check delta-deltas are not outrageous; it is not in spec, but there is
553
    // no reason to allow larger values.
554
766k
    if ((control_point.first >= kDeltaLimit) ||
555
766k
        (control_point.first <= -kDeltaLimit) ||
556
766k
        (control_point.second >= kDeltaLimit) ||
557
766k
        (control_point.second <= -kDeltaLimit)) {
558
12
      return JXL_FAILURE("Spline delta-delta is out of bounds");
559
12
    }
560
766k
  }
561
562
3.86M
  const auto decode_dct = [decoder, br, &context_map](int dct[32]) -> Status {
563
3.86M
    constexpr int kWeirdNumber = std::numeric_limits<int>::min();
564
127M
    for (int i = 0; i < 32; ++i) {
565
123M
      dct[i] =
566
123M
          UnpackSigned(decoder->ReadHybridUint(kDCTContext, br, context_map));
567
123M
      if (dct[i] == kWeirdNumber) {
568
8
        return JXL_FAILURE("The weird number in spline DCT");
569
8
      }
570
123M
    }
571
3.86M
    return true;
572
3.86M
  };
573
2.89M
  for (auto& dct : color_dct_) {
574
2.89M
    JXL_RETURN_IF_ERROR(decode_dct(dct));
575
2.89M
  }
576
965k
  JXL_RETURN_IF_ERROR(decode_dct(sigma_dct_));
577
965k
  return true;
578
965k
}
579
580
52.8k
void Splines::Clear() {
581
52.8k
  quantization_adjustment_ = 0;
582
52.8k
  splines_.clear();
583
52.8k
  starting_points_.clear();
584
52.8k
  segments_.clear();
585
52.8k
  segment_indices_.clear();
586
52.8k
  segment_y_start_.clear();
587
52.8k
}
588
589
Status Splines::Decode(JxlMemoryManager* memory_manager, jxl::BitReader* br,
590
23.9k
                       const size_t num_pixels) {
591
23.9k
  std::vector<uint8_t> context_map;
592
23.9k
  ANSCode code;
593
23.9k
  JXL_RETURN_IF_ERROR(DecodeHistograms(memory_manager, br, kNumSplineContexts,
594
23.9k
                                       &code, &context_map));
595
45.6k
  JXL_ASSIGN_OR_RETURN(ANSSymbolReader decoder,
596
45.6k
                       ANSSymbolReader::Create(&code, br));
597
45.6k
  size_t num_splines =
598
45.6k
      decoder.ReadHybridUint(kNumSplinesContext, br, context_map);
599
45.6k
  size_t max_control_points = std::min(
600
45.6k
      kMaxNumControlPoints, num_pixels / kMaxNumControlPointsPerPixelRatio);
601
45.6k
  if (num_splines > max_control_points ||
602
22.8k
      num_splines + 1 > max_control_points) {
603
152
    return JXL_FAILURE("Too many splines: %" PRIuS, num_splines);
604
152
  }
605
22.6k
  num_splines++;
606
22.6k
  JXL_RETURN_IF_ERROR(DecodeAllStartingPoints(&starting_points_, br, &decoder,
607
22.6k
                                              context_map, num_splines));
608
609
22.6k
  quantization_adjustment_ = UnpackSigned(
610
22.6k
      decoder.ReadHybridUint(kQuantizationAdjustmentContext, br, context_map));
611
612
22.6k
  splines_.clear();
613
22.6k
  splines_.reserve(num_splines);
614
22.6k
  size_t num_control_points = num_splines;
615
988k
  for (size_t i = 0; i < num_splines; ++i) {
616
967k
    QuantizedSpline spline;
617
967k
    JXL_RETURN_IF_ERROR(spline.Decode(context_map, &decoder, br,
618
967k
                                      max_control_points, &num_control_points));
619
965k
    splines_.push_back(std::move(spline));
620
965k
  }
621
622
21.2k
  JXL_RETURN_IF_ERROR(decoder.CheckANSFinalState());
623
624
21.2k
  if (!HasAny()) {
625
0
    return JXL_FAILURE("Decoded splines but got none");
626
0
  }
627
628
21.2k
  return true;
629
21.2k
}
630
631
0
void Splines::AddTo(Image3F* const opsin, const Rect& opsin_rect) const {
632
0
  Apply</*add=*/true>(opsin, opsin_rect);
633
0
}
634
void Splines::AddToRow(float* JXL_RESTRICT row_x, float* JXL_RESTRICT row_y,
635
                       float* JXL_RESTRICT row_b, size_t y, size_t x0,
636
536k
                       size_t x1) const {
637
536k
  ApplyToRow</*add=*/true>(row_x, row_y, row_b, y, x0, x1);
638
536k
}
639
640
2.13k
void Splines::SubtractFrom(Image3F* const opsin) const {
641
2.13k
  Apply</*add=*/false>(opsin, Rect(*opsin));
642
2.13k
}
643
644
Status Splines::InitializeDrawCache(const size_t image_xsize,
645
                                    const size_t image_ysize,
646
22.5k
                                    const ColorCorrelation& color_correlation) {
647
  // TODO(veluca): avoid storing segments that are entirely outside image
648
  // boundaries.
649
22.5k
  segments_.clear();
650
22.5k
  segment_indices_.clear();
651
22.5k
  segment_y_start_.clear();
652
22.5k
  std::vector<std::pair<size_t, size_t>> segments_by_y;
653
22.5k
  std::vector<Spline::Point> intermediate_points;
654
22.5k
  uint64_t total_estimated_area_reached = 0;
655
22.5k
  std::vector<Spline> splines;
656
59.3k
  for (size_t i = 0; i < splines_.size(); ++i) {
657
37.0k
    Spline spline;
658
37.0k
    JXL_RETURN_IF_ERROR(splines_[i].Dequantize(
659
37.0k
        starting_points_[i], quantization_adjustment_,
660
37.0k
        color_correlation.YtoXRatio(0), color_correlation.YtoBRatio(0),
661
37.0k
        image_xsize * image_ysize, &total_estimated_area_reached, spline));
662
36.9k
    if (std::adjacent_find(spline.control_points.begin(),
663
36.9k
                           spline.control_points.end()) !=
664
36.9k
        spline.control_points.end()) {
665
      // Otherwise division by zero might occur. Once control points coincide,
666
      // the direction of curve is undefined...
667
203
      return JXL_FAILURE(
668
203
          "identical successive control points in spline %" PRIuS, i);
669
203
    }
670
36.7k
    splines.push_back(spline);
671
36.7k
  }
672
  // TODO(firsching) Change this into a JXL_FAILURE for level 5 codestreams.
673
22.3k
  if (total_estimated_area_reached >
674
22.3k
      std::min(
675
22.3k
          (8 * image_xsize * image_ysize + (static_cast<uint64_t>(1) << 25)),
676
22.3k
          (static_cast<uint64_t>(1) << 30))) {
677
15
    JXL_WARNING(
678
15
        "Large total_estimated_area_reached, expect slower decoding: %" PRIu64,
679
15
        total_estimated_area_reached);
680
15
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
681
15
    return JXL_FAILURE("Total spline area is too large");
682
15
#endif
683
15
  }
684
685
36.5k
  for (Spline& spline : splines) {
686
36.5k
    std::vector<std::pair<Spline::Point, float>> points_to_draw;
687
7.90M
    auto add_point = [&](const Spline::Point& point, const float multiplier) {
688
7.90M
      points_to_draw.emplace_back(point, multiplier);
689
7.90M
    };
690
36.5k
    intermediate_points.clear();
691
36.5k
    DrawCentripetalCatmullRomSpline(spline.control_points, intermediate_points);
692
36.5k
    JXL_RETURN_IF_ERROR(
693
36.5k
        ForEachEquallySpacedPoint(intermediate_points, add_point));
694
36.5k
    const float arc_length =
695
36.5k
        (points_to_draw.size() - 2) * kDesiredRenderingDistance +
696
36.5k
        points_to_draw.back().second;
697
36.5k
    if (arc_length <= 0.f) {
698
      // This spline wouldn't have any effect.
699
15.4k
      continue;
700
15.4k
    }
701
21.0k
    HWY_DYNAMIC_DISPATCH(SegmentsFromPoints)
702
21.0k
    (spline, points_to_draw, arc_length, segments_, segments_by_y);
703
21.0k
  }
704
705
  // TODO(eustas): consider linear sorting here.
706
22.3k
  std::sort(segments_by_y.begin(), segments_by_y.end());
707
22.3k
  segment_indices_.resize(segments_by_y.size());
708
22.3k
  segment_y_start_.resize(image_ysize + 1);
709
25.1M
  for (size_t i = 0; i < segments_by_y.size(); i++) {
710
25.1M
    segment_indices_[i] = segments_by_y[i].second;
711
25.1M
    size_t y = segments_by_y[i].first;
712
25.1M
    if (y < image_ysize) {
713
13.0M
      segment_y_start_[y + 1]++;
714
13.0M
    }
715
25.1M
  }
716
1.99M
  for (size_t y = 0; y < image_ysize; y++) {
717
1.97M
    segment_y_start_[y + 1] += segment_y_start_[y];
718
1.97M
  }
719
22.3k
  return true;
720
22.3k
}
721
722
template <bool add>
723
void Splines::ApplyToRow(float* JXL_RESTRICT row_x, float* JXL_RESTRICT row_y,
724
                         float* JXL_RESTRICT row_b, size_t y, size_t x0,
725
536k
                         size_t x1) const {
726
536k
  if (segments_.empty()) return;
727
532k
  HWY_DYNAMIC_DISPATCH(DrawSegments)
728
532k
  (row_x, row_y, row_b, y, x0, x1, add, segments_.data(),
729
532k
   segment_indices_.data(), segment_y_start_.data());
730
532k
}
void jxl::Splines::ApplyToRow<true>(float*, float*, float*, unsigned long, unsigned long, unsigned long) const
Line
Count
Source
725
536k
                         size_t x1) const {
726
536k
  if (segments_.empty()) return;
727
532k
  HWY_DYNAMIC_DISPATCH(DrawSegments)
728
532k
  (row_x, row_y, row_b, y, x0, x1, add, segments_.data(),
729
532k
   segment_indices_.data(), segment_y_start_.data());
730
532k
}
Unexecuted instantiation: void jxl::Splines::ApplyToRow<false>(float*, float*, float*, unsigned long, unsigned long, unsigned long) const
731
732
template <bool add>
733
2.13k
void Splines::Apply(Image3F* const opsin, const Rect& opsin_rect) const {
734
2.13k
  if (segments_.empty()) return;
735
0
  const size_t y0 = opsin_rect.y0();
736
0
  const size_t x0 = opsin_rect.x0();
737
0
  const size_t x1 = opsin_rect.x1();
738
0
  for (size_t y = 0; y < opsin_rect.ysize(); y++) {
739
0
    ApplyToRow<add>(opsin->PlaneRow(0, y0 + y) + x0,
740
0
                    opsin->PlaneRow(1, y0 + y) + x0,
741
0
                    opsin->PlaneRow(2, y0 + y) + x0, y0 + y, x0, x1);
742
0
  }
743
0
}
Unexecuted instantiation: void jxl::Splines::Apply<true>(jxl::Image3<float>*, jxl::RectT<unsigned long> const&) const
void jxl::Splines::Apply<false>(jxl::Image3<float>*, jxl::RectT<unsigned long> const&) const
Line
Count
Source
733
2.13k
void Splines::Apply(Image3F* const opsin, const Rect& opsin_rect) const {
734
2.13k
  if (segments_.empty()) return;
735
0
  const size_t y0 = opsin_rect.y0();
736
0
  const size_t x0 = opsin_rect.x0();
737
0
  const size_t x1 = opsin_rect.x1();
738
0
  for (size_t y = 0; y < opsin_rect.ysize(); y++) {
739
0
    ApplyToRow<add>(opsin->PlaneRow(0, y0 + y) + x0,
740
0
                    opsin->PlaneRow(1, y0 + y) + x0,
741
0
                    opsin->PlaneRow(2, y0 + y) + x0, y0 + y, x0, x1);
742
0
  }
743
0
}
744
745
}  // namespace jxl
746
#endif  // HWY_ONCE