Coverage Report

Created: 2026-11-12 07:35

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