Move blurhash to its own module.

This commit is contained in:
Alex Hart
2026-02-02 12:17:16 -04:00
committed by GitHub
parent 35190ebb63
commit 2aa0b3700f
39 changed files with 142 additions and 181 deletions

View File

@@ -0,0 +1,8 @@
plugins {
id("signal-library")
id("kotlin-parcelize")
}
android {
namespace = "org.signal.blurhash"
}

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>

View File

@@ -0,0 +1,73 @@
/**
* Source: https://github.com/hsch/blurhash-java
*
* Copyright (c) 2019 Hendrik Schnepel
*
* 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.
*/
package org.signal.blurhash;
import androidx.annotation.Nullable;
final class Base83 {
private static final int MAX_LENGTH = 90;
private static final char[]ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~".toCharArray();
private static int indexOf(char[] a, char key) {
for (int i = 0; i < a.length; i++) {
if (a[i] == key) {
return i;
}
}
return -1;
}
static void encode(long value, int length, char[] buffer, int offset) {
int exp = 1;
for (int i = 1; i <= length; i++, exp *= 83) {
int digit = (int)(value / exp % 83);
buffer[offset + length - i] = ALPHABET[digit];
}
}
static int decode(String value, int fromInclusive, int toExclusive) {
int result = 0;
char[] chars = value.toCharArray();
for (int i = fromInclusive; i < toExclusive; i++) {
result = result * 83 + indexOf(ALPHABET, chars[i]);
}
return result;
}
static boolean isValid(@Nullable String value) {
if (value == null) return false;
final int length = value.length();
if (length == 0 || length > MAX_LENGTH) return false;
for (int i = 0; i < length; i++) {
if (indexOf(ALPHABET, value.charAt(i)) == -1) return false;
}
return true;
}
private Base83() {
}
}

View File

@@ -0,0 +1,20 @@
package org.signal.blurhash
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* A BlurHash is a compact string representation of a blurred image that we can use to show fast
* image previews.
*/
@Parcelize
data class BlurHash(val hash: String) : Parcelable {
companion object {
fun parseOrNull(hash: String?): BlurHash? {
if (Base83.isValid(hash)) {
return BlurHash(hash!!)
}
return null
}
}
}

View File

@@ -0,0 +1,113 @@
/**
* Source: https://github.com/woltapp/blurhash
*
* Copyright (c) 2018 Wolt Enterprises
*
* 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.
*/
package org.signal.blurhash;
import android.graphics.Bitmap;
import android.graphics.Color;
import androidx.annotation.Nullable;
import static org.signal.blurhash.BlurHashUtil.linearTosRGB;
import static org.signal.blurhash.BlurHashUtil.sRGBToLinear;
import static org.signal.blurhash.BlurHashUtil.signPow;
public class BlurHashDecoder {
public static @Nullable Bitmap decode(@Nullable String blurHash, int width, int height) {
return decode(blurHash, width, height, 1f);
}
static @Nullable Bitmap decode(@Nullable String blurHash, int width, int height, double punch) {
if (blurHash == null || blurHash.length() < 6) {
return null;
}
int numCompEnc = Base83.decode(blurHash, 0, 1);
int numCompX = (numCompEnc % 9) + 1;
int numCompY = (numCompEnc / 9) + 1;
if (blurHash.length() != 4 + 2 * numCompX * numCompY) {
return null;
}
int maxAcEnc = Base83.decode(blurHash, 1, 2);
double maxAc = (maxAcEnc + 1) / 166f;
double[][] colors = new double[numCompX * numCompY][];
for (int i = 0; i < colors.length; i++) {
if (i == 0) {
int colorEnc = Base83.decode(blurHash, 2, 6);
colors[i] = decodeDc(colorEnc);
} else {
int from = 4 + i * 2;
int colorEnc = Base83.decode(blurHash, from, from + 2);
colors[i] = decodeAc(colorEnc, maxAc * punch);
}
}
return composeBitmap(width, height, numCompX, numCompY, colors);
}
private static double[] decodeDc(int colorEnc) {
int r = colorEnc >> 16;
int g = (colorEnc >> 8) & 255;
int b = colorEnc & 255;
return new double[] {sRGBToLinear(r),
sRGBToLinear(g),
sRGBToLinear(b)};
}
private static double[] decodeAc(int value, double maxAc) {
int r = value / (19 * 19);
int g = (value / 19) % 19;
int b = value % 19;
return new double[]{
signPow((r - 9) / 9.0f, 2f) * maxAc,
signPow((g - 9) / 9.0f, 2f) * maxAc,
signPow((b - 9) / 9.0f, 2f) * maxAc
};
}
private static Bitmap composeBitmap(int width, int height, int numCompX, int numCompY, double[][] colors) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double r = 0f;
double g = 0f;
double b = 0f;
for (int j = 0; j < numCompY; j++) {
for (int i = 0; i < numCompX; i++) {
double basis = (Math.cos(Math.PI * x * i / width) * Math.cos(Math.PI * y * j / height));
double[] color = colors[j * numCompX + i];
r += color[0] * basis;
g += color[1] * basis;
b += color[2] * basis;
}
}
bitmap.setPixel(x, y, Color.rgb((int) linearTosRGB(r), (int) linearTosRGB(g), (int) linearTosRGB(b)));
}
}
return bitmap;
}
}

View File

@@ -0,0 +1,148 @@
/**
* Source: https://github.com/hsch/blurhash-java
*
* Copyright (c) 2019 Hendrik Schnepel
*
* 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.
*/
package org.signal.blurhash;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.InputStream;
import static org.signal.blurhash.BlurHashUtil.linearTosRGB;
import static org.signal.blurhash.BlurHashUtil.max;
import static org.signal.blurhash.BlurHashUtil.sRGBToLinear;
import static org.signal.blurhash.BlurHashUtil.signPow;
public final class BlurHashEncoder {
private BlurHashEncoder() {
}
public static @Nullable String encode(InputStream inputStream) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
if (bitmap == null) return null;
String hash = encode(bitmap);
bitmap.recycle();
return hash;
}
public static @Nullable String encode(@NonNull Bitmap bitmap) {
return encode(bitmap, 4, 3);
}
static String encode(Bitmap bitmap, int componentX, int componentY) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
return encode(pixels, width, height, componentX, componentY);
}
private static String encode(int[] pixels, int width, int height, int componentX, int componentY) {
if (componentX < 1 || componentX > 9 || componentY < 1 || componentY > 9) {
throw new IllegalArgumentException("Blur hash must have between 1 and 9 components");
}
if (width * height != pixels.length) {
throw new IllegalArgumentException("Width and height must match the pixels array");
}
double[][] factors = new double[componentX * componentY][3];
for (int j = 0; j < componentY; j++) {
for (int i = 0; i < componentX; i++) {
double normalisation = i == 0 && j == 0 ? 1 : 2;
applyBasisFunction(pixels, width, height,
normalisation, i, j,
factors, j * componentX + i);
}
}
char[] hash = new char[1 + 1 + 4 + 2 * (factors.length - 1)]; // size flag + max AC + DC + 2 * AC components
long sizeFlag = componentX - 1 + (componentY - 1) * 9;
Base83.encode(sizeFlag, 1, hash, 0);
double maximumValue;
if (factors.length > 1) {
double actualMaximumValue = max(factors, 1, factors.length);
double quantisedMaximumValue = Math.floor(Math.max(0, Math.min(82, Math.floor(actualMaximumValue * 166 - 0.5))));
maximumValue = (quantisedMaximumValue + 1) / 166;
Base83.encode(Math.round(quantisedMaximumValue), 1, hash, 1);
} else {
maximumValue = 1;
Base83.encode(0, 1, hash, 1);
}
double[] dc = factors[0];
Base83.encode(encodeDC(dc), 4, hash, 2);
for (int i = 1; i < factors.length; i++) {
Base83.encode(encodeAC(factors[i], maximumValue), 2, hash, 6 + 2 * (i - 1));
}
return new String(hash);
}
private static void applyBasisFunction(int[] pixels, int width, int height,
double normalisation, int i, int j,
double[][] factors, int index)
{
double r = 0, g = 0, b = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
double basis = normalisation
* Math.cos((Math.PI * i * x) / width)
* Math.cos((Math.PI * j * y) / height);
int pixel = pixels[y * width + x];
r += basis * sRGBToLinear((pixel >> 16) & 0xff);
g += basis * sRGBToLinear((pixel >> 8) & 0xff);
b += basis * sRGBToLinear( pixel & 0xff);
}
}
double scale = 1.0 / (width * height);
factors[index][0] = r * scale;
factors[index][1] = g * scale;
factors[index][2] = b * scale;
}
private static long encodeDC(double[] value) {
long r = linearTosRGB(value[0]);
long g = linearTosRGB(value[1]);
long b = linearTosRGB(value[2]);
return (r << 16) + (g << 8) + b;
}
private static long encodeAC(double[] value, double maximumValue) {
double quantR = Math.floor(Math.max(0, Math.min(18, Math.floor(signPow(value[0] / maximumValue, 0.5) * 9 + 9.5))));
double quantG = Math.floor(Math.max(0, Math.min(18, Math.floor(signPow(value[1] / maximumValue, 0.5) * 9 + 9.5))));
double quantB = Math.floor(Math.max(0, Math.min(18, Math.floor(signPow(value[2] / maximumValue, 0.5) * 9 + 9.5))));
return Math.round(quantR * 19 * 19 + quantG * 19 + quantB);
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.blurhash;
final class BlurHashUtil {
static double sRGBToLinear(long value) {
double v = value / 255.0;
if (v <= 0.04045) {
return v / 12.92;
} else {
return Math.pow((v + 0.055) / 1.055, 2.4);
}
}
static long linearTosRGB(double value) {
double v = Math.max(0, Math.min(1, value));
if (v <= 0.0031308) {
return (long)(v * 12.92 * 255 + 0.5);
} else {
return (long)((1.055 * Math.pow(v, 1 / 2.4) - 0.055) * 255 + 0.5);
}
}
static double signPow(double val, double exp) {
return Math.copySign(Math.pow(Math.abs(val), exp), val);
}
static double max(double[][] values, int from, int endExclusive) {
double result = Double.NEGATIVE_INFINITY;
for (int i = from; i < endExclusive; i++) {
for (int j = 0; j < values[i].length; j++) {
double value = values[i][j];
if (value > result) {
result = value;
}
}
}
return result;
}
private BlurHashUtil() {
}
}

View File

@@ -14,6 +14,7 @@ android {
dependencies {
implementation(project(":core:util"))
implementation(project(":lib:blurhash"))
api(libs.glide.glide)
ksp(libs.glide.ksp)

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.glide.blurhash;
import androidx.annotation.NonNull;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import com.bumptech.glide.signature.ObjectKey;
import org.signal.blurhash.BlurHash;
public final class BlurHashModelLoader implements ModelLoader<BlurHash, BlurHash> {
private BlurHashModelLoader() {}
@Override
public LoadData<BlurHash> buildLoadData(@NonNull BlurHash blurHash,
int width,
int height,
@NonNull Options options)
{
return new LoadData<>(new ObjectKey(blurHash.getHash()), new BlurDataFetcher(blurHash));
}
@Override
public boolean handles(@NonNull BlurHash blurHash) {
return true;
}
private final class BlurDataFetcher implements DataFetcher<BlurHash> {
private final BlurHash blurHash;
private BlurDataFetcher(@NonNull BlurHash blurHash) {
this.blurHash = blurHash;
}
@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super BlurHash> callback) {
callback.onDataReady(blurHash);
}
@Override
public void cleanup() {
}
@Override
public void cancel() {
}
@Override
public @NonNull Class<BlurHash> getDataClass() {
return BlurHash.class;
}
@Override
public @NonNull DataSource getDataSource() {
return DataSource.LOCAL;
}
}
public static class Factory implements ModelLoaderFactory<BlurHash, BlurHash> {
@Override
public @NonNull ModelLoader<BlurHash, BlurHash> build(@NonNull MultiModelLoaderFactory multiFactory) {
return new BlurHashModelLoader();
}
@Override
public void teardown() {
}
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.signal.glide.blurhash;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.ResourceDecoder;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.resource.SimpleResource;
import org.signal.blurhash.BlurHash;
import org.signal.blurhash.BlurHashDecoder;
import java.io.IOException;
public class BlurHashResourceDecoder implements ResourceDecoder<BlurHash, Bitmap> {
private static final int MAX_DIMEN = 20;
@Override
public boolean handles(@NonNull BlurHash source, @NonNull Options options) throws IOException {
return true;
}
@Override
public @Nullable Resource<Bitmap> decode(@NonNull BlurHash source, int width, int height, @NonNull Options options) throws IOException {
final int finalWidth;
final int finalHeight;
if (width > height) {
finalWidth = Math.min(width, MAX_DIMEN);
finalHeight = (int) (finalWidth * height / (float) width);
} else {
finalHeight = Math.min(height, MAX_DIMEN);
finalWidth = (int) (finalHeight * width / (float) height);
}
return new SimpleResource<>(BlurHashDecoder.decode(source.getHash(), finalWidth, finalHeight));
}
}