Coverage Report

Created: 2026-02-14 07:09

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