Coverage Report

Created: 2026-07-25 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/butteraugli/butteraugli.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
// Author: Jyrki Alakuijala (jyrki.alakuijala@gmail.com)
7
//
8
// The physical architecture of butteraugli is based on the following naming
9
// convention:
10
//   * Opsin - dynamics of the photosensitive chemicals in the retina
11
//             with their immediate electrical processing
12
//   * Xyb - hybrid opponent/trichromatic color space
13
//     x is roughly red-subtract-green.
14
//     y is yellow.
15
//     b is blue.
16
//     Xyb values are computed from Opsin mixing, not directly from rgb.
17
//   * Mask - for visual masking
18
//   * Hf - color modeling for spatially high-frequency features
19
//   * Lf - color modeling for spatially low-frequency features
20
//   * Diffmap - to cluster and build an image of error between the images
21
//   * Blur - to hold the smoothing code
22
23
#include "lib/jxl/butteraugli/butteraugli.h"
24
25
#include <jxl/memory_manager.h>
26
27
#include <algorithm>
28
#include <atomic>
29
#include <cmath>
30
#include <cstddef>
31
#include <cstdint>
32
#include <cstdio>
33
#include <cstdlib>
34
#include <cstring>
35
#include <memory>
36
37
#include "lib/jxl/base/common.h"
38
#include "lib/jxl/base/compiler_specific.h"
39
#include "lib/jxl/base/rect.h"
40
#include "lib/jxl/convolve.h"
41
#include "lib/jxl/image.h"
42
43
#undef HWY_TARGET_INCLUDE
44
#define HWY_TARGET_INCLUDE "lib/jxl/butteraugli/butteraugli.cc"
45
#include <hwy/foreach_target.h>
46
47
#include "lib/jxl/base/fast_math-inl.h"
48
#include "lib/jxl/base/status.h"
49
#include "lib/jxl/image_ops.h"
50
51
#if BUTTERAUGLI_ENABLE_CHECKS
52
#include "lib/jxl/base/printf_macros.h"
53
#endif
54
55
#ifndef JXL_BUTTERAUGLI_ONCE
56
#define JXL_BUTTERAUGLI_ONCE
57
58
namespace jxl {
59
60
static const double wMfMalta = 37.0819870399;
61
static const double norm1Mf = 130262059.556;
62
static const double wMfMaltaX = 8246.75321353;
63
static const double norm1MfX = 1009002.70582;
64
static const double wHfMalta = 18.7237414387;
65
static const double norm1Hf = 4498534.45232;
66
static const double wHfMaltaX = 6923.99476109;
67
static const double norm1HfX = 8051.15833247;
68
static const double wUhfMalta = 1.10039032555;
69
static const double norm1Uhf = 71.7800275169;
70
static const double wUhfMaltaX = 173.5;
71
static const double norm1UhfX = 5.0;
72
static const double wmul[9] = {
73
    400.0,         1.50815703118,  0,
74
    2150.0,        10.6195433239,  16.2176043152,
75
    29.2353797994, 0.844626970982, 0.703646627719,
76
};
77
78
0
std::vector<float> ComputeKernel(float sigma) {
79
0
  const float m = 2.25;  // Accuracy increases when m is increased.
80
0
  const double scaler = -1.0 / (2.0 * sigma * sigma);
81
0
  const int diff = std::max<int>(1, m * std::fabs(sigma));
82
0
  std::vector<float> kernel(2 * diff + 1);
83
0
  for (int i = -diff; i <= diff; ++i) {
84
0
    kernel[i + diff] = std::exp(scaler * i * i);
85
0
  }
86
0
  return kernel;
87
0
}
88
89
void ConvolveBorderColumn(const ImageF& in, const std::vector<float>& kernel,
90
0
                          const size_t x, float* BUTTERAUGLI_RESTRICT row_out) {
91
0
  const size_t offset = kernel.size() / 2;
92
0
  int minx = x < offset ? 0 : x - offset;
93
0
  int maxx = std::min<int>(in.xsize() - 1, x + offset);
94
0
  float weight = 0.0f;
95
0
  for (int j = minx; j <= maxx; ++j) {
96
0
    weight += kernel[j - x + offset];
97
0
  }
98
0
  float scale = 1.0f / weight;
99
0
  for (size_t y = 0; y < in.ysize(); ++y) {
100
0
    const float* BUTTERAUGLI_RESTRICT row_in = in.Row(y);
101
0
    float sum = 0.0f;
102
0
    for (int j = minx; j <= maxx; ++j) {
103
0
      sum += row_in[j] * kernel[j - x + offset];
104
0
    }
105
0
    row_out[y] = sum * scale;
106
0
  }
107
0
}
108
109
// Computes a horizontal convolution and transposes the result.
110
Status ConvolutionWithTranspose(const ImageF& in,
111
                                const std::vector<float>& kernel,
112
0
                                ImageF* BUTTERAUGLI_RESTRICT out) {
113
0
  JXL_ENSURE(out->xsize() == in.ysize());
114
0
  JXL_ENSURE(out->ysize() == in.xsize());
115
0
  const size_t len = kernel.size();
116
0
  const size_t offset = len / 2;
117
0
  float weight_no_border = 0.0f;
118
0
  for (size_t j = 0; j < len; ++j) {
119
0
    weight_no_border += kernel[j];
120
0
  }
121
0
  const float scale_no_border = 1.0f / weight_no_border;
122
0
  const size_t border1 = std::min(in.xsize(), offset);
123
0
  const size_t border2 = in.xsize() > offset ? in.xsize() - offset : 0;
124
0
  std::vector<float> scaled_kernel(len / 2 + 1);
125
0
  for (size_t i = 0; i <= len / 2; ++i) {
126
0
    scaled_kernel[i] = kernel[i] * scale_no_border;
127
0
  }
128
129
  // middle
130
0
  switch (len) {
131
0
    case 7: {
132
0
      const float sk0 = scaled_kernel[0];
133
0
      const float sk1 = scaled_kernel[1];
134
0
      const float sk2 = scaled_kernel[2];
135
0
      const float sk3 = scaled_kernel[3];
136
0
      for (size_t y = 0; y < in.ysize(); ++y) {
137
0
        const float* BUTTERAUGLI_RESTRICT row_in = in.Row(y) + border1 - offset;
138
0
        for (size_t x = border1; x < border2; ++x, ++row_in) {
139
0
          const float sum0 = (row_in[0] + row_in[6]) * sk0;
140
0
          const float sum1 = (row_in[1] + row_in[5]) * sk1;
141
0
          const float sum2 = (row_in[2] + row_in[4]) * sk2;
142
0
          const float sum = (row_in[3]) * sk3 + sum0 + sum1 + sum2;
143
0
          float* BUTTERAUGLI_RESTRICT row_out = out->Row(x);
144
0
          row_out[y] = sum;
145
0
        }
146
0
      }
147
0
    } break;
148
0
    case 13: {
149
0
      for (size_t y = 0; y < in.ysize(); ++y) {
150
0
        const float* BUTTERAUGLI_RESTRICT row_in = in.Row(y) + border1 - offset;
151
0
        for (size_t x = border1; x < border2; ++x, ++row_in) {
152
0
          float sum0 = (row_in[0] + row_in[12]) * scaled_kernel[0];
153
0
          float sum1 = (row_in[1] + row_in[11]) * scaled_kernel[1];
154
0
          float sum2 = (row_in[2] + row_in[10]) * scaled_kernel[2];
155
0
          float sum3 = (row_in[3] + row_in[9]) * scaled_kernel[3];
156
0
          sum0 += (row_in[4] + row_in[8]) * scaled_kernel[4];
157
0
          sum1 += (row_in[5] + row_in[7]) * scaled_kernel[5];
158
0
          const float sum = (row_in[6]) * scaled_kernel[6];
159
0
          float* BUTTERAUGLI_RESTRICT row_out = out->Row(x);
160
0
          row_out[y] = sum + sum0 + sum1 + sum2 + sum3;
161
0
        }
162
0
      }
163
0
      break;
164
0
    }
165
0
    case 15: {
166
0
      for (size_t y = 0; y < in.ysize(); ++y) {
167
0
        const float* BUTTERAUGLI_RESTRICT row_in = in.Row(y) + border1 - offset;
168
0
        for (size_t x = border1; x < border2; ++x, ++row_in) {
169
0
          float sum0 = (row_in[0] + row_in[14]) * scaled_kernel[0];
170
0
          float sum1 = (row_in[1] + row_in[13]) * scaled_kernel[1];
171
0
          float sum2 = (row_in[2] + row_in[12]) * scaled_kernel[2];
172
0
          float sum3 = (row_in[3] + row_in[11]) * scaled_kernel[3];
173
0
          sum0 += (row_in[4] + row_in[10]) * scaled_kernel[4];
174
0
          sum1 += (row_in[5] + row_in[9]) * scaled_kernel[5];
175
0
          sum2 += (row_in[6] + row_in[8]) * scaled_kernel[6];
176
0
          const float sum = (row_in[7]) * scaled_kernel[7];
177
0
          float* BUTTERAUGLI_RESTRICT row_out = out->Row(x);
178
0
          row_out[y] = sum + sum0 + sum1 + sum2 + sum3;
179
0
        }
180
0
      }
181
0
      break;
182
0
    }
183
0
    case 33: {
184
0
      for (size_t y = 0; y < in.ysize(); ++y) {
185
0
        const float* BUTTERAUGLI_RESTRICT row_in = in.Row(y) + border1 - offset;
186
0
        for (size_t x = border1; x < border2; ++x, ++row_in) {
187
0
          float sum0 = (row_in[0] + row_in[32]) * scaled_kernel[0];
188
0
          float sum1 = (row_in[1] + row_in[31]) * scaled_kernel[1];
189
0
          float sum2 = (row_in[2] + row_in[30]) * scaled_kernel[2];
190
0
          float sum3 = (row_in[3] + row_in[29]) * scaled_kernel[3];
191
0
          sum0 += (row_in[4] + row_in[28]) * scaled_kernel[4];
192
0
          sum1 += (row_in[5] + row_in[27]) * scaled_kernel[5];
193
0
          sum2 += (row_in[6] + row_in[26]) * scaled_kernel[6];
194
0
          sum3 += (row_in[7] + row_in[25]) * scaled_kernel[7];
195
0
          sum0 += (row_in[8] + row_in[24]) * scaled_kernel[8];
196
0
          sum1 += (row_in[9] + row_in[23]) * scaled_kernel[9];
197
0
          sum2 += (row_in[10] + row_in[22]) * scaled_kernel[10];
198
0
          sum3 += (row_in[11] + row_in[21]) * scaled_kernel[11];
199
0
          sum0 += (row_in[12] + row_in[20]) * scaled_kernel[12];
200
0
          sum1 += (row_in[13] + row_in[19]) * scaled_kernel[13];
201
0
          sum2 += (row_in[14] + row_in[18]) * scaled_kernel[14];
202
0
          sum3 += (row_in[15] + row_in[17]) * scaled_kernel[15];
203
0
          const float sum = (row_in[16]) * scaled_kernel[16];
204
0
          float* BUTTERAUGLI_RESTRICT row_out = out->Row(x);
205
0
          row_out[y] = sum + sum0 + sum1 + sum2 + sum3;
206
0
        }
207
0
      }
208
0
      break;
209
0
    }
210
0
    default:
211
0
      return JXL_UNREACHABLE("kernel size %d not implemented",
212
0
                             static_cast<int>(len));
213
0
  }
214
  // left border
215
0
  for (size_t x = 0; x < border1; ++x) {
216
0
    ConvolveBorderColumn(in, kernel, x, out->Row(x));
217
0
  }
218
219
  // right border
220
0
  for (size_t x = border2; x < in.xsize(); ++x) {
221
0
    ConvolveBorderColumn(in, kernel, x, out->Row(x));
222
0
  }
223
0
  return true;
224
0
}
225
226
// A blur somewhat similar to a 2D Gaussian blur.
227
// See: https://en.wikipedia.org/wiki/Gaussian_blur
228
//
229
// This is a bottleneck because the sigma can be quite large (>7). We can use
230
// gauss_blur.cc (runtime independent of sigma, closer to a 4*sigma truncated
231
// Gaussian and our 2.25 in ComputeKernel), but its boundary conditions are
232
// zero-valued. This leads to noticeable differences at the edges of diffmaps.
233
// We retain a special case for 5x5 kernels (even faster than gauss_blur),
234
// optionally use gauss_blur followed by fixup of the borders for large images,
235
// or fall back to the previous truncated FIR followed by a transpose.
236
Status Blur(const ImageF& in, float sigma, const ButteraugliParams& params,
237
0
            BlurTemp* temp, ImageF* out) {
238
0
  std::vector<float> kernel = ComputeKernel(sigma);
239
  // Separable5 does an in-place convolution, so this fast path is not safe if
240
  // in aliases out.
241
0
  if (kernel.size() == 5 && &in != out) {
242
0
    float sum_weights = 0.0f;
243
0
    for (const float w : kernel) {
244
0
      sum_weights += w;
245
0
    }
246
0
    const float scale = 1.0f / sum_weights;
247
0
    const float w0 = kernel[2] * scale;
248
0
    const float w1 = kernel[1] * scale;
249
0
    const float w2 = kernel[0] * scale;
250
0
    const WeightsSeparable5 weights = {
251
0
        {HWY_REP4(w0), HWY_REP4(w1), HWY_REP4(w2)},
252
0
        {HWY_REP4(w0), HWY_REP4(w1), HWY_REP4(w2)},
253
0
    };
254
0
    JXL_RETURN_IF_ERROR(
255
0
        Separable5(in, Rect(in), weights, /*pool=*/nullptr, out));
256
0
    return true;
257
0
  }
258
259
0
  ImageF* temp_t;
260
0
  JXL_RETURN_IF_ERROR(temp->GetTransposed(in, &temp_t));
261
0
  JXL_RETURN_IF_ERROR(ConvolutionWithTranspose(in, kernel, temp_t));
262
0
  JXL_RETURN_IF_ERROR(ConvolutionWithTranspose(*temp_t, kernel, out));
263
0
  return true;
264
0
}
265
266
// Allows PaddedMaltaUnit to call either function via overloading.
267
struct MaltaTagLF {};
268
struct MaltaTag {};
269
270
}  // namespace jxl
271
272
#endif  // JXL_BUTTERAUGLI_ONCE
273
274
#include <hwy/highway.h>
275
HWY_BEFORE_NAMESPACE();
276
namespace jxl {
277
namespace HWY_NAMESPACE {
278
279
// These templates are not found via ADL.
280
using hwy::HWY_NAMESPACE::Abs;
281
using hwy::HWY_NAMESPACE::Div;
282
using hwy::HWY_NAMESPACE::Gt;
283
using hwy::HWY_NAMESPACE::IfThenElse;
284
using hwy::HWY_NAMESPACE::IfThenElseZero;
285
using hwy::HWY_NAMESPACE::Lt;
286
using hwy::HWY_NAMESPACE::Max;
287
using hwy::HWY_NAMESPACE::Mul;
288
using hwy::HWY_NAMESPACE::MulAdd;
289
using hwy::HWY_NAMESPACE::MulSub;
290
using hwy::HWY_NAMESPACE::Neg;
291
using hwy::HWY_NAMESPACE::Sub;
292
using hwy::HWY_NAMESPACE::Vec;
293
using hwy::HWY_NAMESPACE::ZeroIfNegative;
294
295
template <class D, class V>
296
0
HWY_INLINE V MaximumClamp(D d, V v, double kMaxVal) {
297
0
  static const double kMul = 0.724216145665;
298
0
  const V mul = Set(d, kMul);
299
0
  const V maxval = Set(d, kMaxVal);
300
  // If greater than maxval or less than -maxval, replace with if_*.
301
0
  const V if_pos = MulAdd(Sub(v, maxval), mul, maxval);
302
0
  const V if_neg = MulSub(Add(v, maxval), mul, maxval);
303
0
  const V pos_or_v = IfThenElse(Ge(v, maxval), if_pos, v);
304
0
  return IfThenElse(Lt(v, Neg(maxval)), if_neg, pos_or_v);
305
0
}
306
307
// Make area around zero less important (remove it).
308
template <class D, class V>
309
0
HWY_INLINE V RemoveRangeAroundZero(const D d, const double kw, const V x) {
310
0
  const auto w = Set(d, kw);
311
0
  return IfThenElse(Gt(x, w), Sub(x, w),
312
0
                    IfThenElseZero(Lt(x, Neg(w)), Add(x, w)));
313
0
}
314
315
// Make area around zero more important (2x it until the limit).
316
template <class D, class V>
317
0
HWY_INLINE V AmplifyRangeAroundZero(const D d, const double kw, const V x) {
318
0
  const auto w = Set(d, kw);
319
0
  return IfThenElse(Gt(x, w), Add(x, w),
320
0
                    IfThenElse(Lt(x, Neg(w)), Sub(x, w), Add(x, x)));
321
0
}
322
323
// XybLowFreqToVals converts from low-frequency XYB space to the 'vals' space.
324
// Vals space can be converted to L2-norm space (Euclidean and normalized)
325
// through visual masking.
326
template <class D, class V>
327
HWY_INLINE void XybLowFreqToVals(const D d, const V& x, const V& y,
328
                                 const V& b_arg, V* HWY_RESTRICT valx,
329
0
                                 V* HWY_RESTRICT valy, V* HWY_RESTRICT valb) {
330
0
  static const double xmul_scalar = 33.832837186260;
331
0
  static const double ymul_scalar = 14.458268100570;
332
0
  static const double bmul_scalar = 49.87984651440;
333
0
  static const double y_to_b_mul_scalar = -0.362267051518;
334
0
  const V xmul = Set(d, xmul_scalar);
335
0
  const V ymul = Set(d, ymul_scalar);
336
0
  const V bmul = Set(d, bmul_scalar);
337
0
  const V y_to_b_mul = Set(d, y_to_b_mul_scalar);
338
0
  const V b = MulAdd(y_to_b_mul, y, b_arg);
339
0
  *valb = Mul(b, bmul);
340
0
  *valx = Mul(x, xmul);
341
0
  *valy = Mul(y, ymul);
342
0
}
343
344
0
void XybLowFreqToVals(Image3F* xyb_lf) {
345
  // Modify range around zero code only concerns the high frequency
346
  // planes and only the X and Y channels.
347
  // Convert low freq xyb to vals space so that we can do a simple squared sum
348
  // diff on the low frequencies later.
349
0
  const HWY_FULL(float) d;
350
0
  for (size_t y = 0; y < xyb_lf->ysize(); ++y) {
351
0
    float* BUTTERAUGLI_RESTRICT row_x = xyb_lf->PlaneRow(0, y);
352
0
    float* BUTTERAUGLI_RESTRICT row_y = xyb_lf->PlaneRow(1, y);
353
0
    float* BUTTERAUGLI_RESTRICT row_b = xyb_lf->PlaneRow(2, y);
354
0
    for (size_t x = 0; x < xyb_lf->xsize(); x += Lanes(d)) {
355
0
      auto valx = Undefined(d);
356
0
      auto valy = Undefined(d);
357
0
      auto valb = Undefined(d);
358
0
      XybLowFreqToVals(d, Load(d, row_x + x), Load(d, row_y + x),
359
0
                       Load(d, row_b + x), &valx, &valy, &valb);
360
0
      Store(valx, d, row_x + x);
361
0
      Store(valy, d, row_y + x);
362
0
      Store(valb, d, row_b + x);
363
0
    }
364
0
  }
365
0
}
366
367
0
Status SuppressXByY(const ImageF& in_y, ImageF* HWY_RESTRICT inout_x) {
368
0
  JXL_ENSURE(SameSize(*inout_x, in_y));
369
0
  const size_t xsize = in_y.xsize();
370
0
  const size_t ysize = in_y.ysize();
371
0
  const HWY_FULL(float) d;
372
0
  static const double suppress = 46.0;
373
0
  static const double s = 0.653020556257;
374
0
  const auto sv = Set(d, s);
375
0
  const auto one_minus_s = Set(d, 1.0 - s);
376
0
  const auto ywv = Set(d, suppress);
377
378
0
  for (size_t y = 0; y < ysize; ++y) {
379
0
    const float* HWY_RESTRICT row_y = in_y.ConstRow(y);
380
0
    float* HWY_RESTRICT row_x = inout_x->Row(y);
381
0
    for (size_t x = 0; x < xsize; x += Lanes(d)) {
382
0
      const auto vx = Load(d, row_x + x);
383
0
      const auto vy = Load(d, row_y + x);
384
0
      const auto scaler =
385
0
          MulAdd(Div(ywv, MulAdd(vy, vy, ywv)), one_minus_s, sv);
386
0
      Store(Mul(scaler, vx), d, row_x + x);
387
0
    }
388
0
  }
389
0
  return true;
390
0
}
391
392
0
void Subtract(const ImageF& a, const ImageF& b, ImageF* c) {
393
0
  const HWY_FULL(float) d;
394
0
  for (size_t y = 0; y < a.ysize(); ++y) {
395
0
    const float* row_a = a.ConstRow(y);
396
0
    const float* row_b = b.ConstRow(y);
397
0
    float* row_c = c->Row(y);
398
0
    for (size_t x = 0; x < a.xsize(); x += Lanes(d)) {
399
0
      Store(Sub(Load(d, row_a + x), Load(d, row_b + x)), d, row_c + x);
400
0
    }
401
0
  }
402
0
}
403
404
Status SeparateLFAndMF(const ButteraugliParams& params, const Image3F& xyb,
405
0
                       Image3F* lf, Image3F* mf, BlurTemp* blur_temp) {
406
0
  static const double kSigmaLf = 7.15593339443;
407
0
  for (int i = 0; i < 3; ++i) {
408
    // Extract lf ...
409
0
    JXL_RETURN_IF_ERROR(
410
0
        Blur(xyb.Plane(i), kSigmaLf, params, blur_temp, &lf->Plane(i)));
411
    // ... and keep everything else in mf.
412
0
    Subtract(xyb.Plane(i), lf->Plane(i), &mf->Plane(i));
413
0
  }
414
0
  XybLowFreqToVals(lf);
415
0
  return true;
416
0
}
417
418
Status SeparateMFAndHF(const ButteraugliParams& params, Image3F* mf, ImageF* hf,
419
0
                       BlurTemp* blur_temp) {
420
0
  const HWY_FULL(float) d;
421
0
  static const double kSigmaHf = 3.22489901262;
422
0
  const size_t xsize = mf->xsize();
423
0
  const size_t ysize = mf->ysize();
424
0
  JxlMemoryManager* memory_manager = mf[0].memory_manager();
425
0
  JXL_ASSIGN_OR_RETURN(hf[0], ImageF::Create(memory_manager, xsize, ysize));
426
0
  JXL_ASSIGN_OR_RETURN(hf[1], ImageF::Create(memory_manager, xsize, ysize));
427
0
  for (int i = 0; i < 3; ++i) {
428
0
    if (i == 2) {
429
0
      JXL_RETURN_IF_ERROR(
430
0
          Blur(mf->Plane(i), kSigmaHf, params, blur_temp, &mf->Plane(i)));
431
0
      break;
432
0
    }
433
0
    for (size_t y = 0; y < ysize; ++y) {
434
0
      float* BUTTERAUGLI_RESTRICT row_mf = mf->PlaneRow(i, y);
435
0
      float* BUTTERAUGLI_RESTRICT row_hf = hf[i].Row(y);
436
0
      for (size_t x = 0; x < xsize; x += Lanes(d)) {
437
0
        Store(Load(d, row_mf + x), d, row_hf + x);
438
0
      }
439
0
    }
440
0
    JXL_RETURN_IF_ERROR(
441
0
        Blur(mf->Plane(i), kSigmaHf, params, blur_temp, &mf->Plane(i)));
442
0
    static const double kRemoveMfRange = 0.29;
443
0
    static const double kAddMfRange = 0.1;
444
0
    if (i == 0) {
445
0
      for (size_t y = 0; y < ysize; ++y) {
446
0
        float* BUTTERAUGLI_RESTRICT row_mf = mf->PlaneRow(0, y);
447
0
        float* BUTTERAUGLI_RESTRICT row_hf = hf[0].Row(y);
448
0
        for (size_t x = 0; x < xsize; x += Lanes(d)) {
449
0
          auto mfv = Load(d, row_mf + x);
450
0
          auto hfv = Sub(Load(d, row_hf + x), mfv);
451
0
          mfv = RemoveRangeAroundZero(d, kRemoveMfRange, mfv);
452
0
          Store(mfv, d, row_mf + x);
453
0
          Store(hfv, d, row_hf + x);
454
0
        }
455
0
      }
456
0
    } else {
457
0
      for (size_t y = 0; y < ysize; ++y) {
458
0
        float* BUTTERAUGLI_RESTRICT row_mf = mf->PlaneRow(1, y);
459
0
        float* BUTTERAUGLI_RESTRICT row_hf = hf[1].Row(y);
460
0
        for (size_t x = 0; x < xsize; x += Lanes(d)) {
461
0
          auto mfv = Load(d, row_mf + x);
462
0
          auto hfv = Sub(Load(d, row_hf + x), mfv);
463
464
0
          mfv = AmplifyRangeAroundZero(d, kAddMfRange, mfv);
465
0
          Store(mfv, d, row_mf + x);
466
0
          Store(hfv, d, row_hf + x);
467
0
        }
468
0
      }
469
0
    }
470
0
  }
471
  // Suppress red-green by intensity change in the high freq channels.
472
0
  JXL_RETURN_IF_ERROR(SuppressXByY(hf[1], &hf[0]));
473
0
  return true;
474
0
}
475
476
Status SeparateHFAndUHF(const ButteraugliParams& params, ImageF* hf,
477
0
                        ImageF* uhf, BlurTemp* blur_temp) {
478
0
  const HWY_FULL(float) d;
479
0
  const size_t xsize = hf[0].xsize();
480
0
  const size_t ysize = hf[0].ysize();
481
0
  JxlMemoryManager* memory_manager = hf[0].memory_manager();
482
0
  static const double kSigmaUhf = 1.56416327805;
483
0
  JXL_ASSIGN_OR_RETURN(uhf[0], ImageF::Create(memory_manager, xsize, ysize));
484
0
  JXL_ASSIGN_OR_RETURN(uhf[1], ImageF::Create(memory_manager, xsize, ysize));
485
0
  for (int i = 0; i < 2; ++i) {
486
    // Divide hf into hf and uhf.
487
0
    for (size_t y = 0; y < ysize; ++y) {
488
0
      float* BUTTERAUGLI_RESTRICT row_uhf = uhf[i].Row(y);
489
0
      float* BUTTERAUGLI_RESTRICT row_hf = hf[i].Row(y);
490
0
      for (size_t x = 0; x < xsize; ++x) {
491
0
        row_uhf[x] = row_hf[x];
492
0
      }
493
0
    }
494
0
    JXL_RETURN_IF_ERROR(Blur(hf[i], kSigmaUhf, params, blur_temp, &hf[i]));
495
0
    static const double kRemoveHfRange = 1.5;
496
0
    static const double kAddHfRange = 0.132;
497
0
    static const double kRemoveUhfRange = 0.04;
498
0
    static const double kMaxclampHf = 28.4691806922;
499
0
    static const double kMaxclampUhf = 5.19175294647;
500
0
    static double kMulYHf = 2.155;
501
0
    static double kMulYUhf = 2.69313763794;
502
0
    if (i == 0) {
503
0
      for (size_t y = 0; y < ysize; ++y) {
504
0
        float* BUTTERAUGLI_RESTRICT row_uhf = uhf[0].Row(y);
505
0
        float* BUTTERAUGLI_RESTRICT row_hf = hf[0].Row(y);
506
0
        for (size_t x = 0; x < xsize; x += Lanes(d)) {
507
0
          auto hfv = Load(d, row_hf + x);
508
0
          auto uhfv = Sub(Load(d, row_uhf + x), hfv);
509
0
          hfv = RemoveRangeAroundZero(d, kRemoveHfRange, hfv);
510
0
          uhfv = RemoveRangeAroundZero(d, kRemoveUhfRange, uhfv);
511
0
          Store(hfv, d, row_hf + x);
512
0
          Store(uhfv, d, row_uhf + x);
513
0
        }
514
0
      }
515
0
    } else {
516
0
      for (size_t y = 0; y < ysize; ++y) {
517
0
        float* BUTTERAUGLI_RESTRICT row_uhf = uhf[1].Row(y);
518
0
        float* BUTTERAUGLI_RESTRICT row_hf = hf[1].Row(y);
519
0
        for (size_t x = 0; x < xsize; x += Lanes(d)) {
520
0
          auto hfv = Load(d, row_hf + x);
521
0
          hfv = MaximumClamp(d, hfv, kMaxclampHf);
522
523
0
          auto uhfv = Sub(Load(d, row_uhf + x), hfv);
524
0
          uhfv = MaximumClamp(d, uhfv, kMaxclampUhf);
525
0
          uhfv = Mul(uhfv, Set(d, kMulYUhf));
526
0
          Store(uhfv, d, row_uhf + x);
527
528
0
          hfv = Mul(hfv, Set(d, kMulYHf));
529
0
          hfv = AmplifyRangeAroundZero(d, kAddHfRange, hfv);
530
0
          Store(hfv, d, row_hf + x);
531
0
        }
532
0
      }
533
0
    }
534
0
  }
535
0
  return true;
536
0
}
537
538
0
void DeallocateHFAndUHF(ImageF* hf, ImageF* uhf) {
539
0
  for (int i = 0; i < 2; ++i) {
540
0
    hf[i] = ImageF();
541
0
    uhf[i] = ImageF();
542
0
  }
543
0
}
544
545
Status SeparateFrequencies(size_t xsize, size_t ysize,
546
                           const ButteraugliParams& params, BlurTemp* blur_temp,
547
0
                           const Image3F& xyb, PsychoImage& ps) {
548
0
  JxlMemoryManager* memory_manager = xyb.memory_manager();
549
0
  JXL_ASSIGN_OR_RETURN(
550
0
      ps.lf, Image3F::Create(memory_manager, xyb.xsize(), xyb.ysize()));
551
0
  JXL_ASSIGN_OR_RETURN(
552
0
      ps.mf, Image3F::Create(memory_manager, xyb.xsize(), xyb.ysize()));
553
0
  JXL_RETURN_IF_ERROR(SeparateLFAndMF(params, xyb, &ps.lf, &ps.mf, blur_temp));
554
0
  JXL_RETURN_IF_ERROR(SeparateMFAndHF(params, &ps.mf, &ps.hf[0], blur_temp));
555
0
  JXL_RETURN_IF_ERROR(
556
0
      SeparateHFAndUHF(params, &ps.hf[0], &ps.uhf[0], blur_temp));
557
0
  return true;
558
0
}
559
560
namespace {
561
template <typename V>
562
0
BUTTERAUGLI_INLINE V Sum(V a, V b, V c, V d) {
563
0
  return Add(Add(a, b), Add(c, d));
564
0
}
565
template <typename V>
566
0
BUTTERAUGLI_INLINE V Sum(V a, V b, V c, V d, V e) {
567
0
  return Sum(a, b, c, Add(d, e));
568
0
}
569
template <typename V>
570
0
BUTTERAUGLI_INLINE V Sum(V a, V b, V c, V d, V e, V f, V g) {
571
0
  return Sum(a, b, c, Sum(d, e, f, g));
572
0
}
573
template <typename V>
574
0
BUTTERAUGLI_INLINE V Sum(V a, V b, V c, V d, V e, V f, V g, V h, V i) {
575
0
  return Add(Add(Sum(a, b, c, d), Sum(e, f, g, h)), i);
576
0
}
577
}  // namespace
578
579
template <class D>
580
Vec<D> MaltaUnit(MaltaTagLF /*tag*/, const D df,
581
0
                 const float* BUTTERAUGLI_RESTRICT d, const ptrdiff_t xs) {
582
0
  const ptrdiff_t xs3 = 3 * xs;
583
584
0
  const auto center = LoadU(df, d);
585
586
  // x grows, y constant
587
0
  const auto sum_yconst = Sum(LoadU(df, d - 4), LoadU(df, d - 2), center,
588
0
                              LoadU(df, d + 2), LoadU(df, d + 4));
589
  // Will return this, sum of all line kernels
590
0
  auto retval = Mul(sum_yconst, sum_yconst);
591
0
  {
592
    // y grows, x constant
593
0
    auto sum = Sum(LoadU(df, d - xs3 - xs), LoadU(df, d - xs - xs), center,
594
0
                   LoadU(df, d + xs + xs), LoadU(df, d + xs3 + xs));
595
0
    retval = MulAdd(sum, sum, retval);
596
0
  }
597
0
  {
598
    // both grow
599
0
    auto sum = Sum(LoadU(df, d - xs3 - 3), LoadU(df, d - xs - xs - 2), center,
600
0
                   LoadU(df, d + xs + xs + 2), LoadU(df, d + xs3 + 3));
601
0
    retval = MulAdd(sum, sum, retval);
602
0
  }
603
0
  {
604
    // y grows, x shrinks
605
0
    auto sum = Sum(LoadU(df, d - xs3 + 3), LoadU(df, d - xs - xs + 2), center,
606
0
                   LoadU(df, d + xs + xs - 2), LoadU(df, d + xs3 - 3));
607
0
    retval = MulAdd(sum, sum, retval);
608
0
  }
609
0
  {
610
    // y grows -4 to 4, x shrinks 1 -> -1
611
0
    auto sum =
612
0
        Sum(LoadU(df, d - xs3 - xs + 1), LoadU(df, d - xs - xs + 1), center,
613
0
            LoadU(df, d + xs + xs - 1), LoadU(df, d + xs3 + xs - 1));
614
0
    retval = MulAdd(sum, sum, retval);
615
0
  }
616
0
  {
617
    //  y grows -4 to 4, x grows -1 -> 1
618
0
    auto sum =
619
0
        Sum(LoadU(df, d - xs3 - xs - 1), LoadU(df, d - xs - xs - 1), center,
620
0
            LoadU(df, d + xs + xs + 1), LoadU(df, d + xs3 + xs + 1));
621
0
    retval = MulAdd(sum, sum, retval);
622
0
  }
623
0
  {
624
    // x grows -4 to 4, y grows -1 to 1
625
0
    auto sum = Sum(LoadU(df, d - 4 - xs), LoadU(df, d - 2 - xs), center,
626
0
                   LoadU(df, d + 2 + xs), LoadU(df, d + 4 + xs));
627
0
    retval = MulAdd(sum, sum, retval);
628
0
  }
629
0
  {
630
    // x grows -4 to 4, y shrinks 1 to -1
631
0
    auto sum = Sum(LoadU(df, d - 4 + xs), LoadU(df, d - 2 + xs), center,
632
0
                   LoadU(df, d + 2 - xs), LoadU(df, d + 4 - xs));
633
0
    retval = MulAdd(sum, sum, retval);
634
0
  }
635
0
  {
636
    /* 0_________
637
       1__*______
638
       2___*_____
639
       3_________
640
       4____0____
641
       5_________
642
       6_____*___
643
       7______*__
644
       8_________ */
645
0
    auto sum = Sum(LoadU(df, d - xs3 - 2), LoadU(df, d - xs - xs - 1), center,
646
0
                   LoadU(df, d + xs + xs + 1), LoadU(df, d + xs3 + 2));
647
0
    retval = MulAdd(sum, sum, retval);
648
0
  }
649
0
  {
650
    /* 0_________
651
       1______*__
652
       2_____*___
653
       3_________
654
       4____0____
655
       5_________
656
       6___*_____
657
       7__*______
658
       8_________ */
659
0
    auto sum = Sum(LoadU(df, d - xs3 + 2), LoadU(df, d - xs - xs + 1), center,
660
0
                   LoadU(df, d + xs + xs - 1), LoadU(df, d + xs3 - 2));
661
0
    retval = MulAdd(sum, sum, retval);
662
0
  }
663
0
  {
664
    /* 0_________
665
       1_________
666
       2_*_______
667
       3__*______
668
       4____0____
669
       5______*__
670
       6_______*_
671
       7_________
672
       8_________ */
673
0
    auto sum = Sum(LoadU(df, d - xs - xs - 3), LoadU(df, d - xs - 2), center,
674
0
                   LoadU(df, d + xs + 2), LoadU(df, d + xs + xs + 3));
675
0
    retval = MulAdd(sum, sum, retval);
676
0
  }
677
0
  {
678
    /* 0_________
679
       1_________
680
       2_______*_
681
       3______*__
682
       4____0____
683
       5__*______
684
       6_*_______
685
       7_________
686
       8_________ */
687
0
    auto sum = Sum(LoadU(df, d - xs - xs + 3), LoadU(df, d - xs + 2), center,
688
0
                   LoadU(df, d + xs - 2), LoadU(df, d + xs + xs - 3));
689
0
    retval = MulAdd(sum, sum, retval);
690
0
  }
691
0
  {
692
    /* 0_________
693
       1_________
694
       2________*
695
       3______*__
696
       4____0____
697
       5__*______
698
       6*________
699
       7_________
700
       8_________ */
701
702
0
    auto sum = Sum(LoadU(df, d + xs + xs - 4), LoadU(df, d + xs - 2), center,
703
0
                   LoadU(df, d - xs + 2), LoadU(df, d - xs - xs + 4));
704
0
    retval = MulAdd(sum, sum, retval);
705
0
  }
706
0
  {
707
    /* 0_________
708
       1_________
709
       2*________
710
       3__*______
711
       4____0____
712
       5______*__
713
       6________*
714
       7_________
715
       8_________ */
716
0
    auto sum = Sum(LoadU(df, d - xs - xs - 4), LoadU(df, d - xs - 2), center,
717
0
                   LoadU(df, d + xs + 2), LoadU(df, d + xs + xs + 4));
718
0
    retval = MulAdd(sum, sum, retval);
719
0
  }
720
0
  {
721
    /* 0__*______
722
       1_________
723
       2___*_____
724
       3_________
725
       4____0____
726
       5_________
727
       6_____*___
728
       7_________
729
       8______*__ */
730
0
    auto sum =
731
0
        Sum(LoadU(df, d - xs3 - xs - 2), LoadU(df, d - xs - xs - 1), center,
732
0
            LoadU(df, d + xs + xs + 1), LoadU(df, d + xs3 + xs + 2));
733
0
    retval = MulAdd(sum, sum, retval);
734
0
  }
735
0
  {
736
    /* 0______*__
737
       1_________
738
       2_____*___
739
       3_________
740
       4____0____
741
       5_________
742
       6___*_____
743
       7_________
744
       8__*______ */
745
0
    auto sum =
746
0
        Sum(LoadU(df, d - xs3 - xs + 2), LoadU(df, d - xs - xs + 1), center,
747
0
            LoadU(df, d + xs + xs - 1), LoadU(df, d + xs3 + xs - 2));
748
0
    retval = MulAdd(sum, sum, retval);
749
0
  }
750
0
  return retval;
751
0
}
752
753
template <class D>
754
Vec<D> MaltaUnit(MaltaTag /*tag*/, const D df,
755
0
                 const float* BUTTERAUGLI_RESTRICT d, const ptrdiff_t xs) {
756
0
  const ptrdiff_t xs3 = 3 * xs;
757
758
0
  const auto center = LoadU(df, d);
759
760
  // x grows, y constant
761
0
  const auto sum_yconst =
762
0
      Sum(LoadU(df, d - 4), LoadU(df, d - 3), LoadU(df, d - 2),
763
0
          LoadU(df, d - 1), center, LoadU(df, d + 1), LoadU(df, d + 2),
764
0
          LoadU(df, d + 3), LoadU(df, d + 4));
765
  // Will return this, sum of all line kernels
766
0
  auto retval = Mul(sum_yconst, sum_yconst);
767
768
0
  {
769
    // y grows, x constant
770
0
    auto sum = Sum(LoadU(df, d - xs3 - xs), LoadU(df, d - xs3),
771
0
                   LoadU(df, d - xs - xs), LoadU(df, d - xs), center,
772
0
                   LoadU(df, d + xs), LoadU(df, d + xs + xs),
773
0
                   LoadU(df, d + xs3), LoadU(df, d + xs3 + xs));
774
0
    retval = MulAdd(sum, sum, retval);
775
0
  }
776
0
  {
777
    // both grow
778
0
    auto sum = Sum(LoadU(df, d - xs3 - 3), LoadU(df, d - xs - xs - 2),
779
0
                   LoadU(df, d - xs - 1), center, LoadU(df, d + xs + 1),
780
0
                   LoadU(df, d + xs + xs + 2), LoadU(df, d + xs3 + 3));
781
0
    retval = MulAdd(sum, sum, retval);
782
0
  }
783
0
  {
784
    // y grows, x shrinks
785
0
    auto sum = Sum(LoadU(df, d - xs3 + 3), LoadU(df, d - xs - xs + 2),
786
0
                   LoadU(df, d - xs + 1), center, LoadU(df, d + xs - 1),
787
0
                   LoadU(df, d + xs + xs - 2), LoadU(df, d + xs3 - 3));
788
0
    retval = MulAdd(sum, sum, retval);
789
0
  }
790
0
  {
791
    // y grows -4 to 4, x shrinks 1 -> -1
792
0
    auto sum = Sum(LoadU(df, d - xs3 - xs + 1), LoadU(df, d - xs3 + 1),
793
0
                   LoadU(df, d - xs - xs + 1), LoadU(df, d - xs), center,
794
0
                   LoadU(df, d + xs), LoadU(df, d + xs + xs - 1),
795
0
                   LoadU(df, d + xs3 - 1), LoadU(df, d + xs3 + xs - 1));
796
0
    retval = MulAdd(sum, sum, retval);
797
0
  }
798
0
  {
799
    //  y grows -4 to 4, x grows -1 -> 1
800
0
    auto sum = Sum(LoadU(df, d - xs3 - xs - 1), LoadU(df, d - xs3 - 1),
801
0
                   LoadU(df, d - xs - xs - 1), LoadU(df, d - xs), center,
802
0
                   LoadU(df, d + xs), LoadU(df, d + xs + xs + 1),
803
0
                   LoadU(df, d + xs3 + 1), LoadU(df, d + xs3 + xs + 1));
804
0
    retval = MulAdd(sum, sum, retval);
805
0
  }
806
0
  {
807
    // x grows -4 to 4, y grows -1 to 1
808
0
    auto sum =
809
0
        Sum(LoadU(df, d - 4 - xs), LoadU(df, d - 3 - xs), LoadU(df, d - 2 - xs),
810
0
            LoadU(df, d - 1), center, LoadU(df, d + 1), LoadU(df, d + 2 + xs),
811
0
            LoadU(df, d + 3 + xs), LoadU(df, d + 4 + xs));
812
0
    retval = MulAdd(sum, sum, retval);
813
0
  }
814
0
  {
815
    // x grows -4 to 4, y shrinks 1 to -1
816
0
    auto sum =
817
0
        Sum(LoadU(df, d - 4 + xs), LoadU(df, d - 3 + xs), LoadU(df, d - 2 + xs),
818
0
            LoadU(df, d - 1), center, LoadU(df, d + 1), LoadU(df, d + 2 - xs),
819
0
            LoadU(df, d + 3 - xs), LoadU(df, d + 4 - xs));
820
0
    retval = MulAdd(sum, sum, retval);
821
0
  }
822
0
  {
823
    /* 0_________
824
       1__*______
825
       2___*_____
826
       3___*_____
827
       4____0____
828
       5_____*___
829
       6_____*___
830
       7______*__
831
       8_________ */
832
0
    auto sum = Sum(LoadU(df, d - xs3 - 2), LoadU(df, d - xs - xs - 1),
833
0
                   LoadU(df, d - xs - 1), center, LoadU(df, d + xs + 1),
834
0
                   LoadU(df, d + xs + xs + 1), LoadU(df, d + xs3 + 2));
835
0
    retval = MulAdd(sum, sum, retval);
836
0
  }
837
0
  {
838
    /* 0_________
839
       1______*__
840
       2_____*___
841
       3_____*___
842
       4____0____
843
       5___*_____
844
       6___*_____
845
       7__*______
846
       8_________ */
847
0
    auto sum = Sum(LoadU(df, d - xs3 + 2), LoadU(df, d - xs - xs + 1),
848
0
                   LoadU(df, d - xs + 1), center, LoadU(df, d + xs - 1),
849
0
                   LoadU(df, d + xs + xs - 1), LoadU(df, d + xs3 - 2));
850
0
    retval = MulAdd(sum, sum, retval);
851
0
  }
852
0
  {
853
    /* 0_________
854
       1_________
855
       2_*_______
856
       3__**_____
857
       4____0____
858
       5_____**__
859
       6_______*_
860
       7_________
861
       8_________ */
862
0
    auto sum = Sum(LoadU(df, d - xs - xs - 3), LoadU(df, d - xs - 2),
863
0
                   LoadU(df, d - xs - 1), center, LoadU(df, d + xs + 1),
864
0
                   LoadU(df, d + xs + 2), LoadU(df, d + xs + xs + 3));
865
0
    retval = MulAdd(sum, sum, retval);
866
0
  }
867
0
  {
868
    /* 0_________
869
       1_________
870
       2_______*_
871
       3_____**__
872
       4____0____
873
       5__**_____
874
       6_*_______
875
       7_________
876
       8_________ */
877
0
    auto sum = Sum(LoadU(df, d - xs - xs + 3), LoadU(df, d - xs + 2),
878
0
                   LoadU(df, d - xs + 1), center, LoadU(df, d + xs - 1),
879
0
                   LoadU(df, d + xs - 2), LoadU(df, d + xs + xs - 3));
880
0
    retval = MulAdd(sum, sum, retval);
881
0
  }
882
0
  {
883
    /* 0_________
884
       1_________
885
       2_________
886
       3______***
887
       4___*0*___
888
       5***______
889
       6_________
890
       7_________
891
       8_________ */
892
893
0
    auto sum =
894
0
        Sum(LoadU(df, d + xs - 4), LoadU(df, d + xs - 3), LoadU(df, d + xs - 2),
895
0
            LoadU(df, d - 1), center, LoadU(df, d + 1), LoadU(df, d - xs + 2),
896
0
            LoadU(df, d - xs + 3), LoadU(df, d - xs + 4));
897
0
    retval = MulAdd(sum, sum, retval);
898
0
  }
899
0
  {
900
    /* 0_________
901
       1_________
902
       2_________
903
       3***______
904
       4___*0*___
905
       5______***
906
       6_________
907
       7_________
908
       8_________ */
909
0
    auto sum =
910
0
        Sum(LoadU(df, d - xs - 4), LoadU(df, d - xs - 3), LoadU(df, d - xs - 2),
911
0
            LoadU(df, d - 1), center, LoadU(df, d + 1), LoadU(df, d + xs + 2),
912
0
            LoadU(df, d + xs + 3), LoadU(df, d + xs + 4));
913
0
    retval = MulAdd(sum, sum, retval);
914
0
  }
915
0
  {
916
    /* 0___*_____
917
       1___*_____
918
       2___*_____
919
       3____*____
920
       4____0____
921
       5____*____
922
       6_____*___
923
       7_____*___
924
       8_____*___ */
925
0
    auto sum = Sum(LoadU(df, d - xs3 - xs - 1), LoadU(df, d - xs3 - 1),
926
0
                   LoadU(df, d - xs - xs - 1), LoadU(df, d - xs), center,
927
0
                   LoadU(df, d + xs), LoadU(df, d + xs + xs + 1),
928
0
                   LoadU(df, d + xs3 + 1), LoadU(df, d + xs3 + xs + 1));
929
0
    retval = MulAdd(sum, sum, retval);
930
0
  }
931
0
  {
932
    /* 0_____*___
933
       1_____*___
934
       2____ *___
935
       3____*____
936
       4____0____
937
       5____*____
938
       6___*_____
939
       7___*_____
940
       8___*_____ */
941
0
    auto sum = Sum(LoadU(df, d - xs3 - xs + 1), LoadU(df, d - xs3 + 1),
942
0
                   LoadU(df, d - xs - xs + 1), LoadU(df, d - xs), center,
943
0
                   LoadU(df, d + xs), LoadU(df, d + xs + xs - 1),
944
0
                   LoadU(df, d + xs3 - 1), LoadU(df, d + xs3 + xs - 1));
945
0
    retval = MulAdd(sum, sum, retval);
946
0
  }
947
0
  return retval;
948
0
}
949
950
// Returns MaltaUnit. Avoids bounds-checks when x0 and y0 are known
951
// to be far enough from the image borders. "diffs" is a packed image.
952
template <class Tag>
953
static BUTTERAUGLI_INLINE float PaddedMaltaUnit(const ImageF& diffs,
954
                                                const size_t x0,
955
0
                                                const size_t y0) {
956
0
  const float* BUTTERAUGLI_RESTRICT d = diffs.ConstRow(y0) + x0;
957
0
  const HWY_CAPPED(float, 1) df;
958
0
  if ((x0 >= 4 && y0 >= 4 && x0 < (diffs.xsize() - 4) &&
959
0
       y0 < (diffs.ysize() - 4))) {
960
0
    return GetLane(MaltaUnit(Tag(), df, d, diffs.PixelsPerRow()));
961
0
  }
962
963
0
  float borderimage[12 * 9];  // round up to 4
964
0
  for (int dy = 0; dy < 9; ++dy) {
965
0
    int y = y0 + dy - 4;
966
0
    if (y < 0 || static_cast<size_t>(y) >= diffs.ysize()) {
967
0
      for (int dx = 0; dx < 12; ++dx) {
968
0
        borderimage[dy * 12 + dx] = 0.0f;
969
0
      }
970
0
      continue;
971
0
    }
972
973
0
    const float* row_diffs = diffs.ConstRow(y);
974
0
    for (int dx = 0; dx < 9; ++dx) {
975
0
      int x = x0 + dx - 4;
976
0
      if (x < 0 || static_cast<size_t>(x) >= diffs.xsize()) {
977
0
        borderimage[dy * 12 + dx] = 0.0f;
978
0
      } else {
979
0
        borderimage[dy * 12 + dx] = row_diffs[x];
980
0
      }
981
0
    }
982
0
    std::fill(borderimage + dy * 12 + 9, borderimage + dy * 12 + 12, 0.0f);
983
0
  }
984
0
  return GetLane(MaltaUnit(Tag(), df, &borderimage[4 * 12 + 4], 12));
985
0
}
Unexecuted instantiation: butteraugli.cc:float jxl::N_SCALAR::PaddedMaltaUnit<jxl::MaltaTag>(jxl::Plane<float> const&, unsigned long, unsigned long)
Unexecuted instantiation: butteraugli.cc:float jxl::N_SCALAR::PaddedMaltaUnit<jxl::MaltaTagLF>(jxl::Plane<float> const&, unsigned long, unsigned long)
986
987
template <class Tag>
988
static Status MaltaDiffMapT(const Tag tag, const ImageF& lum0,
989
                            const ImageF& lum1, const double w_0gt1,
990
                            const double w_0lt1, const double norm1,
991
                            const double len, const double mulli,
992
                            ImageF* HWY_RESTRICT diffs,
993
0
                            ImageF* HWY_RESTRICT block_diff_ac) {
994
0
  JXL_ENSURE(SameSize(lum0, lum1) && SameSize(lum0, *diffs));
995
0
  const size_t xsize_ = lum0.xsize();
996
0
  const size_t ysize_ = lum0.ysize();
997
998
0
  const float kWeight0 = 0.5;
999
0
  const float kWeight1 = 0.33;
1000
1001
0
  const double w_pre0gt1 = mulli * std::sqrt(kWeight0 * w_0gt1) / (len * 2 + 1);
1002
0
  const double w_pre0lt1 = mulli * std::sqrt(kWeight1 * w_0lt1) / (len * 2 + 1);
1003
0
  const float norm2_0gt1 = w_pre0gt1 * norm1;
1004
0
  const float norm2_0lt1 = w_pre0lt1 * norm1;
1005
1006
0
  for (size_t y = 0; y < ysize_; ++y) {
1007
0
    const float* HWY_RESTRICT row0 = lum0.ConstRow(y);
1008
0
    const float* HWY_RESTRICT row1 = lum1.ConstRow(y);
1009
0
    float* HWY_RESTRICT row_diffs = diffs->Row(y);
1010
0
    for (size_t x = 0; x < xsize_; ++x) {
1011
0
      const float absval = 0.5f * (std::abs(row0[x]) + std::abs(row1[x]));
1012
0
      const float diff = row0[x] - row1[x];
1013
0
      const float scaler = norm2_0gt1 / (static_cast<float>(norm1) + absval);
1014
1015
      // Primary symmetric quadratic objective.
1016
0
      row_diffs[x] = scaler * diff;
1017
1018
0
      const float scaler2 = norm2_0lt1 / (static_cast<float>(norm1) + absval);
1019
0
      const double fabs0 = std::fabs(row0[x]);
1020
1021
      // Secondary half-open quadratic objectives.
1022
0
      const double too_small = 0.55 * fabs0;
1023
0
      const double too_big = 1.05 * fabs0;
1024
1025
0
      if (row0[x] < 0) {
1026
0
        if (row1[x] > -too_small) {
1027
0
          double impact = scaler2 * (row1[x] + too_small);
1028
0
          row_diffs[x] -= impact;
1029
0
        } else if (row1[x] < -too_big) {
1030
0
          double impact = scaler2 * (-row1[x] - too_big);
1031
0
          row_diffs[x] += impact;
1032
0
        }
1033
0
      } else {
1034
0
        if (row1[x] < too_small) {
1035
0
          double impact = scaler2 * (too_small - row1[x]);
1036
0
          row_diffs[x] += impact;
1037
0
        } else if (row1[x] > too_big) {
1038
0
          double impact = scaler2 * (row1[x] - too_big);
1039
0
          row_diffs[x] -= impact;
1040
0
        }
1041
0
      }
1042
0
    }
1043
0
  }
1044
1045
0
  size_t y0 = 0;
1046
  // Top
1047
0
  for (; y0 < 4; ++y0) {
1048
0
    float* BUTTERAUGLI_RESTRICT row_diff = block_diff_ac->Row(y0);
1049
0
    for (size_t x0 = 0; x0 < xsize_; ++x0) {
1050
0
      row_diff[x0] += PaddedMaltaUnit<Tag>(*diffs, x0, y0);
1051
0
    }
1052
0
  }
1053
1054
0
  const HWY_FULL(float) df;
1055
0
  const size_t aligned_x = std::max(static_cast<size_t>(4), Lanes(df));
1056
0
  const ptrdiff_t stride = diffs->PixelsPerRow();
1057
1058
  // Middle
1059
0
  for (; y0 < ysize_ - 4; ++y0) {
1060
0
    const float* BUTTERAUGLI_RESTRICT row_in = diffs->ConstRow(y0);
1061
0
    float* BUTTERAUGLI_RESTRICT row_diff = block_diff_ac->Row(y0);
1062
0
    size_t x0 = 0;
1063
0
    for (; x0 < aligned_x; ++x0) {
1064
0
      row_diff[x0] += PaddedMaltaUnit<Tag>(*diffs, x0, y0);
1065
0
    }
1066
0
    for (; x0 + Lanes(df) + 4 <= xsize_; x0 += Lanes(df)) {
1067
0
      auto diff = Load(df, row_diff + x0);
1068
0
      diff = Add(diff, MaltaUnit(Tag(), df, row_in + x0, stride));
1069
0
      Store(diff, df, row_diff + x0);
1070
0
    }
1071
1072
0
    for (; x0 < xsize_; ++x0) {
1073
0
      row_diff[x0] += PaddedMaltaUnit<Tag>(*diffs, x0, y0);
1074
0
    }
1075
0
  }
1076
1077
  // Bottom
1078
0
  for (; y0 < ysize_; ++y0) {
1079
0
    float* BUTTERAUGLI_RESTRICT row_diff = block_diff_ac->Row(y0);
1080
0
    for (size_t x0 = 0; x0 < xsize_; ++x0) {
1081
0
      row_diff[x0] += PaddedMaltaUnit<Tag>(*diffs, x0, y0);
1082
0
    }
1083
0
  }
1084
0
  return true;
1085
0
}
Unexecuted instantiation: butteraugli.cc:jxl::Status jxl::N_SCALAR::MaltaDiffMapT<jxl::MaltaTag>(jxl::MaltaTag, jxl::Plane<float> const&, jxl::Plane<float> const&, double, double, double, double, double, jxl::Plane<float>*, jxl::Plane<float>*)
Unexecuted instantiation: butteraugli.cc:jxl::Status jxl::N_SCALAR::MaltaDiffMapT<jxl::MaltaTagLF>(jxl::MaltaTagLF, jxl::Plane<float> const&, jxl::Plane<float> const&, double, double, double, double, double, jxl::Plane<float>*, jxl::Plane<float>*)
1086
1087
// Need non-template wrapper functions for HWY_EXPORT.
1088
Status MaltaDiffMap(const ImageF& lum0, const ImageF& lum1, const double w_0gt1,
1089
                    const double w_0lt1, const double norm1,
1090
                    ImageF* HWY_RESTRICT diffs,
1091
0
                    ImageF* HWY_RESTRICT block_diff_ac) {
1092
0
  const double len = 3.75;
1093
0
  static const double mulli = 0.39905817637;
1094
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapT(MaltaTag(), lum0, lum1, w_0gt1, w_0lt1,
1095
0
                                    norm1, len, mulli, diffs, block_diff_ac));
1096
0
  return true;
1097
0
}
1098
1099
Status MaltaDiffMapLF(const ImageF& lum0, const ImageF& lum1,
1100
                      const double w_0gt1, const double w_0lt1,
1101
                      const double norm1, ImageF* HWY_RESTRICT diffs,
1102
0
                      ImageF* HWY_RESTRICT block_diff_ac) {
1103
0
  const double len = 3.75;
1104
0
  static const double mulli = 0.611612573796;
1105
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapT(MaltaTagLF(), lum0, lum1, w_0gt1, w_0lt1,
1106
0
                                    norm1, len, mulli, diffs, block_diff_ac));
1107
0
  return true;
1108
0
}
1109
1110
void CombineChannelsForMasking(const ImageF* hf, const ImageF* uhf,
1111
0
                               ImageF* out) {
1112
  // Only X and Y components are involved in masking. B's influence
1113
  // is considered less important in the high frequency area, and we
1114
  // don't model masking from lower frequency signals.
1115
0
  static const float muls[3] = {
1116
0
      2.5f,
1117
0
      0.4f,
1118
0
      0.4f,
1119
0
  };
1120
  // Silly and unoptimized approach here. TODO(jyrki): rework this.
1121
0
  for (size_t y = 0; y < hf[0].ysize(); ++y) {
1122
0
    const float* BUTTERAUGLI_RESTRICT row_y_hf = hf[1].Row(y);
1123
0
    const float* BUTTERAUGLI_RESTRICT row_y_uhf = uhf[1].Row(y);
1124
0
    const float* BUTTERAUGLI_RESTRICT row_x_hf = hf[0].Row(y);
1125
0
    const float* BUTTERAUGLI_RESTRICT row_x_uhf = uhf[0].Row(y);
1126
0
    float* BUTTERAUGLI_RESTRICT row = out->Row(y);
1127
0
    for (size_t x = 0; x < hf[0].xsize(); ++x) {
1128
0
      float xdiff = (row_x_uhf[x] + row_x_hf[x]) * muls[0];
1129
0
      float ydiff = row_y_uhf[x] * muls[1] + row_y_hf[x] * muls[2];
1130
0
      row[x] = xdiff * xdiff + ydiff * ydiff;
1131
0
      row[x] = std::sqrt(row[x]);
1132
0
    }
1133
0
  }
1134
0
}
1135
1136
0
void DiffPrecompute(const ImageF& xyb, float mul, float bias_arg, ImageF* out) {
1137
0
  const size_t xsize = xyb.xsize();
1138
0
  const size_t ysize = xyb.ysize();
1139
0
  const float bias = mul * bias_arg;
1140
0
  const float sqrt_bias = std::sqrt(bias);
1141
0
  for (size_t y = 0; y < ysize; ++y) {
1142
0
    const float* BUTTERAUGLI_RESTRICT row_in = xyb.Row(y);
1143
0
    float* BUTTERAUGLI_RESTRICT row_out = out->Row(y);
1144
0
    for (size_t x = 0; x < xsize; ++x) {
1145
      // kBias makes sqrt behave more linearly.
1146
0
      row_out[x] = std::sqrt(mul * std::abs(row_in[x]) + bias) - sqrt_bias;
1147
0
    }
1148
0
  }
1149
0
}
1150
1151
// std::log(80.0) / std::log(255.0);
1152
constexpr float kIntensityTargetNormalizationHack = 0.79079917404f;
1153
static const float kInternalGoodQualityThreshold =
1154
    17.83f * kIntensityTargetNormalizationHack;
1155
static const float kGlobalScale = 1.0 / kInternalGoodQualityThreshold;
1156
1157
0
void StoreMin3(const float v, float& min0, float& min1, float& min2) {
1158
0
  if (v < min2) {
1159
0
    if (v < min0) {
1160
0
      min2 = min1;
1161
0
      min1 = min0;
1162
0
      min0 = v;
1163
0
    } else if (v < min1) {
1164
0
      min2 = min1;
1165
0
      min1 = v;
1166
0
    } else {
1167
0
      min2 = v;
1168
0
    }
1169
0
  }
1170
0
}
1171
1172
// Look for smooth areas near the area of degradation.
1173
// If the areas area generally smooth, don't do masking.
1174
0
void FuzzyErosion(const ImageF& from, ImageF* to) {
1175
0
  const size_t xsize = from.xsize();
1176
0
  const size_t ysize = from.ysize();
1177
0
  static const int kStep = 3;
1178
0
  for (size_t y = 0; y < ysize; ++y) {
1179
0
    for (size_t x = 0; x < xsize; ++x) {
1180
0
      float min0 = from.Row(y)[x];
1181
0
      float min1 = 2 * min0;
1182
0
      float min2 = min1;
1183
0
      if (x >= kStep) {
1184
0
        StoreMin3(from.Row(y)[x - kStep], min0, min1, min2);
1185
0
        if (y >= kStep) {
1186
0
          StoreMin3(from.Row(y - kStep)[x - kStep], min0, min1, min2);
1187
0
        }
1188
0
        if (y < ysize - kStep) {
1189
0
          StoreMin3(from.Row(y + kStep)[x - kStep], min0, min1, min2);
1190
0
        }
1191
0
      }
1192
0
      if (x < xsize - kStep) {
1193
0
        StoreMin3(from.Row(y)[x + kStep], min0, min1, min2);
1194
0
        if (y >= kStep) {
1195
0
          StoreMin3(from.Row(y - kStep)[x + kStep], min0, min1, min2);
1196
0
        }
1197
0
        if (y < ysize - kStep) {
1198
0
          StoreMin3(from.Row(y + kStep)[x + kStep], min0, min1, min2);
1199
0
        }
1200
0
      }
1201
0
      if (y >= kStep) {
1202
0
        StoreMin3(from.Row(y - kStep)[x], min0, min1, min2);
1203
0
      }
1204
0
      if (y < ysize - kStep) {
1205
0
        StoreMin3(from.Row(y + kStep)[x], min0, min1, min2);
1206
0
      }
1207
0
      to->Row(y)[x] = (0.45f * min0 + 0.3f * min1 + 0.25f * min2);
1208
0
    }
1209
0
  }
1210
0
}
1211
1212
// Compute values of local frequency and dc masking based on the activity
1213
// in the two images. img_diff_ac may be null.
1214
Status Mask(const ImageF& mask0, const ImageF& mask1,
1215
            const ButteraugliParams& params, BlurTemp* blur_temp,
1216
            ImageF* BUTTERAUGLI_RESTRICT mask,
1217
0
            ImageF* BUTTERAUGLI_RESTRICT diff_ac) {
1218
0
  const size_t xsize = mask0.xsize();
1219
0
  const size_t ysize = mask0.ysize();
1220
0
  JxlMemoryManager* memory_manager = mask0.memory_manager();
1221
0
  JXL_ASSIGN_OR_RETURN(*mask, ImageF::Create(memory_manager, xsize, ysize));
1222
0
  static const float kMul = 6.19424080439;
1223
0
  static const float kBias = 12.61050594197;
1224
0
  static const float kRadius = 2.7;
1225
0
  JXL_ASSIGN_OR_RETURN(ImageF diff0,
1226
0
                       ImageF::Create(memory_manager, xsize, ysize));
1227
0
  JXL_ASSIGN_OR_RETURN(ImageF diff1,
1228
0
                       ImageF::Create(memory_manager, xsize, ysize));
1229
0
  JXL_ASSIGN_OR_RETURN(ImageF blurred0,
1230
0
                       ImageF::Create(memory_manager, xsize, ysize));
1231
0
  JXL_ASSIGN_OR_RETURN(ImageF blurred1,
1232
0
                       ImageF::Create(memory_manager, xsize, ysize));
1233
0
  DiffPrecompute(mask0, kMul, kBias, &diff0);
1234
0
  DiffPrecompute(mask1, kMul, kBias, &diff1);
1235
0
  JXL_RETURN_IF_ERROR(Blur(diff0, kRadius, params, blur_temp, &blurred0));
1236
0
  FuzzyErosion(blurred0, &diff0);
1237
0
  JXL_RETURN_IF_ERROR(Blur(diff1, kRadius, params, blur_temp, &blurred1));
1238
0
  for (size_t y = 0; y < ysize; ++y) {
1239
0
    for (size_t x = 0; x < xsize; ++x) {
1240
0
      mask->Row(y)[x] = diff0.Row(y)[x];
1241
0
      if (diff_ac != nullptr) {
1242
0
        static const float kMaskToErrorMul = 10.0;
1243
0
        float diff = blurred0.Row(y)[x] - blurred1.Row(y)[x];
1244
0
        diff_ac->Row(y)[x] += kMaskToErrorMul * diff * diff;
1245
0
      }
1246
0
    }
1247
0
  }
1248
0
  return true;
1249
0
}
1250
1251
// `diff_ac` may be null.
1252
Status MaskPsychoImage(const PsychoImage& pi0, const PsychoImage& pi1,
1253
                       const size_t xsize, const size_t ysize,
1254
                       const ButteraugliParams& params, BlurTemp* blur_temp,
1255
                       ImageF* BUTTERAUGLI_RESTRICT mask,
1256
0
                       ImageF* BUTTERAUGLI_RESTRICT diff_ac) {
1257
0
  JxlMemoryManager* memory_manager = pi0.hf[0].memory_manager();
1258
0
  JXL_ASSIGN_OR_RETURN(ImageF mask0,
1259
0
                       ImageF::Create(memory_manager, xsize, ysize));
1260
0
  JXL_ASSIGN_OR_RETURN(ImageF mask1,
1261
0
                       ImageF::Create(memory_manager, xsize, ysize));
1262
0
  CombineChannelsForMasking(&pi0.hf[0], &pi0.uhf[0], &mask0);
1263
0
  CombineChannelsForMasking(&pi1.hf[0], &pi1.uhf[0], &mask1);
1264
0
  JXL_RETURN_IF_ERROR(Mask(mask0, mask1, params, blur_temp, mask, diff_ac));
1265
0
  return true;
1266
0
}
1267
1268
0
double MaskY(double delta) {
1269
0
  static const double offset = 0.829591754942;
1270
0
  static const double scaler = 0.451936922203;
1271
0
  static const double mul = 2.5485944793;
1272
0
  const double c = mul / ((scaler * delta) + offset);
1273
0
  const double retval = kGlobalScale * (1.0 + c);
1274
0
  return retval * retval;
1275
0
}
1276
1277
0
double MaskDcY(double delta) {
1278
0
  static const double offset = 0.20025578522;
1279
0
  static const double scaler = 3.87449418804;
1280
0
  static const double mul = 0.505054525019;
1281
0
  const double c = mul / ((scaler * delta) + offset);
1282
0
  const double retval = kGlobalScale * (1.0 + c);
1283
0
  return retval * retval;
1284
0
}
1285
1286
0
inline float MaskColor(const float color[3], const float mask) {
1287
0
  return color[0] * mask + color[1] * mask + color[2] * mask;
1288
0
}
1289
1290
// Diffmap := sqrt of sum{diff images by multiplied by X and Y/B masks}
1291
Status CombineChannelsToDiffmap(const ImageF& mask,
1292
                                const Image3F& block_diff_dc,
1293
                                const Image3F& block_diff_ac, float xmul,
1294
0
                                ImageF* result) {
1295
0
  JXL_ENSURE(SameSize(mask, *result));
1296
0
  size_t xsize = mask.xsize();
1297
0
  size_t ysize = mask.ysize();
1298
0
  for (size_t y = 0; y < ysize; ++y) {
1299
0
    float* BUTTERAUGLI_RESTRICT row_out = result->Row(y);
1300
0
    for (size_t x = 0; x < xsize; ++x) {
1301
0
      float val = mask.Row(y)[x];
1302
0
      float maskval = MaskY(val);
1303
0
      float dc_maskval = MaskDcY(val);
1304
0
      float diff_dc[3];
1305
0
      float diff_ac[3];
1306
0
      for (int i = 0; i < 3; ++i) {
1307
0
        diff_dc[i] = block_diff_dc.PlaneRow(i, y)[x];
1308
0
        diff_ac[i] = block_diff_ac.PlaneRow(i, y)[x];
1309
0
      }
1310
0
      diff_ac[0] *= xmul;
1311
0
      diff_dc[0] *= xmul;
1312
0
      row_out[x] = std::sqrt(MaskColor(diff_dc, dc_maskval) +
1313
0
                             MaskColor(diff_ac, maskval));
1314
0
    }
1315
0
  }
1316
0
  return true;
1317
0
}
1318
1319
// Adds weighted L2 difference between i0 and i1 to diffmap.
1320
static void L2Diff(const ImageF& i0, const ImageF& i1, const float w,
1321
0
                   ImageF* BUTTERAUGLI_RESTRICT diffmap) {
1322
0
  if (w == 0) return;
1323
1324
0
  const HWY_FULL(float) d;
1325
0
  const auto weight = Set(d, w);
1326
1327
0
  for (size_t y = 0; y < i0.ysize(); ++y) {
1328
0
    const float* BUTTERAUGLI_RESTRICT row0 = i0.ConstRow(y);
1329
0
    const float* BUTTERAUGLI_RESTRICT row1 = i1.ConstRow(y);
1330
0
    float* BUTTERAUGLI_RESTRICT row_diff = diffmap->Row(y);
1331
1332
0
    for (size_t x = 0; x < i0.xsize(); x += Lanes(d)) {
1333
0
      const auto diff = Sub(Load(d, row0 + x), Load(d, row1 + x));
1334
0
      const auto diff2 = Mul(diff, diff);
1335
0
      const auto prev = Load(d, row_diff + x);
1336
0
      Store(MulAdd(diff2, weight, prev), d, row_diff + x);
1337
0
    }
1338
0
  }
1339
0
}
1340
1341
// Initializes diffmap to the weighted L2 difference between i0 and i1.
1342
static void SetL2Diff(const ImageF& i0, const ImageF& i1, const float w,
1343
0
                      ImageF* BUTTERAUGLI_RESTRICT diffmap) {
1344
0
  if (w == 0) return;
1345
1346
0
  const HWY_FULL(float) d;
1347
0
  const auto weight = Set(d, w);
1348
1349
0
  for (size_t y = 0; y < i0.ysize(); ++y) {
1350
0
    const float* BUTTERAUGLI_RESTRICT row0 = i0.ConstRow(y);
1351
0
    const float* BUTTERAUGLI_RESTRICT row1 = i1.ConstRow(y);
1352
0
    float* BUTTERAUGLI_RESTRICT row_diff = diffmap->Row(y);
1353
1354
0
    for (size_t x = 0; x < i0.xsize(); x += Lanes(d)) {
1355
0
      const auto diff = Sub(Load(d, row0 + x), Load(d, row1 + x));
1356
0
      const auto diff2 = Mul(diff, diff);
1357
0
      Store(Mul(diff2, weight), d, row_diff + x);
1358
0
    }
1359
0
  }
1360
0
}
1361
1362
// i0 is the original image.
1363
// i1 is the deformed copy.
1364
static void L2DiffAsymmetric(const ImageF& i0, const ImageF& i1, float w_0gt1,
1365
                             float w_0lt1,
1366
0
                             ImageF* BUTTERAUGLI_RESTRICT diffmap) {
1367
0
  if (w_0gt1 == 0 && w_0lt1 == 0) {
1368
0
    return;
1369
0
  }
1370
1371
0
  const HWY_FULL(float) d;
1372
0
  const auto vw_0gt1 = Set(d, w_0gt1 * 0.8);
1373
0
  const auto vw_0lt1 = Set(d, w_0lt1 * 0.8);
1374
1375
0
  for (size_t y = 0; y < i0.ysize(); ++y) {
1376
0
    const float* BUTTERAUGLI_RESTRICT row0 = i0.Row(y);
1377
0
    const float* BUTTERAUGLI_RESTRICT row1 = i1.Row(y);
1378
0
    float* BUTTERAUGLI_RESTRICT row_diff = diffmap->Row(y);
1379
1380
0
    for (size_t x = 0; x < i0.xsize(); x += Lanes(d)) {
1381
0
      const auto val0 = Load(d, row0 + x);
1382
0
      const auto val1 = Load(d, row1 + x);
1383
1384
      // Primary symmetric quadratic objective.
1385
0
      const auto diff = Sub(val0, val1);
1386
0
      auto total = MulAdd(Mul(diff, diff), vw_0gt1, Load(d, row_diff + x));
1387
1388
      // Secondary half-open quadratic objectives.
1389
0
      const auto fabs0 = Abs(val0);
1390
0
      const auto too_small = Mul(Set(d, 0.4), fabs0);
1391
0
      const auto too_big = fabs0;
1392
1393
0
      const auto if_neg = IfThenElse(
1394
0
          Gt(val1, Neg(too_small)), Add(val1, too_small),
1395
0
          IfThenElseZero(Lt(val1, Neg(too_big)), Sub(Neg(val1), too_big)));
1396
0
      const auto if_pos =
1397
0
          IfThenElse(Lt(val1, too_small), Sub(too_small, val1),
1398
0
                     IfThenElseZero(Gt(val1, too_big), Sub(val1, too_big)));
1399
0
      const auto v = IfThenElse(Lt(val0, Zero(d)), if_neg, if_pos);
1400
0
      total = MulAdd(vw_0lt1, Mul(v, v), total);
1401
0
      Store(total, d, row_diff + x);
1402
0
    }
1403
0
  }
1404
0
}
1405
1406
// A simple HDR compatible gamma function.
1407
template <class DF, class V>
1408
0
V Gamma(const DF df, V v) {
1409
  // ln(2) constant folded in because we want std::log but have FastLog2f.
1410
0
  const auto kRetMul = Set(df, 19.245013259874995f * kInvLog2e);
1411
0
  const auto kRetAdd = Set(df, -23.16046239805755);
1412
  // This should happen rarely, but may lead to a NaN in log, which is
1413
  // undesirable. Since negative photons don't exist we solve the NaNs by
1414
  // clamping here.
1415
0
  v = ZeroIfNegative(v);
1416
1417
0
  const auto biased = Add(v, Set(df, 9.9710635769299145));
1418
0
  const auto log = FastLog2f(df, biased);
1419
  // We could fold this into a custom Log2 polynomial, but there would be
1420
  // relatively little gain.
1421
0
  return MulAdd(kRetMul, log, kRetAdd);
1422
0
}
1423
1424
template <bool Clamp, class DF, class V>
1425
BUTTERAUGLI_INLINE void OpsinAbsorbance(const DF df, const V& in0, const V& in1,
1426
                                        const V& in2, V* JXL_RESTRICT out0,
1427
                                        V* JXL_RESTRICT out1,
1428
0
                                        V* JXL_RESTRICT out2) {
1429
  // https://en.wikipedia.org/wiki/Photopsin absorbance modeling.
1430
0
  static const double mixi0 = 0.29956550340058319;
1431
0
  static const double mixi1 = 0.63373087833825936;
1432
0
  static const double mixi2 = 0.077705617820981968;
1433
0
  static const double mixi3 = 1.7557483643287353;
1434
0
  static const double mixi4 = 0.22158691104574774;
1435
0
  static const double mixi5 = 0.69391388044116142;
1436
0
  static const double mixi6 = 0.0987313588422;
1437
0
  static const double mixi7 = 1.7557483643287353;
1438
0
  static const double mixi8 = 0.02;
1439
0
  static const double mixi9 = 0.02;
1440
0
  static const double mixi10 = 0.20480129041026129;
1441
0
  static const double mixi11 = 12.226454707163354;
1442
1443
0
  const V mix0 = Set(df, mixi0);
1444
0
  const V mix1 = Set(df, mixi1);
1445
0
  const V mix2 = Set(df, mixi2);
1446
0
  const V mix3 = Set(df, mixi3);
1447
0
  const V mix4 = Set(df, mixi4);
1448
0
  const V mix5 = Set(df, mixi5);
1449
0
  const V mix6 = Set(df, mixi6);
1450
0
  const V mix7 = Set(df, mixi7);
1451
0
  const V mix8 = Set(df, mixi8);
1452
0
  const V mix9 = Set(df, mixi9);
1453
0
  const V mix10 = Set(df, mixi10);
1454
0
  const V mix11 = Set(df, mixi11);
1455
1456
0
  *out0 = MulAdd(mix0, in0, MulAdd(mix1, in1, MulAdd(mix2, in2, mix3)));
1457
0
  *out1 = MulAdd(mix4, in0, MulAdd(mix5, in1, MulAdd(mix6, in2, mix7)));
1458
0
  *out2 = MulAdd(mix8, in0, MulAdd(mix9, in1, MulAdd(mix10, in2, mix11)));
1459
1460
0
  if (Clamp) {
1461
0
    *out0 = Max(*out0, mix3);
1462
0
    *out1 = Max(*out1, mix7);
1463
0
    *out2 = Max(*out2, mix11);
1464
0
  }
1465
0
}
Unexecuted instantiation: void jxl::N_SCALAR::OpsinAbsorbance<true, hwy::N_SCALAR::Simd<float, 1ul, 0>, hwy::N_SCALAR::Vec1<float> >(hwy::N_SCALAR::Simd<float, 1ul, 0>, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float>*, hwy::N_SCALAR::Vec1<float>*, hwy::N_SCALAR::Vec1<float>*)
Unexecuted instantiation: void jxl::N_SCALAR::OpsinAbsorbance<false, hwy::N_SCALAR::Simd<float, 1ul, 0>, hwy::N_SCALAR::Vec1<float> >(hwy::N_SCALAR::Simd<float, 1ul, 0>, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float> const&, hwy::N_SCALAR::Vec1<float>*, hwy::N_SCALAR::Vec1<float>*, hwy::N_SCALAR::Vec1<float>*)
1466
1467
// `blurred` is a temporary image used inside this function and not returned.
1468
Status OpsinDynamicsImage(const Image3F& rgb, const ButteraugliParams& params,
1469
0
                          Image3F* blurred, BlurTemp* blur_temp, Image3F* xyb) {
1470
0
  JXL_ENSURE(blurred != nullptr);
1471
0
  const double kSigma = 1.2;
1472
0
  JXL_RETURN_IF_ERROR(
1473
0
      Blur(rgb.Plane(0), kSigma, params, blur_temp, &blurred->Plane(0)));
1474
0
  JXL_RETURN_IF_ERROR(
1475
0
      Blur(rgb.Plane(1), kSigma, params, blur_temp, &blurred->Plane(1)));
1476
0
  JXL_RETURN_IF_ERROR(
1477
0
      Blur(rgb.Plane(2), kSigma, params, blur_temp, &blurred->Plane(2)));
1478
0
  const HWY_FULL(float) df;
1479
0
  const auto intensity_target_multiplier = Set(df, params.intensity_target);
1480
0
  for (size_t y = 0; y < rgb.ysize(); ++y) {
1481
0
    const float* row_r = rgb.ConstPlaneRow(0, y);
1482
0
    const float* row_g = rgb.ConstPlaneRow(1, y);
1483
0
    const float* row_b = rgb.ConstPlaneRow(2, y);
1484
0
    const float* row_blurred_r = blurred->ConstPlaneRow(0, y);
1485
0
    const float* row_blurred_g = blurred->ConstPlaneRow(1, y);
1486
0
    const float* row_blurred_b = blurred->ConstPlaneRow(2, y);
1487
0
    float* row_out_x = xyb->PlaneRow(0, y);
1488
0
    float* row_out_y = xyb->PlaneRow(1, y);
1489
0
    float* row_out_b = xyb->PlaneRow(2, y);
1490
0
    const auto min = Set(df, 1e-4f);
1491
0
    for (size_t x = 0; x < rgb.xsize(); x += Lanes(df)) {
1492
0
      auto sensitivity0 = Undefined(df);
1493
0
      auto sensitivity1 = Undefined(df);
1494
0
      auto sensitivity2 = Undefined(df);
1495
0
      {
1496
        // Calculate sensitivity based on the smoothed image gamma derivative.
1497
0
        auto pre_mixed0 = Undefined(df);
1498
0
        auto pre_mixed1 = Undefined(df);
1499
0
        auto pre_mixed2 = Undefined(df);
1500
0
        OpsinAbsorbance<true>(
1501
0
            df, Mul(Load(df, row_blurred_r + x), intensity_target_multiplier),
1502
0
            Mul(Load(df, row_blurred_g + x), intensity_target_multiplier),
1503
0
            Mul(Load(df, row_blurred_b + x), intensity_target_multiplier),
1504
0
            &pre_mixed0, &pre_mixed1, &pre_mixed2);
1505
0
        pre_mixed0 = Max(pre_mixed0, min);
1506
0
        pre_mixed1 = Max(pre_mixed1, min);
1507
0
        pre_mixed2 = Max(pre_mixed2, min);
1508
0
        sensitivity0 = Div(Gamma(df, pre_mixed0), pre_mixed0);
1509
0
        sensitivity1 = Div(Gamma(df, pre_mixed1), pre_mixed1);
1510
0
        sensitivity2 = Div(Gamma(df, pre_mixed2), pre_mixed2);
1511
0
        sensitivity0 = Max(sensitivity0, min);
1512
0
        sensitivity1 = Max(sensitivity1, min);
1513
0
        sensitivity2 = Max(sensitivity2, min);
1514
0
      }
1515
0
      auto cur_mixed0 = Undefined(df);
1516
0
      auto cur_mixed1 = Undefined(df);
1517
0
      auto cur_mixed2 = Undefined(df);
1518
0
      OpsinAbsorbance<false>(
1519
0
          df, Mul(Load(df, row_r + x), intensity_target_multiplier),
1520
0
          Mul(Load(df, row_g + x), intensity_target_multiplier),
1521
0
          Mul(Load(df, row_b + x), intensity_target_multiplier), &cur_mixed0,
1522
0
          &cur_mixed1, &cur_mixed2);
1523
0
      cur_mixed0 = Mul(cur_mixed0, sensitivity0);
1524
0
      cur_mixed1 = Mul(cur_mixed1, sensitivity1);
1525
0
      cur_mixed2 = Mul(cur_mixed2, sensitivity2);
1526
      // This is a kludge. The negative values should be zeroed away before
1527
      // blurring. Ideally there would be no negative values in the first place.
1528
0
      const auto min01 = Set(df, 1.7557483643287353f);
1529
0
      const auto min2 = Set(df, 12.226454707163354f);
1530
0
      cur_mixed0 = Max(cur_mixed0, min01);
1531
0
      cur_mixed1 = Max(cur_mixed1, min01);
1532
0
      cur_mixed2 = Max(cur_mixed2, min2);
1533
1534
0
      Store(Sub(cur_mixed0, cur_mixed1), df, row_out_x + x);
1535
0
      Store(Add(cur_mixed0, cur_mixed1), df, row_out_y + x);
1536
0
      Store(cur_mixed2, df, row_out_b + x);
1537
0
    }
1538
0
  }
1539
0
  return true;
1540
0
}
1541
1542
Status ButteraugliDiffmapInPlace(Image3F& image0, Image3F& image1,
1543
                                 const ButteraugliParams& params,
1544
0
                                 ImageF& diffmap) {
1545
  // image0 and image1 are in linear sRGB color space
1546
0
  const size_t xsize = image0.xsize();
1547
0
  const size_t ysize = image0.ysize();
1548
0
  JxlMemoryManager* memory_manager = image0.memory_manager();
1549
0
  BlurTemp blur_temp;
1550
0
  {
1551
    // Convert image0 and image1 to XYB in-place
1552
0
    JXL_ASSIGN_OR_RETURN(Image3F temp,
1553
0
                         Image3F::Create(memory_manager, xsize, ysize));
1554
0
    JXL_RETURN_IF_ERROR(
1555
0
        OpsinDynamicsImage(image0, params, &temp, &blur_temp, &image0));
1556
0
    JXL_RETURN_IF_ERROR(
1557
0
        OpsinDynamicsImage(image1, params, &temp, &blur_temp, &image1));
1558
0
  }
1559
  // image0 and image1 are in XYB color space
1560
0
  JXL_ASSIGN_OR_RETURN(ImageF block_diff_dc,
1561
0
                       ImageF::Create(memory_manager, xsize, ysize));
1562
0
  ZeroFillImage(&block_diff_dc);
1563
0
  {
1564
    // separate out LF components from image0 and image1 and compute the dc
1565
    // diff image from them
1566
0
    JXL_ASSIGN_OR_RETURN(Image3F lf0,
1567
0
                         Image3F::Create(memory_manager, xsize, ysize));
1568
0
    JXL_ASSIGN_OR_RETURN(Image3F lf1,
1569
0
                         Image3F::Create(memory_manager, xsize, ysize));
1570
0
    JXL_RETURN_IF_ERROR(
1571
0
        SeparateLFAndMF(params, image0, &lf0, &image0, &blur_temp));
1572
0
    JXL_RETURN_IF_ERROR(
1573
0
        SeparateLFAndMF(params, image1, &lf1, &image1, &blur_temp));
1574
0
    for (size_t c = 0; c < 3; ++c) {
1575
0
      L2Diff(lf0.Plane(c), lf1.Plane(c), wmul[6 + c], &block_diff_dc);
1576
0
    }
1577
0
  }
1578
  // image0 and image1 are MF residuals (before blurring) in XYB color space
1579
0
  ImageF hf0[2];
1580
0
  ImageF hf1[2];
1581
0
  JXL_RETURN_IF_ERROR(SeparateMFAndHF(params, &image0, &hf0[0], &blur_temp));
1582
0
  JXL_RETURN_IF_ERROR(SeparateMFAndHF(params, &image1, &hf1[0], &blur_temp));
1583
  // image0 and image1 are MF-images in XYB color space
1584
1585
0
  JXL_ASSIGN_OR_RETURN(ImageF block_diff_ac,
1586
0
                       ImageF::Create(memory_manager, xsize, ysize));
1587
0
  ZeroFillImage(&block_diff_ac);
1588
  // start accumulating ac diff image from MF images
1589
0
  {
1590
0
    JXL_ASSIGN_OR_RETURN(ImageF diffs,
1591
0
                         ImageF::Create(memory_manager, xsize, ysize));
1592
0
    JXL_RETURN_IF_ERROR(MaltaDiffMapLF(image0.Plane(1), image1.Plane(1),
1593
0
                                       wMfMalta, wMfMalta, norm1Mf, &diffs,
1594
0
                                       &block_diff_ac));
1595
0
    JXL_RETURN_IF_ERROR(MaltaDiffMapLF(image0.Plane(0), image1.Plane(0),
1596
0
                                       wMfMaltaX, wMfMaltaX, norm1MfX, &diffs,
1597
0
                                       &block_diff_ac));
1598
0
  }
1599
0
  for (size_t c = 0; c < 3; ++c) {
1600
0
    L2Diff(image0.Plane(c), image1.Plane(c), wmul[3 + c], &block_diff_ac);
1601
0
  }
1602
  // we will not need the MF-images and more, so we deallocate them to reduce
1603
  // peak memory usage
1604
0
  image0 = Image3F();
1605
0
  image1 = Image3F();
1606
1607
0
  ImageF uhf0[2];
1608
0
  ImageF uhf1[2];
1609
0
  JXL_RETURN_IF_ERROR(SeparateHFAndUHF(params, &hf0[0], &uhf0[0], &blur_temp));
1610
0
  JXL_RETURN_IF_ERROR(SeparateHFAndUHF(params, &hf1[0], &uhf1[0], &blur_temp));
1611
1612
  // continue accumulating ac diff image from HF and UHF images
1613
0
  const float hf_asymmetry = params.hf_asymmetry;
1614
0
  {
1615
0
    JXL_ASSIGN_OR_RETURN(ImageF diffs,
1616
0
                         ImageF::Create(memory_manager, xsize, ysize));
1617
0
    JXL_RETURN_IF_ERROR(MaltaDiffMap(uhf0[1], uhf1[1], wUhfMalta * hf_asymmetry,
1618
0
                                     wUhfMalta / hf_asymmetry, norm1Uhf, &diffs,
1619
0
                                     &block_diff_ac));
1620
0
    JXL_RETURN_IF_ERROR(MaltaDiffMap(
1621
0
        uhf0[0], uhf1[0], wUhfMaltaX * hf_asymmetry, wUhfMaltaX / hf_asymmetry,
1622
0
        norm1UhfX, &diffs, &block_diff_ac));
1623
0
    JXL_RETURN_IF_ERROR(MaltaDiffMapLF(
1624
0
        hf0[1], hf1[1], wHfMalta * std::sqrt(hf_asymmetry),
1625
0
        wHfMalta / std::sqrt(hf_asymmetry), norm1Hf, &diffs, &block_diff_ac));
1626
0
    JXL_RETURN_IF_ERROR(MaltaDiffMapLF(
1627
0
        hf0[0], hf1[0], wHfMaltaX * std::sqrt(hf_asymmetry),
1628
0
        wHfMaltaX / std::sqrt(hf_asymmetry), norm1HfX, &diffs, &block_diff_ac));
1629
0
  }
1630
0
  for (size_t c = 0; c < 2; ++c) {
1631
0
    L2DiffAsymmetric(hf0[c], hf1[c], wmul[c] * hf_asymmetry,
1632
0
                     wmul[c] / hf_asymmetry, &block_diff_ac);
1633
0
  }
1634
1635
  // compute mask image from HF and UHF X and Y images
1636
0
  JXL_ASSIGN_OR_RETURN(ImageF mask,
1637
0
                       ImageF::Create(memory_manager, xsize, ysize));
1638
0
  {
1639
0
    JXL_ASSIGN_OR_RETURN(ImageF mask0,
1640
0
                         ImageF::Create(memory_manager, xsize, ysize));
1641
0
    JXL_ASSIGN_OR_RETURN(ImageF mask1,
1642
0
                         ImageF::Create(memory_manager, xsize, ysize));
1643
0
    CombineChannelsForMasking(&hf0[0], &uhf0[0], &mask0);
1644
0
    CombineChannelsForMasking(&hf1[0], &uhf1[0], &mask1);
1645
0
    DeallocateHFAndUHF(&hf1[0], &uhf1[0]);
1646
0
    DeallocateHFAndUHF(&hf0[0], &uhf0[0]);
1647
0
    JXL_RETURN_IF_ERROR(
1648
0
        Mask(mask0, mask1, params, &blur_temp, &mask, &block_diff_ac));
1649
0
  }
1650
1651
  // compute final diffmap from mask image and ac and dc diff images
1652
0
  JXL_ASSIGN_OR_RETURN(diffmap, ImageF::Create(memory_manager, xsize, ysize));
1653
0
  for (size_t y = 0; y < ysize; ++y) {
1654
0
    const float* row_dc = block_diff_dc.Row(y);
1655
0
    const float* row_ac = block_diff_ac.Row(y);
1656
0
    float* row_out = diffmap.Row(y);
1657
0
    for (size_t x = 0; x < xsize; ++x) {
1658
0
      const float val = mask.Row(y)[x];
1659
0
      row_out[x] = sqrt(row_dc[x] * MaskDcY(val) + row_ac[x] * MaskY(val));
1660
0
    }
1661
0
  }
1662
0
  return true;
1663
0
}
1664
1665
// NOLINTNEXTLINE(google-readability-namespace-comments)
1666
}  // namespace HWY_NAMESPACE
1667
}  // namespace jxl
1668
HWY_AFTER_NAMESPACE();
1669
1670
#if HWY_ONCE
1671
namespace jxl {
1672
1673
HWY_EXPORT(SeparateFrequencies);       // Local function.
1674
HWY_EXPORT(MaskPsychoImage);           // Local function.
1675
HWY_EXPORT(L2DiffAsymmetric);          // Local function.
1676
HWY_EXPORT(L2Diff);                    // Local function.
1677
HWY_EXPORT(SetL2Diff);                 // Local function.
1678
HWY_EXPORT(CombineChannelsToDiffmap);  // Local function.
1679
HWY_EXPORT(MaltaDiffMap);              // Local function.
1680
HWY_EXPORT(MaltaDiffMapLF);            // Local function.
1681
HWY_EXPORT(OpsinDynamicsImage);        // Local function.
1682
HWY_EXPORT(ButteraugliDiffmapInPlace);  // Local function.
1683
1684
#if BUTTERAUGLI_ENABLE_CHECKS
1685
1686
static inline bool IsNan(const float x) {
1687
  uint32_t bits;
1688
  memcpy(&bits, &x, sizeof(bits));
1689
  const uint32_t bitmask_exp = 0x7F800000;
1690
  return (bits & bitmask_exp) == bitmask_exp && (bits & 0x7FFFFF);
1691
}
1692
1693
static inline bool IsNan(const double x) {
1694
  uint64_t bits;
1695
  memcpy(&bits, &x, sizeof(bits));
1696
  return (0x7ff0000000000001ULL <= bits && bits <= 0x7fffffffffffffffULL) ||
1697
         (0xfff0000000000001ULL <= bits && bits <= 0xffffffffffffffffULL);
1698
}
1699
1700
static inline void CheckImage(const ImageF& image, const char* name) {
1701
  for (size_t y = 0; y < image.ysize(); ++y) {
1702
    const float* BUTTERAUGLI_RESTRICT row = image.Row(y);
1703
    for (size_t x = 0; x < image.xsize(); ++x) {
1704
      if (IsNan(row[x])) {
1705
        printf("NAN: Image %s @ %" PRIuS ",%" PRIuS " (of %" PRIuS ",%" PRIuS
1706
               ")\n",
1707
               name, x, y, image.xsize(), image.ysize());
1708
        exit(1);
1709
      }
1710
    }
1711
  }
1712
}
1713
1714
#define CHECK_NAN(x, str)                \
1715
  do {                                   \
1716
    if (IsNan(x)) {                      \
1717
      printf("%d: %s\n", __LINE__, str); \
1718
      abort();                           \
1719
    }                                    \
1720
  } while (0)
1721
1722
#define CHECK_IMAGE(image, name) CheckImage(image, name)
1723
1724
#else  // BUTTERAUGLI_ENABLE_CHECKS
1725
1726
#define CHECK_NAN(x, str)
1727
#define CHECK_IMAGE(image, name)
1728
1729
#endif  // BUTTERAUGLI_ENABLE_CHECKS
1730
1731
// Calculate a 2x2 subsampled image for purposes of recursive butteraugli at
1732
// multiresolution.
1733
0
static StatusOr<Image3F> SubSample2x(const Image3F& in) {
1734
0
  size_t xs = (in.xsize() + 1) / 2;
1735
0
  size_t ys = (in.ysize() + 1) / 2;
1736
0
  JxlMemoryManager* memory_manager = in.memory_manager();
1737
0
  JXL_ASSIGN_OR_RETURN(Image3F retval, Image3F::Create(memory_manager, xs, ys));
1738
0
  for (size_t c = 0; c < 3; ++c) {
1739
0
    for (size_t y = 0; y < ys; ++y) {
1740
0
      for (size_t x = 0; x < xs; ++x) {
1741
0
        retval.PlaneRow(c, y)[x] = 0;
1742
0
      }
1743
0
    }
1744
0
  }
1745
0
  for (size_t c = 0; c < 3; ++c) {
1746
0
    for (size_t y = 0; y < in.ysize(); ++y) {
1747
0
      for (size_t x = 0; x < in.xsize(); ++x) {
1748
0
        retval.PlaneRow(c, y / 2)[x / 2] += 0.25f * in.PlaneRow(c, y)[x];
1749
0
      }
1750
0
    }
1751
0
    if ((in.xsize() & 1) != 0) {
1752
0
      for (size_t y = 0; y < retval.ysize(); ++y) {
1753
0
        size_t last_column = retval.xsize() - 1;
1754
0
        retval.PlaneRow(c, y)[last_column] *= 2.0f;
1755
0
      }
1756
0
    }
1757
0
    if ((in.ysize() & 1) != 0) {
1758
0
      for (size_t x = 0; x < retval.xsize(); ++x) {
1759
0
        size_t last_row = retval.ysize() - 1;
1760
0
        retval.PlaneRow(c, last_row)[x] *= 2.0f;
1761
0
      }
1762
0
    }
1763
0
  }
1764
0
  return retval;
1765
0
}
1766
1767
// Supersample src by 2x and add it to dest.
1768
0
static void AddSupersampled2x(const ImageF& src, float w, ImageF& dest) {
1769
0
  for (size_t y = 0; y < dest.ysize(); ++y) {
1770
0
    for (size_t x = 0; x < dest.xsize(); ++x) {
1771
      // There will be less errors from the more averaged images.
1772
      // We take it into account to some extent using a scaler.
1773
0
      static const double kHeuristicMixingValue = 0.3;
1774
0
      dest.Row(y)[x] *= 1.0 - kHeuristicMixingValue * w;
1775
0
      dest.Row(y)[x] += w * src.Row(y / 2)[x / 2];
1776
0
    }
1777
0
  }
1778
0
}
1779
1780
0
Image3F* ButteraugliComparator::Temp() const {
1781
0
  bool was_in_use = temp_in_use_.test_and_set(std::memory_order_acq_rel);
1782
0
  if (was_in_use) return nullptr;
1783
0
  return &temp_;
1784
0
}
1785
1786
0
void ButteraugliComparator::ReleaseTemp() const { temp_in_use_.clear(); }
1787
1788
ButteraugliComparator::ButteraugliComparator(size_t xsize, size_t ysize,
1789
                                             const ButteraugliParams& params)
1790
0
    : xsize_(xsize), ysize_(ysize), params_(params) {}
1791
1792
StatusOr<std::unique_ptr<ButteraugliComparator>> ButteraugliComparator::Make(
1793
0
    const Image3F& rgb0, const ButteraugliParams& params) {
1794
0
  size_t xsize = rgb0.xsize();
1795
0
  size_t ysize = rgb0.ysize();
1796
0
  JxlMemoryManager* memory_manager = rgb0.memory_manager();
1797
0
  std::unique_ptr<ButteraugliComparator> result =
1798
0
      std::unique_ptr<ButteraugliComparator>(
1799
0
          new ButteraugliComparator(xsize, ysize, params));
1800
0
  JXL_ASSIGN_OR_RETURN(result->temp_,
1801
0
                       Image3F::Create(memory_manager, xsize, ysize));
1802
1803
0
  if (xsize < 8 || ysize < 8) {
1804
0
    return result;
1805
0
  }
1806
1807
0
  JXL_ASSIGN_OR_RETURN(Image3F xyb0,
1808
0
                       Image3F::Create(memory_manager, xsize, ysize));
1809
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(OpsinDynamicsImage)(
1810
0
      rgb0, params, result->Temp(), &result->blur_temp_, &xyb0));
1811
0
  result->ReleaseTemp();
1812
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(SeparateFrequencies)(
1813
0
      xsize, ysize, params, &result->blur_temp_, xyb0, result->pi0_));
1814
1815
  // Awful recursive construction of samples of different resolution.
1816
  // This is an after-thought and possibly somewhat parallel in
1817
  // functionality with the PsychoImage multi-resolution approach.
1818
0
  JXL_ASSIGN_OR_RETURN(Image3F subsampledRgb0, SubSample2x(rgb0));
1819
0
  JXL_ASSIGN_OR_RETURN(result->sub_,
1820
0
                       ButteraugliComparator::Make(subsampledRgb0, params));
1821
0
  return result;
1822
0
}
1823
1824
0
Status ButteraugliComparator::Mask(ImageF* BUTTERAUGLI_RESTRICT mask) const {
1825
0
  return HWY_DYNAMIC_DISPATCH(MaskPsychoImage)(
1826
0
      pi0_, pi0_, xsize_, ysize_, params_, &blur_temp_, mask, nullptr);
1827
0
}
1828
1829
Status ButteraugliComparator::Diffmap(const Image3F& rgb1,
1830
0
                                      ImageF& result) const {
1831
0
  JxlMemoryManager* memory_manager = rgb1.memory_manager();
1832
0
  if (xsize_ < 8 || ysize_ < 8) {
1833
0
    ZeroFillImage(&result);
1834
0
    return true;
1835
0
  }
1836
0
  JXL_ASSIGN_OR_RETURN(Image3F xyb1,
1837
0
                       Image3F::Create(memory_manager, xsize_, ysize_));
1838
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(OpsinDynamicsImage)(
1839
0
      rgb1, params_, Temp(), &blur_temp_, &xyb1));
1840
0
  ReleaseTemp();
1841
0
  JXL_RETURN_IF_ERROR(DiffmapOpsinDynamicsImage(xyb1, result));
1842
0
  if (sub_) {
1843
0
    if (sub_->xsize_ < 8 || sub_->ysize_ < 8) {
1844
0
      return true;
1845
0
    }
1846
0
    JXL_ASSIGN_OR_RETURN(
1847
0
        Image3F sub_xyb,
1848
0
        Image3F::Create(memory_manager, sub_->xsize_, sub_->ysize_));
1849
0
    JXL_ASSIGN_OR_RETURN(Image3F subsampledRgb1, SubSample2x(rgb1));
1850
0
    JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(OpsinDynamicsImage)(
1851
0
        subsampledRgb1, params_, sub_->Temp(), &sub_->blur_temp_, &sub_xyb));
1852
0
    sub_->ReleaseTemp();
1853
0
    ImageF subresult;
1854
0
    JXL_RETURN_IF_ERROR(sub_->DiffmapOpsinDynamicsImage(sub_xyb, subresult));
1855
0
    AddSupersampled2x(subresult, 0.5, result);
1856
0
  }
1857
0
  return true;
1858
0
}
1859
1860
Status ButteraugliComparator::DiffmapOpsinDynamicsImage(const Image3F& xyb1,
1861
0
                                                        ImageF& result) const {
1862
0
  JxlMemoryManager* memory_manager = xyb1.memory_manager();
1863
0
  if (xsize_ < 8 || ysize_ < 8) {
1864
0
    ZeroFillImage(&result);
1865
0
    return true;
1866
0
  }
1867
0
  PsychoImage pi1;
1868
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(SeparateFrequencies)(
1869
0
      xsize_, ysize_, params_, &blur_temp_, xyb1, pi1));
1870
0
  JXL_ASSIGN_OR_RETURN(result, ImageF::Create(memory_manager, xsize_, ysize_));
1871
0
  return DiffmapPsychoImage(pi1, result);
1872
0
}
1873
1874
namespace {
1875
1876
Status MaltaDiffMap(const ImageF& lum0, const ImageF& lum1, const double w_0gt1,
1877
                    const double w_0lt1, const double norm1,
1878
                    ImageF* HWY_RESTRICT diffs,
1879
0
                    Image3F* HWY_RESTRICT block_diff_ac, size_t c) {
1880
0
  return HWY_DYNAMIC_DISPATCH(MaltaDiffMap)(lum0, lum1, w_0gt1, w_0lt1, norm1,
1881
0
                                            diffs, &block_diff_ac->Plane(c));
1882
0
}
1883
1884
Status MaltaDiffMapLF(const ImageF& lum0, const ImageF& lum1,
1885
                      const double w_0gt1, const double w_0lt1,
1886
                      const double norm1, ImageF* HWY_RESTRICT diffs,
1887
0
                      Image3F* HWY_RESTRICT block_diff_ac, size_t c) {
1888
0
  return HWY_DYNAMIC_DISPATCH(MaltaDiffMapLF)(lum0, lum1, w_0gt1, w_0lt1, norm1,
1889
0
                                              diffs, &block_diff_ac->Plane(c));
1890
0
}
1891
1892
}  // namespace
1893
1894
Status ButteraugliComparator::DiffmapPsychoImage(const PsychoImage& pi1,
1895
0
                                                 ImageF& diffmap) const {
1896
0
  JxlMemoryManager* memory_manager = diffmap.memory_manager();
1897
0
  if (xsize_ < 8 || ysize_ < 8) {
1898
0
    ZeroFillImage(&diffmap);
1899
0
    return true;
1900
0
  }
1901
1902
0
  const float hf_asymmetry_ = params_.hf_asymmetry;
1903
0
  const float xmul_ = params_.xmul;
1904
1905
0
  JXL_ASSIGN_OR_RETURN(ImageF diffs,
1906
0
                       ImageF::Create(memory_manager, xsize_, ysize_));
1907
0
  JXL_ASSIGN_OR_RETURN(Image3F block_diff_ac,
1908
0
                       Image3F::Create(memory_manager, xsize_, ysize_));
1909
0
  ZeroFillImage(&block_diff_ac);
1910
0
  JXL_RETURN_IF_ERROR(MaltaDiffMap(
1911
0
      pi0_.uhf[1], pi1.uhf[1], wUhfMalta * hf_asymmetry_,
1912
0
      wUhfMalta / hf_asymmetry_, norm1Uhf, &diffs, &block_diff_ac, 1));
1913
0
  JXL_RETURN_IF_ERROR(MaltaDiffMap(
1914
0
      pi0_.uhf[0], pi1.uhf[0], wUhfMaltaX * hf_asymmetry_,
1915
0
      wUhfMaltaX / hf_asymmetry_, norm1UhfX, &diffs, &block_diff_ac, 0));
1916
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapLF(
1917
0
      pi0_.hf[1], pi1.hf[1], wHfMalta * std::sqrt(hf_asymmetry_),
1918
0
      wHfMalta / std::sqrt(hf_asymmetry_), norm1Hf, &diffs, &block_diff_ac, 1));
1919
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapLF(pi0_.hf[0], pi1.hf[0],
1920
0
                                     wHfMaltaX * std::sqrt(hf_asymmetry_),
1921
0
                                     wHfMaltaX / std::sqrt(hf_asymmetry_),
1922
0
                                     norm1HfX, &diffs, &block_diff_ac, 0));
1923
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapLF(pi0_.mf.Plane(1), pi1.mf.Plane(1),
1924
0
                                     wMfMalta, wMfMalta, norm1Mf, &diffs,
1925
0
                                     &block_diff_ac, 1));
1926
0
  JXL_RETURN_IF_ERROR(MaltaDiffMapLF(pi0_.mf.Plane(0), pi1.mf.Plane(0),
1927
0
                                     wMfMaltaX, wMfMaltaX, norm1MfX, &diffs,
1928
0
                                     &block_diff_ac, 0));
1929
1930
0
  JXL_ASSIGN_OR_RETURN(Image3F block_diff_dc,
1931
0
                       Image3F::Create(memory_manager, xsize_, ysize_));
1932
0
  for (size_t c = 0; c < 3; ++c) {
1933
0
    if (c < 2) {  // No blue channel error accumulated at HF.
1934
0
      HWY_DYNAMIC_DISPATCH(L2DiffAsymmetric)
1935
0
      (pi0_.hf[c], pi1.hf[c], wmul[c] * hf_asymmetry_, wmul[c] / hf_asymmetry_,
1936
0
       &block_diff_ac.Plane(c));
1937
0
    }
1938
0
    HWY_DYNAMIC_DISPATCH(L2Diff)
1939
0
    (pi0_.mf.Plane(c), pi1.mf.Plane(c), wmul[3 + c], &block_diff_ac.Plane(c));
1940
0
    HWY_DYNAMIC_DISPATCH(SetL2Diff)
1941
0
    (pi0_.lf.Plane(c), pi1.lf.Plane(c), wmul[6 + c], &block_diff_dc.Plane(c));
1942
0
  }
1943
1944
0
  ImageF mask;
1945
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(MaskPsychoImage)(
1946
0
      pi0_, pi1, xsize_, ysize_, params_, &blur_temp_, &mask,
1947
0
      &block_diff_ac.Plane(1)));
1948
1949
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(CombineChannelsToDiffmap)(
1950
0
      mask, block_diff_dc, block_diff_ac, xmul_, &diffmap));
1951
0
  return true;
1952
0
}
1953
1954
double ButteraugliScoreFromDiffmap(const ImageF& diffmap,
1955
0
                                   const ButteraugliParams* params) {
1956
0
  float retval = 0.0f;
1957
0
  for (size_t y = 0; y < diffmap.ysize(); ++y) {
1958
0
    const float* BUTTERAUGLI_RESTRICT row = diffmap.ConstRow(y);
1959
0
    for (size_t x = 0; x < diffmap.xsize(); ++x) {
1960
0
      retval = std::max(retval, row[x]);
1961
0
    }
1962
0
  }
1963
0
  return retval;
1964
0
}
1965
1966
Status ButteraugliDiffmap(const Image3F& rgb0, const Image3F& rgb1,
1967
0
                          double hf_asymmetry, double xmul, ImageF& diffmap) {
1968
0
  ButteraugliParams params;
1969
0
  params.hf_asymmetry = hf_asymmetry;
1970
0
  params.xmul = xmul;
1971
0
  return ButteraugliDiffmap(rgb0, rgb1, params, diffmap);
1972
0
}
1973
1974
template <size_t kMax>
1975
bool ButteraugliDiffmapSmall(const Image3F& rgb0, const Image3F& rgb1,
1976
0
                             const ButteraugliParams& params, ImageF& diffmap) {
1977
0
  const size_t xsize = rgb0.xsize();
1978
0
  const size_t ysize = rgb0.ysize();
1979
0
  JxlMemoryManager* memory_manager = rgb0.memory_manager();
1980
  // Butteraugli values for small (where xsize or ysize is smaller
1981
  // than 8 pixels) images are non-sensical, but most likely it is
1982
  // less disruptive to try to compute something than just give up.
1983
  // Temporarily extend the borders of the image to fit 8 x 8 size.
1984
0
  size_t xborder = xsize < kMax ? (kMax - xsize) / 2 : 0;
1985
0
  size_t yborder = ysize < kMax ? (kMax - ysize) / 2 : 0;
1986
0
  size_t xscaled = std::max<size_t>(kMax, xsize);
1987
0
  size_t yscaled = std::max<size_t>(kMax, ysize);
1988
0
  JXL_ASSIGN_OR_RETURN(Image3F scaled0,
1989
0
                       Image3F::Create(memory_manager, xscaled, yscaled));
1990
0
  JXL_ASSIGN_OR_RETURN(Image3F scaled1,
1991
0
                       Image3F::Create(memory_manager, xscaled, yscaled));
1992
0
  for (int i = 0; i < 3; ++i) {
1993
0
    for (size_t y = 0; y < yscaled; ++y) {
1994
0
      for (size_t x = 0; x < xscaled; ++x) {
1995
0
        size_t x2 = std::min<size_t>(xsize - 1, x > xborder ? x - xborder : 0);
1996
0
        size_t y2 = std::min<size_t>(ysize - 1, y > yborder ? y - yborder : 0);
1997
0
        scaled0.PlaneRow(i, y)[x] = rgb0.PlaneRow(i, y2)[x2];
1998
0
        scaled1.PlaneRow(i, y)[x] = rgb1.PlaneRow(i, y2)[x2];
1999
0
      }
2000
0
    }
2001
0
  }
2002
0
  ImageF diffmap_scaled;
2003
0
  const bool ok = ButteraugliDiffmap(scaled0, scaled1, params, diffmap_scaled);
2004
0
  JXL_ASSIGN_OR_RETURN(diffmap, ImageF::Create(memory_manager, xsize, ysize));
2005
0
  for (size_t y = 0; y < ysize; ++y) {
2006
0
    for (size_t x = 0; x < xsize; ++x) {
2007
0
      diffmap.Row(y)[x] = diffmap_scaled.Row(y + yborder)[x + xborder];
2008
0
    }
2009
0
  }
2010
0
  return ok;
2011
0
}
2012
2013
Status ButteraugliDiffmap(const Image3F& rgb0, const Image3F& rgb1,
2014
0
                          const ButteraugliParams& params, ImageF& diffmap) {
2015
0
  const size_t xsize = rgb0.xsize();
2016
0
  const size_t ysize = rgb0.ysize();
2017
0
  if (xsize < 1 || ysize < 1) {
2018
0
    return JXL_FAILURE("Zero-sized image");
2019
0
  }
2020
0
  if (!SameSize(rgb0, rgb1)) {
2021
0
    return JXL_FAILURE("Size mismatch");
2022
0
  }
2023
0
  static const int kMax = 8;
2024
0
  if (xsize < kMax || ysize < kMax) {
2025
0
    return ButteraugliDiffmapSmall<kMax>(rgb0, rgb1, params, diffmap);
2026
0
  }
2027
0
  JXL_ASSIGN_OR_RETURN(std::unique_ptr<ButteraugliComparator> butteraugli,
2028
0
                       ButteraugliComparator::Make(rgb0, params));
2029
0
  JXL_RETURN_IF_ERROR(butteraugli->Diffmap(rgb1, diffmap));
2030
0
  return true;
2031
0
}
2032
2033
bool ButteraugliInterface(const Image3F& rgb0, const Image3F& rgb1,
2034
                          float hf_asymmetry, float xmul, ImageF& diffmap,
2035
0
                          double& diffvalue) {
2036
0
  ButteraugliParams params;
2037
0
  params.hf_asymmetry = hf_asymmetry;
2038
0
  params.xmul = xmul;
2039
0
  return ButteraugliInterface(rgb0, rgb1, params, diffmap, diffvalue);
2040
0
}
2041
2042
bool ButteraugliInterface(const Image3F& rgb0, const Image3F& rgb1,
2043
                          const ButteraugliParams& params, ImageF& diffmap,
2044
0
                          double& diffvalue) {
2045
0
  if (!ButteraugliDiffmap(rgb0, rgb1, params, diffmap)) {
2046
0
    return false;
2047
0
  }
2048
0
  diffvalue = ButteraugliScoreFromDiffmap(diffmap, &params);
2049
0
  return true;
2050
0
}
2051
2052
Status ButteraugliInterfaceInPlace(Image3F&& rgb0, Image3F&& rgb1,
2053
                                   const ButteraugliParams& params,
2054
0
                                   ImageF& diffmap, double& diffvalue) {
2055
0
  const size_t xsize = rgb0.xsize();
2056
0
  const size_t ysize = rgb0.ysize();
2057
0
  if (xsize < 1 || ysize < 1) {
2058
0
    return JXL_FAILURE("Zero-sized image");
2059
0
  }
2060
0
  if (!SameSize(rgb0, rgb1)) {
2061
0
    return JXL_FAILURE("Size mismatch");
2062
0
  }
2063
0
  static const int kMax = 8;
2064
0
  if (xsize < kMax || ysize < kMax) {
2065
0
    bool ok = ButteraugliDiffmapSmall<kMax>(rgb0, rgb1, params, diffmap);
2066
0
    diffvalue = ButteraugliScoreFromDiffmap(diffmap, &params);
2067
0
    return ok;
2068
0
  }
2069
0
  ImageF subdiffmap;
2070
0
  if (xsize >= 15 && ysize >= 15) {
2071
0
    JXL_ASSIGN_OR_RETURN(Image3F rgb0_sub, SubSample2x(rgb0));
2072
0
    JXL_ASSIGN_OR_RETURN(Image3F rgb1_sub, SubSample2x(rgb1));
2073
0
    JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(ButteraugliDiffmapInPlace)(
2074
0
        rgb0_sub, rgb1_sub, params, subdiffmap));
2075
0
  }
2076
0
  JXL_RETURN_IF_ERROR(HWY_DYNAMIC_DISPATCH(ButteraugliDiffmapInPlace)(
2077
0
      rgb0, rgb1, params, diffmap));
2078
0
  if (xsize >= 15 && ysize >= 15) {
2079
0
    AddSupersampled2x(subdiffmap, 0.5, diffmap);
2080
0
  }
2081
0
  diffvalue = ButteraugliScoreFromDiffmap(diffmap, &params);
2082
0
  return true;
2083
0
}
2084
2085
0
double ButteraugliFuzzyClass(double score) {
2086
0
  static const double fuzzy_width_up = 4.8;
2087
0
  static const double fuzzy_width_down = 4.8;
2088
0
  static const double m0 = 2.0;
2089
0
  static const double scaler = 0.7777;
2090
0
  double val;
2091
0
  if (score < 1.0) {
2092
    // val in [scaler .. 2.0]
2093
0
    val = m0 / (1.0 + exp((score - 1.0) * fuzzy_width_down));
2094
0
    val -= 1.0;           // from [1 .. 2] to [0 .. 1]
2095
0
    val *= 2.0 - scaler;  // from [0 .. 1] to [0 .. 2.0 - scaler]
2096
0
    val += scaler;        // from [0 .. 2.0 - scaler] to [scaler .. 2.0]
2097
0
  } else {
2098
    // val in [0 .. scaler]
2099
0
    val = m0 / (1.0 + exp((score - 1.0) * fuzzy_width_up));
2100
0
    val *= scaler;
2101
0
  }
2102
0
  return val;
2103
0
}
2104
2105
// #define PRINT_OUT_NORMALIZATION
2106
2107
0
double ButteraugliFuzzyInverse(double seek) {
2108
0
  double pos = 0;
2109
  // NOLINTNEXTLINE(clang-analyzer-security.FloatLoopCounter)
2110
0
  for (double range = 1.0; range >= 1e-10; range *= 0.5) {
2111
0
    double cur = ButteraugliFuzzyClass(pos);
2112
0
    if (cur < seek) {
2113
0
      pos -= range;
2114
0
    } else {
2115
0
      pos += range;
2116
0
    }
2117
0
  }
2118
#ifdef PRINT_OUT_NORMALIZATION
2119
  if (seek == 1.0) {
2120
    fprintf(stderr, "Fuzzy inverse %g\n", pos);
2121
  }
2122
#endif
2123
0
  return pos;
2124
0
}
2125
2126
#ifdef PRINT_OUT_NORMALIZATION
2127
static double print_out_normalization = ButteraugliFuzzyInverse(1.0);
2128
#endif
2129
2130
namespace {
2131
2132
void ScoreToRgb(double score, double good_threshold, double bad_threshold,
2133
0
                float rgb[3]) {
2134
0
  double heatmap[12][3] = {
2135
0
      {0, 0, 0},       {0, 0, 1},
2136
0
      {0, 1, 1},       {0, 1, 0},  // Good level
2137
0
      {1, 1, 0},       {1, 0, 0},  // Bad level
2138
0
      {1, 0, 1},       {0.5, 0.5, 1.0},
2139
0
      {1.0, 0.5, 0.5},  // Pastel colors for the very bad quality range.
2140
0
      {1.0, 1.0, 0.5}, {1, 1, 1},
2141
0
      {1, 1, 1},  // Last color repeated to have a solid range of white.
2142
0
  };
2143
0
  if (score < good_threshold) {
2144
0
    score = (score / good_threshold) * 0.3;
2145
0
  } else if (score < bad_threshold) {
2146
0
    score = 0.3 +
2147
0
            (score - good_threshold) / (bad_threshold - good_threshold) * 0.15;
2148
0
  } else {
2149
0
    score = 0.45 + (score - bad_threshold) / (bad_threshold * 12) * 0.5;
2150
0
  }
2151
0
  static const int kTableSize = sizeof(heatmap) / sizeof(heatmap[0]);
2152
0
  score = jxl::Clamp1<double>(score * (kTableSize - 1), 0.0, kTableSize - 2);
2153
0
  int ix = static_cast<int>(score);
2154
0
  ix = jxl::Clamp1(ix, 0, kTableSize - 2);  // Handle NaN
2155
0
  double mix = score - ix;
2156
0
  for (int i = 0; i < 3; ++i) {
2157
0
    double v = mix * heatmap[ix + 1][i] + (1 - mix) * heatmap[ix][i];
2158
0
    rgb[i] = pow(v, 0.5);
2159
0
  }
2160
0
}
2161
2162
}  // namespace
2163
2164
StatusOr<Image3F> CreateHeatMapImage(const ImageF& distmap,
2165
                                     double good_threshold,
2166
0
                                     double bad_threshold) {
2167
0
  JxlMemoryManager* memory_manager = distmap.memory_manager();
2168
0
  JXL_ASSIGN_OR_RETURN(
2169
0
      Image3F heatmap,
2170
0
      Image3F::Create(memory_manager, distmap.xsize(), distmap.ysize()));
2171
0
  for (size_t y = 0; y < distmap.ysize(); ++y) {
2172
0
    const float* BUTTERAUGLI_RESTRICT row_distmap = distmap.ConstRow(y);
2173
0
    float* BUTTERAUGLI_RESTRICT row_h0 = heatmap.PlaneRow(0, y);
2174
0
    float* BUTTERAUGLI_RESTRICT row_h1 = heatmap.PlaneRow(1, y);
2175
0
    float* BUTTERAUGLI_RESTRICT row_h2 = heatmap.PlaneRow(2, y);
2176
0
    for (size_t x = 0; x < distmap.xsize(); ++x) {
2177
0
      const float d = row_distmap[x];
2178
0
      float rgb[3];
2179
0
      ScoreToRgb(d, good_threshold, bad_threshold, rgb);
2180
0
      row_h0[x] = rgb[0];
2181
0
      row_h1[x] = rgb[1];
2182
0
      row_h2[x] = rgb[2];
2183
0
    }
2184
0
  }
2185
0
  return heatmap;
2186
0
}
2187
2188
}  // namespace jxl
2189
#endif  // HWY_ONCE