From d3c723804a65c9567855b093943c34240ebc5438 Mon Sep 17 00:00:00 2001 From: Joshua Goins Date: Sat, 20 Jul 2024 11:20:47 -0400 Subject: [PATCH] Add initial files --- .gitignore | 15 ++ .reuse/dep5 | 11 + CMakeLists.txt | 34 +++ LICENSES/BSD-2-Clause.txt | 9 + LICENSES/CC0-1.0.txt | 121 +++++++++++ LICENSES/MIT.txt | 9 + README.md | 14 ++ autotests/CMakeLists.txt | 7 + autotests/testblurhash.cpp | 153 +++++++++++++ imageprovider/blurhashimageprovider.cpp | 97 +++++++++ imageprovider/blurhashimageprovider.h | 25 +++ src/blurhash.cpp | 272 ++++++++++++++++++++++++ src/blurhash.h | 99 +++++++++ 13 files changed, 866 insertions(+) create mode 100644 .gitignore create mode 100644 .reuse/dep5 create mode 100644 CMakeLists.txt create mode 100644 LICENSES/BSD-2-Clause.txt create mode 100644 LICENSES/CC0-1.0.txt create mode 100644 LICENSES/MIT.txt create mode 100644 README.md create mode 100644 autotests/CMakeLists.txt create mode 100644 autotests/testblurhash.cpp create mode 100644 imageprovider/blurhashimageprovider.cpp create mode 100644 imageprovider/blurhashimageprovider.h create mode 100644 src/blurhash.cpp create mode 100644 src/blurhash.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6cf5748 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +build* +.clang-format +.DS_Store +.kdev4/ +neochat.kdev4 +compile_commands.json +.cache/ +.vscode/ +kate.project.ctags.* +*.user +.flatpak-builder/ +.idea/ +cmake-build-* +src/res.generated.qrc +.qmlls.ini diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000..f5ab622 --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,11 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: QBlurHash +Upstream-Contact: Joshua Goins + +Files: .gitignore +Copyright: None +License: CC0-1.0 + +Files: README.md +Copyright: Joshua Goins +License: CC0-1.0 \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..b64f33d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Joshua Goins +# SPDX-License-Identifier: BSD-2-Clause + +cmake_minimum_required(VERSION 3.16) +project(QtBlurHash VERSION 1.0.0) + +set(KF_MIN_VERSION "6.0.0") +set(QT_MIN_VERSION 6.0) + +find_package(ECM ${KF_MIN_VERSION} REQUIRED NO_MODULE) +set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(KDEInstallDirs) +include(ECMAddTests) +include(KDECMakeSettings) +include(KDEClangFormat) +include(KDECompilerSettings NO_POLICY_SCOPE) +include(KDEGitCommitHooks) + +find_package(Qt6 REQUIRED Core Gui Quick Test) + +add_library(blurhash_qt STATIC src/blurhash.cpp src/blurhash.h imageprovider/blurhashimageprovider.h imageprovider/blurhashimageprovider.cpp) +target_include_directories(blurhash_qt PUBLIC src/) +target_link_libraries(blurhash_qt PUBLIC Qt::Core Qt::Gui Qt::Quick) + +add_subdirectory(autotests) + +file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES src/*.cpp src/*.h) +kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES}) + +kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT) \ No newline at end of file diff --git a/LICENSES/BSD-2-Clause.txt b/LICENSES/BSD-2-Clause.txt new file mode 100644 index 0000000..5f662b3 --- /dev/null +++ b/LICENSES/BSD-2-Clause.txt @@ -0,0 +1,9 @@ +Copyright (c) + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..2071b23 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..df59589 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# QtBlurHash + +A modern Qt/C++ implementation of [BlurHash](https://github.com/woltapp/blurhash). In comparison to other implementations, this uses Qt and modern C++ as much as possible. It also comes with a image provider (for use in QML) and a full test suite. + +## Usage + +Copy the source files under `src/` into your application. The test suite and image provider are optional and located under `autotests/` and `imageprovider/` respectively. + +This requires Qt6 and C++20, but it can be made to compile for C++17 with little changes. + +## Credits + +* [Nheko's Blurhash](https://github.com/Nheko-Reborn/blurhash) as inspiration and the base for the implementation. +* Tobias Fella for the original image provider. \ No newline at end of file diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt new file mode 100644 index 0000000..8ba2fb0 --- /dev/null +++ b/autotests/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Joshua Goins +# SPDX-License-Identifier: BSD-2-Clause + +ecm_add_test(testblurhash.cpp + TEST_NAME testblurhash + LINK_LIBRARIES blurhash_qt Qt::Test +) \ No newline at end of file diff --git a/autotests/testblurhash.cpp b/autotests/testblurhash.cpp new file mode 100644 index 0000000..a60b999 --- /dev/null +++ b/autotests/testblurhash.cpp @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: 2024 Joshua Goins +// SPDX-License-Identifier: MIT + +#include + +#include + +class TestBlurHash : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void encode83_data(); + void encode83(); + + void decode83_data(); + void decode83(); + + void unpackComponents(); + void packComponents(); + + void decodeMaxAC(); + void encodeMaxAC(); + + void decodeAverageColor_data(); + void decodeAverageColor(); + + void decodeAC(); + void encodeAC(); + + void decodeImage(); + void encodeImage(); +}; + +void TestBlurHash::encode83_data() +{ + QTest::addColumn("value"); + QTest::addColumn("expected"); + + QTest::addRow("encoding 1") << 0 << "0"; + QTest::addRow("encoding 2") << 21 << "L"; + QTest::addRow("encoding 3") << 30 << "U"; + QTest::addRow("encoding 4") << 34 << "Y"; + QTest::addRow("encoding 5") << 1 << "1"; +} + +void TestBlurHash::encode83() +{ + QFETCH(int, value); + QFETCH(QString, expected); + + QCOMPARE(BlurHash::encode83(value), expected); +} + +void TestBlurHash::decode83_data() +{ + QTest::addColumn("value"); + QTest::addColumn>("expected"); + + // invalid base83 characters + QTest::addRow("decoding 1") << "試し" << std::optional(std::nullopt); + QTest::addRow("decoding 2") << "(" << std::optional(std::nullopt); + + QTest::addRow("decoding 3") << "0" << std::optional(0); + QTest::addRow("decoding 4") << "L" << std::optional(21); + QTest::addRow("decoding 5") << "U" << std::optional(30); + QTest::addRow("decoding 6") << "Y" << std::optional(34); + QTest::addRow("decoding 7") << "1" << std::optional(1); +} + +void TestBlurHash::decode83() +{ + QFETCH(QString, value); + QFETCH(std::optional, expected); + + QCOMPARE(BlurHash::decode83(value), expected); +} + +void TestBlurHash::unpackComponents() +{ + QCOMPARE(BlurHash::unpackComponents(50), BlurHash::Components(6, 6)); +} + +void TestBlurHash::packComponents() +{ + QCOMPARE(BlurHash::packComponents(BlurHash::Components(6, 6)), 50); +} + +void TestBlurHash::decodeMaxAC() +{ + QCOMPARE(BlurHash::decodeMaxAC(50), 0.307229f); +} + +void TestBlurHash::encodeMaxAC() +{ + QCOMPARE(BlurHash::encodeMaxAC(0.307229f), 50); +} + +void TestBlurHash::decodeAverageColor_data() +{ + QTest::addColumn("value"); + QTest::addColumn("expected"); + + QTest::addRow("decoding 1") << 12688010 << QColor(0xffc19a8a); + QTest::addRow("decoding 2") << 9934485 << QColor(0xff979695); + QTest::addRow("decoding 3") << 8617624 << QColor(0xff837e98); + QTest::addRow("decoding 4") << 14604757 << QColor(0xffded9d5); + QTest::addRow("decoding 5") << 13742755 << QColor(0xffd1b2a3); +} + +void TestBlurHash::decodeAverageColor() +{ + QFETCH(int, value); + QFETCH(QColor, expected); + + QCOMPARE(BlurHash::decodeAverageColor(value), expected); +} + +void TestBlurHash::decodeAC() +{ + constexpr auto maxAC = 0.289157f; + QCOMPARE(BlurHash::decodeAC(0, maxAC), QColor::fromRgbF(-0.289063f, -0.289063f, -0.289063f)); +} + +void TestBlurHash::encodeAC() +{ + constexpr auto maxAC = 0.289157f; + QCOMPARE(BlurHash::encodeAC(QColor::fromRgbF(-0.289063f, -0.289063f, -0.289063f), maxAC), 0); +} + +void TestBlurHash::decodeImage() +{ + const auto image = BlurHash::decode(QStringLiteral("eBB4=;054UK$=402%s%|r^O%06#?*7RijMxGpYMzniVNT@rFN3#=Kt"), QSize(50, 50)); + QVERIFY(!image.isNull()); + + QCOMPARE(image.width(), 50); + QCOMPARE(image.height(), 50); + QCOMPARE(image.pixelColor(0, 0), QColor(0xff005f00)); + QCOMPARE(image.pixelColor(30, 30), QColor(0xff99b76d)); +} + +void TestBlurHash::encodeImage() +{ + auto image = QImage(QSize(360, 200), QImage::Format_RGB888); + image.fill(Qt::black); + + const auto encodedString = BlurHash::encode(image, 4, 3); + QCOMPARE(encodedString.size(), 28); + QCOMPARE(encodedString, QStringLiteral("L00000fQfQfQfQfQfQfQfQfQfQfQ")); +} + +QTEST_GUILESS_MAIN(TestBlurHash) +#include "testblurhash.moc" \ No newline at end of file diff --git a/imageprovider/blurhashimageprovider.cpp b/imageprovider/blurhashimageprovider.cpp new file mode 100644 index 0000000..b1c85eb --- /dev/null +++ b/imageprovider/blurhashimageprovider.cpp @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2024 Joshua Goins +// SPDX-License-Identifier: MIT + +#include "blurhashimageprovider.h" + +#include "blurhash.h" + +/* + * Qt unfortunately re-encodes the base83 string in QML. + * The only special ASCII characters used in the blurhash base83 string are: + * #$%*+,-.:;=?@[]^_{|}~ + * QUrl::fromPercentEncoding is too greedy, and spits out invalid characters + * for parts of valid base83 like %14. + */ +// clang-format off +static const QMap knownEncodings = { + {QLatin1String("%23A"), QLatin1String(":")}, + {QLatin1String("%3F"), QLatin1String("?")}, + {QLatin1String("%23"), QLatin1String("#")}, + {QLatin1String("%5B"), QLatin1String("[")}, + {QLatin1String("%5D"), QLatin1String("]")}, + {QLatin1String("%40"), QLatin1String("@")}, + {QLatin1String("%24"), QLatin1String("$")}, + {QLatin1String("%2A"), QLatin1String("*")}, + {QLatin1String("%2B"), QLatin1String("+")}, + {QLatin1String("%2C"), QLatin1String(",")}, + {QLatin1String("%2D"), QLatin1String("-")}, + {QLatin1String("%2E"), QLatin1String(".")}, + {QLatin1String("%3D"), QLatin1String("=")}, + {QLatin1String("%25"), QLatin1String("%")}, + {QLatin1String("%5E"), QLatin1String("^")}, + {QLatin1String("%7C"), QLatin1String("|")}, + {QLatin1String("%7B"), QLatin1String("{")}, + {QLatin1String("%7D"), QLatin1String("}")}, + {QLatin1String("%7E"), QLatin1String("~")}, +}; +// clang-format on + +class AsyncImageResponseRunnable : public QObject, public QRunnable +{ + Q_OBJECT + +Q_SIGNALS: + void done(QImage image); + +public: + AsyncImageResponseRunnable(const QString &id, const QSize &requestedSize) + : m_id(id) + , m_requestedSize(requestedSize) + { + if (m_requestedSize.width() == -1) + m_requestedSize.setWidth(64); + if (m_requestedSize.height() == -1) + m_requestedSize.setHeight(64); + } + + void run() override + { + if (m_id.isEmpty()) + return; + + QString decodedId = m_id; + for (auto i = knownEncodings.constBegin(); i != knownEncodings.constEnd(); ++i) + decodedId.replace(i.key(), i.value()); + + Q_EMIT done(BlurHash::decode(decodedId, m_requestedSize)); + } + +private: + QString m_id; + QSize m_requestedSize; +}; + +AsyncImageResponse::AsyncImageResponse(const QString &id, const QSize &requestedSize, QThreadPool *pool) +{ + const auto runnable = new AsyncImageResponseRunnable(id, requestedSize); + connect(runnable, &AsyncImageResponseRunnable::done, this, &AsyncImageResponse::handleDone); + pool->start(runnable); +} + +void AsyncImageResponse::handleDone(QImage image) +{ + m_image = std::move(image); + Q_EMIT finished(); +} + +QQuickTextureFactory *AsyncImageResponse::textureFactory() const +{ + return QQuickTextureFactory::textureFactoryForImage(m_image); +} + +QQuickImageResponse *BlurHashImageProvider::requestImageResponse(const QString &id, const QSize &requestedSize) +{ + return new AsyncImageResponse(id, requestedSize, &pool); +} + +#include "blurhashimageprovider.moc" diff --git a/imageprovider/blurhashimageprovider.h b/imageprovider/blurhashimageprovider.h new file mode 100644 index 0000000..64ca4e6 --- /dev/null +++ b/imageprovider/blurhashimageprovider.h @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2024 Joshua Goins +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +class AsyncImageResponse final : public QQuickImageResponse +{ +public: + AsyncImageResponse(const QString &id, const QSize &requestedSize, QThreadPool *pool); + void handleDone(QImage image); + QQuickTextureFactory *textureFactory() const override; + QImage m_image; +}; + +class BlurHashImageProvider : public QQuickAsyncImageProvider +{ +public: + QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override; + +private: + QThreadPool pool; +}; diff --git a/src/blurhash.cpp b/src/blurhash.cpp new file mode 100644 index 0000000..69a9cdc --- /dev/null +++ b/src/blurhash.cpp @@ -0,0 +1,272 @@ +// SPDX-FileCopyrightText: 2024 Joshua Goins +// SPDX-License-Identifier: MIT + +#include "blurhash.h" + +#include + +// From https://github.com/woltapp/blurhash/blob/master/Algorithm.md#base-83 +const static QString b83Characters{QStringLiteral("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~")}; + +const static auto toLinearSRGB = QColorSpace(QColorSpace::SRgb).transformationToColorSpace(QColorSpace::SRgbLinear); +const static auto fromLinearSRGB = QColorSpace(QColorSpace::SRgbLinear).transformationToColorSpace(QColorSpace::SRgb); + +QImage BlurHash::decode(const QString &blurhash, const QSize &size) +{ + // 10 is the minimum length of a blurhash string + if (blurhash.length() < 10) + return {}; + + // First character is the number of components + const auto components83 = decode83(blurhash.first(1)); + if (!components83.has_value()) + return {}; + + const auto components = unpackComponents(*components83); + const auto minimumSize = 1 + 1 + 4 + (components.x * components.y - 1) * 2; + if (components.x < 1 || components.y < 1 || blurhash.size() != minimumSize) + return {}; + + // Second character is the maximum AC component value + const auto maxAC83 = decode83(blurhash.mid(1, 1)); + if (!maxAC83.has_value()) + return {}; + + const auto maxAC = decodeMaxAC(*maxAC83); + + // Third character onward is the average color of the image + const auto averageColor83 = decode83(blurhash.mid(2, 4)); + if (!averageColor83.has_value()) + return {}; + + const auto averageColor = toLinearSRGB.map(decodeAverageColor(*averageColor83)); + + QList values = {averageColor}; + + // Iterate through the rest of the string for the color values + // Each AC component is two characters each + for (qsizetype c = 6; c < blurhash.size(); c += 2) { + const auto acComponent83 = decode83(blurhash.mid(c, 2)); + if (!acComponent83.has_value()) + return {}; + + values.append(decodeAC(*acComponent83, maxAC)); + } + + QImage image(size, QImage::Format_RGB888); + image.setColorSpace(QColorSpace::SRgb); + + const auto basisX = calculateWeights(size.width(), components.x); + const auto basisY = calculateWeights(size.height(), components.y); + + for (int y = 0; y < size.height(); y++) { + for (int x = 0; x < size.width(); x++) { + float linearSumR = 0.0f; + float linearSumG = 0.0f; + float linearSumB = 0.0f; + + for (int nx = 0; nx < components.x; nx++) { + for (int ny = 0; ny < components.y; ny++) { + const float basis = basisX[x * components.x + nx] * basisY[y * components.y + ny]; + + linearSumR += values[nx + ny * components.x].redF() * basis; + linearSumG += values[nx + ny * components.x].greenF() * basis; + linearSumB += values[nx + ny * components.x].blueF() * basis; + } + } + + auto linearColor = QColor::fromRgbF(linearSumR, linearSumG, linearSumB); + image.setPixelColor(x, y, fromLinearSRGB.map(linearColor)); + } + } + + return image; +} + +QString BlurHash::encode(const QImage &image, const int componentsX, const int componentsY) +{ + Q_ASSERT(componentsX >= 1 && componentsX <= 9); + Q_ASSERT(componentsY >= 1 && componentsY <= 9); + + if (image.isNull()) + return {}; + + const auto basisX = calculateWeights(image.width(), componentsX); + const auto basisY = calculateWeights(image.height(), componentsY); + + QList factors; + factors.resize(componentsX * componentsY); + + const float normalizationFactor = 1.0f / static_cast(image.width()); + + for (int y = 0; y < image.height(); y++) { + for (int x = 0; x < image.width(); x++) { + const QColor srgbColor = image.pixelColor(x, y); + const QColor linearColor = toLinearSRGB.map(srgbColor); + + float linearR = linearColor.redF(); + float linearG = linearColor.greenF(); + float linearB = linearColor.blueF(); + + linearR *= normalizationFactor; + linearG *= normalizationFactor; + linearB *= normalizationFactor; + + for (int ny = 0; ny < componentsY; ny++) { + for (int nx = 0; nx < componentsX; nx++) { + const float basis = basisX[x * componentsX + nx] * basisY[y * componentsY + ny]; + + float factorR = factors[ny * componentsX + nx].redF(); + float factorG = factors[ny * componentsX + nx].greenF(); + float factorB = factors[ny * componentsX + nx].blueF(); + + factors[ny * componentsX + nx] = QColor::fromRgbF(factorR + linearR * basis, factorG + linearG * basis, factorB + linearB * basis); + } + } + } + } + + // Scale by normalization. Half the scaling is done in the previous loop to prevent going + // too far outside the float range. + for (qsizetype i = 0; i < factors.size(); i++) { + float normalisation = (i == 0) ? 1 : 2; + float scale = normalisation / static_cast(image.height()); + + float factorR = factors[i].redF() * scale; + float factorG = factors[i].greenF() * scale; + float factorB = factors[i].blueF() * scale; + + factors[i] = QColor::fromRgbF(factorR, factorG, factorB); + } + + const auto averageColor = factors.takeFirst(); + + QString encodedString; + encodedString.append(encode83(packComponents(Components(componentsX, componentsY))).rightJustified(1, QLatin1Char('0'))); + + float maximumValue; + if (!factors.empty()) { + float actualMaximumValue = 0; + for (auto ac : factors) { + actualMaximumValue = std::max({ + std::abs(ac.redF()), + std::abs(ac.greenF()), + std::abs(ac.blueF()), + actualMaximumValue, + }); + } + + int quantisedMaximumValue = encodeMaxAC(actualMaximumValue); + maximumValue = (static_cast(quantisedMaximumValue) + 1) / 166; + encodedString.append(encode83(quantisedMaximumValue).leftJustified(1, QLatin1Char('0'))); + } else { + maximumValue = 1; + encodedString.append(encode83(0).leftJustified(1, QLatin1Char('0'))); + } + + encodedString.append(encode83(encodeAverageColor(fromLinearSRGB.map(averageColor))).leftJustified(4, QLatin1Char('0'))); + + for (auto ac : factors) + encodedString.append(encode83(encodeAC(ac, maximumValue)).leftJustified(2, QLatin1Char('0'))); + + return encodedString; +} + +std::optional BlurHash::decode83(const QString &encodedString) +{ + int temp = 0; + for (const QChar c : encodedString) { + const auto index = b83Characters.indexOf(c); + if (index == -1) + return std::nullopt; + + temp = temp * 83 + static_cast(index); + } + + return temp; +} + +QString BlurHash::encode83(int value) +{ + QString buffer; + + do { + buffer += b83Characters[value % 83]; + } while ((value = value / 83)); + + std::ranges::reverse(buffer); + + return buffer; +} + +BlurHash::Components BlurHash::unpackComponents(const int packedComponents) +{ + return {packedComponents % 9 + 1, packedComponents / 9 + 1}; +} + +int BlurHash::packComponents(const Components &components) +{ + return (components.x - 1) + (components.y - 1) * 9; +} + +float BlurHash::decodeMaxAC(const int value) +{ + return static_cast(value + 1) / 166.f; +} + +int BlurHash::encodeMaxAC(const float value) +{ + return std::clamp(static_cast(value * 166 - 0.5f), 0, 82); +} + +QColor BlurHash::decodeAverageColor(const int encodedValue) +{ + const int intR = encodedValue >> 16; + const int intG = (encodedValue >> 8) & 255; + const int intB = encodedValue & 255; + + return QColor::fromRgb(intR, intG, intB); +} + +int BlurHash::encodeAverageColor(const QColor &averageColor) +{ + return (averageColor.red() << 16) + (averageColor.green() << 8) + averageColor.blue(); +} + +float BlurHash::signPow(const float value, const float exp) +{ + return std::copysign(std::pow(std::abs(value), exp), value); +} + +QColor BlurHash::decodeAC(const int value, const float maxAC) +{ + const auto quantR = value / (19 * 19); + const auto quantG = (value / 19) % 19; + const auto quantB = value % 19; + + return QColor::fromRgbF(signPow((static_cast(quantR) - 9) / 9, 2) * maxAC, + signPow((static_cast(quantG) - 9) / 9, 2) * maxAC, + signPow((static_cast(quantB) - 9) / 9, 2) * maxAC); +} + +int BlurHash::encodeAC(const QColor value, const float maxAC) +{ + const auto quantR = static_cast(std::max(0., std::min(18., std::floor(signPow(value.redF() / maxAC, 0.5) * 9 + 9.5)))); + const auto quantG = static_cast(std::max(0., std::min(18., std::floor(signPow(value.greenF() / maxAC, 0.5) * 9 + 9.5)))); + const auto quantB = static_cast(std::max(0., std::min(18., std::floor(signPow(value.blueF() / maxAC, 0.5) * 9 + 9.5)))); + + return quantR * 19 * 19 + quantG * 19 + quantB; +} + +QList BlurHash::calculateWeights(const qsizetype dimension, const qsizetype components) +{ + QList bases(dimension * components, 0.0f); + + const auto scale = static_cast(std::numbers::pi) / static_cast(dimension); + for (qsizetype x = 0; x < dimension; x++) { + for (qsizetype nx = 0; nx < components; nx++) { + bases[x * components + nx] = std::cos(scale * static_cast(nx * x)); + } + } + return bases; +} diff --git a/src/blurhash.h b/src/blurhash.h new file mode 100644 index 0000000..9e3575d --- /dev/null +++ b/src/blurhash.h @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2024 Joshua Goins +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +/** + * @brief Encodes and decodes image to and from the BlurHash format. See https://blurha.sh/. + */ +class BlurHash +{ +public: + /** Decodes the @p blurhash string creating an image of @p size. + * @note Returns a null image if decoding failed. + */ + static QImage decode(const QString &blurhash, const QSize &size); + + /** Encodes the @p image and returns a blurhash string. + * @param image A non-null image. + * @param componentsX the number of components X-wise. Must be between 1 and 9. + * @param componentsY the number of components Y-wise. Must be between 1 and 9. + * @note Returns an empty string if it failed to encode the image. + */ + static QString encode(const QImage &image, int componentsX = 4, int componentsY = 4); + +protected: + struct Components { + int x, y; + + bool operator==(const Components &other) const + { + return x == other.x && y == other.y; + } + }; + + /** + * @brief Decodes a base 83 string to it's integer value. Returns std::nullopt if there's an invalid character in the blurhash. + */ + static std::optional decode83(const QString &encodedString); + + /** + * @brief Encodes an integer to it's base 83 representation. + */ + static QString encode83(int value); + + /** + * @brief Unpacks an integer to it's @c Components value. + */ + static Components unpackComponents(int packedComponents); + + /** + * @brief Packs @c Components to it's integer representation. + */ + static int packComponents(const Components &components); + + /** + * @brief Decodes a encoded max AC component value. + */ + static float decodeMaxAC(int value); + + /** + * @brief Encodes the maximum AC component value to an integer repsentation. + */ + static int encodeMaxAC(float value); + + /** + * @brief Decodes the average color from the encoded RGB value. + * @note This returns the color as SRGB. + */ + static QColor decodeAverageColor(int encodedValue); + + /** + * @brief Encodes the average color into it's integer representation. + */ + static int encodeAverageColor(const QColor &averageColor); + + /** + * @brief Calls pow() with @p exp on @p value, while keeping the sign. + */ + static float signPow(float value, float exp); + + /** + * @brief Decodes a encoded AC component value. + */ + static QColor decodeAC(int value, float maxAC); + + /** + * @brief Encodes the AC component into it's integer representation. + */ + static int encodeAC(QColor value, float maxAC); + + /** + * @brief Calculates the weighted sum for @p dimension across @p components. + */ + static QList calculateWeights(qsizetype dimension, qsizetype components); + + friend class TestBlurHash; +}; \ No newline at end of file