Debian Codegraph @

third_party/blurhash/blurhash.cpp

raw symbols SCIP
1 #include "blurhash.hpp"
2
3 #include <algorithm>
4 #include <array>
5 #include <cassert>
6 #include <cmath>
7 #include <numbers>
8 #include <stdexcept>
9
10 #ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
11 #if __has_include(<doctest.h>)
12 #include <doctest.h>
13 #else
14 #include <doctest/doctest.h>
15 #endif
16 #endif
17
18 using namespace std::literals;
19
20 namespace {
21 constexpr std::array<char, 84> int_to_b83{
22 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"};
23
24 std::string
25 leftPad(std::string str, size_t len)
26 {
27 if (str.size() >= len)
28 return str;
29 return str.insert(0, len - str.size(), '0');
30 }
31
32 constexpr std::array<int, 255> b83_to_int = []() constexpr
33 {
34 std::array<int, 255> a{};
35
36 for (auto &e : a)
37 e = -1;
38
39 for (int i = 0; i < 83; i++) {
40 a[static_cast<unsigned char>(int_to_b83[i])] = i;
41 }
42
43 return a;
44 }
45 ();
46
47 std::string
48 encode83(int value)
49 {
50 std::string buffer;
51
52 do {
53 buffer += int_to_b83[value % 83];
54 } while ((value = value / 83));
55
56 std::reverse(buffer.begin(), buffer.end());
57 return buffer;
58 }
59
60 struct Components
61 {
62 int x, y;
63 };
64
65 int
66 packComponents(const Components &c) noexcept
67 {
68 return (c.x - 1) + (c.y - 1) * 9;
69 }
70
71 Components
72 unpackComponents(int c) noexcept
73 {
74 return {c % 9 + 1, c / 9 + 1};
75 }
76
77 int
78 decode83(std::string_view value)
79 {
80 int temp = 0;
81
82 for (char c : value)
83 if (b83_to_int[static_cast<unsigned char>(c)] < 0)
84 throw std::invalid_argument("invalid character in blurhash");
85
86 for (char c : value)
87 temp = temp * 83 + b83_to_int[static_cast<unsigned char>(c)];
88 return temp;
89 }
90
91 float
92 decodeMaxAC(int quantizedMaxAC) noexcept
93 {
94 return static_cast<float>(quantizedMaxAC + 1) / 166.f;
95 }
96
97 float
98 decodeMaxAC(std::string_view maxAC)
99 {
100 assert(maxAC.size() == 1);
101 return decodeMaxAC(decode83(maxAC));
102 }
103
104 int
105 encodeMaxAC(float maxAC) noexcept
106 {
107 return std::max(0, std::min(82, int(maxAC * 166 - 0.5f)));
108 }
109
110 float
111 srgbToLinear(int value) noexcept
112 {
113 auto srgbToLinearF = [](float x) {
114 if (x <= 0.0f)
115 return 0.0f;
116 else if (x >= 1.0f)
117 return 1.0f;
118 else if (x < 0.04045f)
119 return x / 12.92f;
120 else
121 return std::pow((x + 0.055f) / 1.055f, 2.4f);
122 };
123
124 return srgbToLinearF(static_cast<float>(value) / 255.f);
125 }
126
127 int
128 linearToSrgb(float value) noexcept
129 {
130 auto linearToSrgbF = [](float x) -> float {
131 if (x <= 0.0f)
132 return 0.0f;
133 else if (x >= 1.0f)
134 return 1.0f;
135 else if (x < 0.0031308f)
136 return x * 12.92f;
137 else
138 return std::pow(x, 1.0f / 2.4f) * 1.055f - 0.055f;
139 };
140
141 return int(linearToSrgbF(value) * 255.f + 0.5f);
142 }
143
144 struct Color
145 {
146 float r, g, b;
147
148 Color &operator*=(float scale)
149 {
150 r *= scale;
151 g *= scale;
152 b *= scale;
153 return *this;
154 }
155 friend Color operator*(Color lhs, float rhs) { return (lhs *= rhs); }
156 Color &operator/=(float scale)
157 {
158 r /= scale;
159 g /= scale;
160 b /= scale;
161 return *this;
162 }
163 Color &operator+=(const Color &rhs)
164 {
165 r += rhs.r;
166 g += rhs.g;
167 b += rhs.b;
168 return *this;
169 }
170 };
171
172 Color
173 decodeDC(int value)
174 {
175 const int intR = value >> 16;
176 const int intG = (value >> 8) & 255;
177 const int intB = value & 255;
178 return {srgbToLinear(intR), srgbToLinear(intG), srgbToLinear(intB)};
179 }
180
181 Color
182 decodeDC(std::string_view value)
183 {
184 assert(value.size() == 4);
185 return decodeDC(decode83(value));
186 }
187
188 int
189 encodeDC(const Color &c)
190 {
191 return (linearToSrgb(c.r) << 16) + (linearToSrgb(c.g) << 8) + linearToSrgb(c.b);
192 }
193
194 float
195 signPow(float value, float exp)
196 {
197 return std::copysign(std::pow(std::abs(value), exp), value);
198 }
199
200 int
201 encodeAC(const Color &c, float maximumValue)
202 {
203 auto quantR =
204 int(std::max(0., std::min(18., std::floor(signPow(c.r / maximumValue, 0.5) * 9 + 9.5))));
205 auto quantG =
206 int(std::max(0., std::min(18., std::floor(signPow(c.g / maximumValue, 0.5) * 9 + 9.5))));
207 auto quantB =
208 int(std::max(0., std::min(18., std::floor(signPow(c.b / maximumValue, 0.5) * 9 + 9.5))));
209
210 return quantR * 19 * 19 + quantG * 19 + quantB;
211 }
212
213 Color
214 decodeAC(int value, float maximumValue)
215 {
216 auto quantR = value / (19 * 19);
217 auto quantG = (value / 19) % 19;
218 auto quantB = value % 19;
219
220 return {signPow((float(quantR) - 9) / 9, 2) * maximumValue,
221 signPow((float(quantG) - 9) / 9, 2) * maximumValue,
222 signPow((float(quantB) - 9) / 9, 2) * maximumValue};
223 }
224
225 Color
226 decodeAC(std::string_view value, float maximumValue)
227 {
228 return decodeAC(decode83(value), maximumValue);
229 }
230
231 std::vector<float>
232 bases_for(size_t dimension, size_t components)
233 {
234 std::vector<float> bases(dimension * components, 0.f);
235 auto scale = std::numbers::pi_v<float> / float(dimension);
236 for (size_t x = 0; x < dimension; x++) {
237 for (size_t nx = 0; nx < size_t(components); nx++) {
238 bases[x * components + nx] = std::cos(scale * float(nx * x));
239 }
240 }
241 return bases;
242 }
243 }
244
245 namespace blurhash {
246 Image
247 decode(std::string_view blurhash, size_t width, size_t height, size_t bytesPerPixel) noexcept
248 {
249 Image i{};
250
251 if (blurhash.size() < 10)
252 return i;
253
254 Components components{};
255 std::vector<Color> values;
256 values.reserve(blurhash.size() / 2);
257 try {
258 components = unpackComponents(decode83(blurhash.substr(0, 1)));
259
260 if (components.x < 1 || components.y < 1 ||
261 blurhash.size() != size_t(1 + 1 + 4 + (components.x * components.y - 1) * 2))
262 return {};
263
264 auto maxAC = decodeMaxAC(blurhash.substr(1, 1));
265 Color average = decodeDC(blurhash.substr(2, 4));
266
267 values.push_back(average);
268 for (size_t c = 6; c < blurhash.size(); c += 2)
269 values.push_back(decodeAC(blurhash.substr(c, 2), maxAC));
270 } catch (std::invalid_argument &) {
271 return {};
272 }
273
274 i.image = decltype(i.image)(height * width * bytesPerPixel, 255);
275
276 std::vector<float> basis_x = bases_for(width, components.x);
277 std::vector<float> basis_y = bases_for(height, components.y);
278
279 for (size_t y = 0; y < height; y++) {
280 for (size_t x = 0; x < width; x++) {
281 Color c{};
282
283 for (size_t nx = 0; nx < size_t(components.x); nx++) {
284 for (size_t ny = 0; ny < size_t(components.y); ny++) {
285 float basis = basis_x[x * components.x + nx] *
286 basis_y[y * components.y + ny];
287 c += values[nx + ny * components.x] * basis;
288 }
289 }
290
291 i.image[(y * width + x) * bytesPerPixel + 0] =
292 static_cast<unsigned char>(linearToSrgb(c.r));
293 i.image[(y * width + x) * bytesPerPixel + 1] =
294 static_cast<unsigned char>(linearToSrgb(c.g));
295 i.image[(y * width + x) * bytesPerPixel + 2] =
296 static_cast<unsigned char>(linearToSrgb(c.b));
297 }
298 }
299
300 i.height = height;
301 i.width = width;
302
303 return i;
304 }
305
306 std::string
307 encode(unsigned char *image, size_t width, size_t height, int components_x, int components_y)
308 {
309 if (width < 1 || height < 1 || components_x < 1 || components_x > 9 || components_y < 1 ||
310 components_y > 9 || !image)
311 return "";
312
313 std::vector<float> basis_x = bases_for(width, components_x);
314 std::vector<float> basis_y = bases_for(height, components_y);
315
316 std::vector<Color> factors(components_x * components_y, Color{});
317 for (size_t y = 0; y < height; y++) {
318 for (size_t x = 0; x < width; x++) {
319 Color linear{srgbToLinear(image[3 * x + 0 + y * width * 3]),
320 srgbToLinear(image[3 * x + 1 + y * width * 3]),
321 srgbToLinear(image[3 * x + 2 + y * width * 3])};
322
323 // other half of normalization.
324 linear *= 1.f / static_cast<float>(width);
325
326 for (size_t ny = 0; ny < size_t(components_y); ny++) {
327 for (size_t nx = 0; nx < size_t(components_x); nx++) {
328 float basis = basis_x[x * size_t(components_x) + nx] *
329 basis_y[y * size_t(components_y) + ny];
330 factors[ny * components_x + nx] += linear * basis;
331 }
332 }
333 }
334 }
335
336 // scale by normalization. Half the scaling is done in the previous loop to prevent going
337 // too far outside the float range.
338 for (size_t i = 0; i < factors.size(); i++) {
339 float normalisation = (i == 0) ? 1 : 2;
340 float scale = normalisation / static_cast<float>(height);
341 factors[i] *= scale;
342 }
343
344 assert(factors.size() > 0);
345
346 auto dc = factors.front();
347 factors.erase(factors.begin());
348
349 std::string h;
350
351 h += leftPad(encode83(packComponents({components_x, components_y})), 1);
352
353 float maximumValue;
354 if (!factors.empty()) {
355 float actualMaximumValue = 0;
356 for (auto ac : factors) {
357 actualMaximumValue = std::max({
358 std::abs(ac.r),
359 std::abs(ac.g),
360 std::abs(ac.b),
361 actualMaximumValue,
362 });
363 }
364
365 int quantisedMaximumValue = encodeMaxAC(actualMaximumValue);
366 maximumValue = ((float)quantisedMaximumValue + 1) / 166;
367 h += leftPad(encode83(quantisedMaximumValue), 1);
368 } else {
369 maximumValue = 1;
370 h += leftPad(encode83(0), 1);
371 }
372
373 h += leftPad(encode83(encodeDC(dc)), 4);
374
375 for (auto ac : factors)
376 h += leftPad(encode83(encodeAC(ac, maximumValue)), 2);
377
378 return h;
379 }
380 }
381
382 #ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
383 TEST_CASE("component packing")
384 {
385 for (int i = 0; i < 9 * 9; i++)
386 CHECK(packComponents(unpackComponents(i)) == i);
387 }
388
389 TEST_CASE("encode83")
390 {
391 CHECK(encode83(0) == "0");
392
393 CHECK(encode83(packComponents({4, 3})) == "L");
394 CHECK(encode83(packComponents({4, 4})) == "U");
395 CHECK(encode83(packComponents({8, 4})) == "Y");
396 CHECK(encode83(packComponents({2, 1})) == "1");
397 }
398
399 TEST_CASE("decode83")
400 {
401 CHECK(packComponents({4, 3}) == decode83("L"));
402 CHECK(packComponents({4, 4}) == decode83("U"));
403 CHECK(packComponents({8, 4}) == decode83("Y"));
404 CHECK(packComponents({2, 1}) == decode83("1"));
405 }
406
407 TEST_CASE("maxAC")
408 {
409 for (int i = 0; i < 83; i++)
410 CHECK(encodeMaxAC(decodeMaxAC(i)) == i);
411
412 CHECK(std::abs(decodeMaxAC("l"sv) - 0.289157f) < 0.00001f);
413 }
414
415 TEST_CASE("DC")
416 {
417 CHECK(encode83(encodeDC(decodeDC("MF%n"))) == "MF%n"sv);
418 CHECK(encode83(encodeDC(decodeDC("HV6n"))) == "HV6n"sv);
419 CHECK(encode83(encodeDC(decodeDC("F5]+"))) == "F5]+"sv);
420 CHECK(encode83(encodeDC(decodeDC("Pj0^"))) == "Pj0^"sv);
421 CHECK(encode83(encodeDC(decodeDC("O2?U"))) == "O2?U"sv);
422 }
423
424 TEST_CASE("AC")
425 {
426 auto h = "00%#MwS|WCWEM{R*bbWBbH"sv;
427 for (size_t i = 0; i < h.size(); i += 2) {
428 auto s = h.substr(i, 2);
429 const auto maxAC = 0.289157f;
430 CHECK(leftPad(encode83(encodeAC(decodeAC(decode83(s), maxAC), maxAC)), 2) == s);
431 }
432 }
433
434 TEST_CASE("decode")
435 {
436 blurhash::Image i1 = blurhash::decode("LEHV6nWB2yk8pyoJadR*.7kCMdnj", 360, 200);
437 CHECK(i1.width == 360);
438 CHECK(i1.height == 200);
439 CHECK(i1.image.size() == i1.height * i1.width * 3);
440 CHECK(i1.image[0] == 135);
441 CHECK(i1.image[1] == 164);
442 CHECK(i1.image[2] == 177);
443 CHECK(i1.image[10000] == 173);
444 CHECK(i1.image[10001] == 176);
445 CHECK(i1.image[10002] == 163);
446 // stbi_write_bmp("test.bmp", i1.width, i1.height, 3, (void *)i1.image.data());
447
448 i1 = blurhash::decode("LGF5]+Yk^6#M@-5c,1J5@[or[Q6.", 360, 200);
449 CHECK(i1.width == 360);
450 CHECK(i1.height == 200);
451 CHECK(i1.image.size() == i1.height * i1.width * 3);
452 // stbi_write_bmp("test2.bmp", i1.width, i1.height, 3, (void *)i1.image.data());
453
454 // invalid inputs
455 i1 = blurhash::decode(" LGF5]+Yk^6#M@-5c,1J5@[or[Q6.", 360, 200);
456 CHECK(i1.width == 0);
457 CHECK(i1.height == 0);
458 CHECK(i1.image.size() == 0);
459 i1 = blurhash::decode(" LGF5]+Yk^6#M@-5c,1J5@[or[Q6.", 360, 200);
460 CHECK(i1.width == 0);
461 CHECK(i1.height == 0);
462 CHECK(i1.image.size() == 0);
463
464 i1 = blurhash::decode("LGF5]+Yk^6# M@-5c,1J5@[or[Q6.", 360, 200);
465 CHECK(i1.width == 0);
466 CHECK(i1.height == 0);
467 CHECK(i1.image.size() == 0);
468 i1 = blurhash::decode("LGF5]+Yk^6# M@-5c,1J5@[or[Q6.", 360, 200);
469 CHECK(i1.width == 0);
470 CHECK(i1.height == 0);
471 CHECK(i1.image.size() == 0);
472
473 i1 = blurhash::decode("LGF5]+Yk^6# @-5c,1J5@[or[Q6.", 360, 200);
474 CHECK(i1.width == 0);
475 CHECK(i1.height == 0);
476 CHECK(i1.image.size() == 0);
477 i1 = blurhash::decode(" GF5]+Yk^6#M@-5c,1J5@[or[Q6.", 360, 200);
478 CHECK(i1.width == 0);
479 CHECK(i1.height == 0);
480 CHECK(i1.image.size() == 0);
481 }
482
483 TEST_CASE("encode")
484 {
485 CHECK(blurhash::encode(nullptr, 360, 200, 4, 3) == "");
486
487 std::vector<unsigned char> black(360 * 200 * 3, 0);
488 CHECK(blurhash::encode(black.data(), 0, 200, 4, 3) == "");
489 CHECK(blurhash::encode(black.data(), 360, 0, 4, 3) == "");
490 CHECK(blurhash::encode(black.data(), 360, 200, 0, 3) == "");
491 CHECK(blurhash::encode(black.data(), 360, 200, 4, 0) == "");
492 CHECK(blurhash::encode(black.data(), 360, 200, 4, 3) == "L00000fQfQfQfQfQfQfQfQfQfQfQ");
493 }
494 #endif