create a wasm js wrapper for blurhash

This commit is contained in:
Fries 2023-08-12 02:14:14 -07:00
commit 799a85c75d
14 changed files with 1523 additions and 0 deletions

8
.editorconfig Normal file
View file

@ -0,0 +1,8 @@
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
node_modules
src/blurhash-decode.wasm
dist

4
.npmignore Normal file
View file

@ -0,0 +1,4 @@
node_modules
blurhash
src
Makefile

1
.prettierrc.json Normal file
View file

@ -0,0 +1 @@
{}

7
Makefile Normal file
View file

@ -0,0 +1,7 @@
LIBRARY=src/blurhash-decode.wasm
$(LIBRARY): blurhash/decode.c
emcc --no-entry -Wl,--export,decodeToArray -Wl,--export,malloc -Wl,--export,free -Wl,--export,isValidBlurhash -o $@ blurhash/decode.c
.PHONY: clean
clean:
rm -f $(LIBRARY)

26
blurhash/common.h Normal file
View file

@ -0,0 +1,26 @@
#ifndef __BLURHASH_COMMON_H__
#define __BLURHASH_COMMON_H__
#include<math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static inline int linearTosRGB(float value) {
float v = fmaxf(0, fminf(1, value));
if(v <= 0.0031308) return v * 12.92 * 255 + 0.5;
else return (1.055 * powf(v, 1 / 2.4) - 0.055) * 255 + 0.5;
}
static inline float sRGBToLinear(int value) {
float v = (float)value / 255;
if(v <= 0.04045) return v / 12.92;
else return powf((v + 0.055) / 1.055, 2.4);
}
static inline float signPow(float value, float exp) {
return copysignf(powf(fabsf(value), exp), value);
}
#endif

135
blurhash/decode.c Normal file
View file

@ -0,0 +1,135 @@
#include "decode.h"
#include "common.h"
#include <stdint.h>
static char chars[83] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~";
static inline uint8_t clampToUByte(int * src) {
if( *src >= 0 && *src <= 255 )
return *src;
return (*src < 0) ? 0 : 255;
}
static inline uint8_t * createByteArray(int size) {
return (uint8_t *)malloc(size * sizeof(uint8_t));
}
int decodeToInt(uint8_t * string, int start, int end) {
int value = 0, iter1 = 0, iter2 = 0;
for( iter1 = start; iter1 < end; iter1 ++) {
int index = -1;
for(iter2 = 0; iter2 < 83; iter2 ++) {
if (chars[iter2] == string[iter1]) {
index = iter2;
break;
}
}
if (index == -1) return -1;
value = value * 83 + index;
}
return value;
}
bool isValidBlurhash(uint8_t * blurhash) {
const int hashLength = strlen((const char *)blurhash);
if (!blurhash || strlen((const char *)blurhash) < 6) return false;
int sizeFlag = decodeToInt(blurhash, 0, 1); //Get size from first character
int numY = (int)floorf(sizeFlag / 9) + 1;
int numX = (sizeFlag % 9) + 1;
if (hashLength != 4 + 2 * numX * numY) return false;
return true;
}
void decodeDC(int value, float * r, float * g, float * b) {
*r = sRGBToLinear(value >> 16); // R-component
*g = sRGBToLinear((value >> 8) & 255); // G-Component
*b = sRGBToLinear(value & 255); // B-Component
}
void decodeAC(int value, float maximumValue, float * r, float * g, float * b) {
int quantR = (int)floorf(value / (19 * 19));
int quantG = (int)floorf(value / 19) % 19;
int quantB = (int)value % 19;
*r = signPow(((float)quantR - 9) / 9, 2.0) * maximumValue;
*g = signPow(((float)quantG - 9) / 9, 2.0) * maximumValue;
*b = signPow(((float)quantB - 9) / 9, 2.0) * maximumValue;
}
int decodeToArray(uint8_t * blurhash, int width, int height, int punch, int nChannels, uint8_t * pixelArray) {
if (!isValidBlurhash(blurhash)) return -1;
if (punch < 1) punch = 1;
int sizeFlag = decodeToInt(blurhash, 0, 1);
int numY = (int)floorf(sizeFlag / 9) + 1;
int numX = (sizeFlag % 9) + 1;
int iter = 0;
float r = 0, g = 0, b = 0;
int quantizedMaxValue = decodeToInt(blurhash, 1, 2);
if (quantizedMaxValue == -1) return -1;
float maxValue = ((float)(quantizedMaxValue + 1)) / 166;
int colors_size = numX * numY;
float colors[colors_size][3];
for(iter = 0; iter < colors_size; iter ++) {
if (iter == 0) {
int value = decodeToInt(blurhash, 2, 6);
if (value == -1) return -1;
decodeDC(value, &r, &g, &b);
colors[iter][0] = r;
colors[iter][1] = g;
colors[iter][2] = b;
} else {
int value = decodeToInt(blurhash, 4 + iter * 2, 6 + iter * 2);
if (value == -1) return -1;
decodeAC(value, maxValue * punch, &r, &g, &b);
colors[iter][0] = r;
colors[iter][1] = g;
colors[iter][2] = b;
}
}
int bytesPerRow = width * nChannels;
int x = 0, y = 0, i = 0, j = 0;
int intR = 0, intG = 0, intB = 0;
for(y = 0; y < height; y ++) {
for(x = 0; x < width; x ++) {
float r = 0, g = 0, b = 0;
for(j = 0; j < numY; j ++) {
for(i = 0; i < numX; i ++) {
float basics = cos((M_PI * x * i) / width) * cos((M_PI * y * j) / height);
int idx = i + j * numX;
r += colors[idx][0] * basics;
g += colors[idx][1] * basics;
b += colors[idx][2] * basics;
}
}
intR = linearTosRGB(r);
intG = linearTosRGB(g);
intB = linearTosRGB(b);
pixelArray[nChannels * x + 0 + y * bytesPerRow] = clampToUByte(&intR);
pixelArray[nChannels * x + 1 + y * bytesPerRow] = clampToUByte(&intG);
pixelArray[nChannels * x + 2 + y * bytesPerRow] = clampToUByte(&intB);
if (nChannels == 4)
pixelArray[nChannels * x + 3 + y * bytesPerRow] = 255; // If nChannels=4, treat each pixel as RGBA instead of RGB
}
}
return 0;
}

34
blurhash/decode.h Normal file
View file

@ -0,0 +1,34 @@
#ifndef __BLURHASH_DECODE_H__
#define __BLURHASH_DECODE_H__
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
/*
decodeToArray : Decodes the blurhash and copies the pixels to pixelArray,
This method is suggested if you use an external memory allocator for pixelArray.
pixelArray should be of size : width * height * nChannels
Parameters :
blurhash : A string representing the blurhash to be decoded.
width : Width of the resulting image
height : Height of the resulting image
punch : The factor to improve the contrast, default = 1
nChannels : Number of channels in the resulting image array, 3 = RGB, 4 = RGBA
pixelArray : Pointer to memory region where pixels needs to be copied.
Returns : int, -1 if error 0 if successful
*/
int decodeToArray(uint8_t * blurhash, int width, int height, int punch, int nChannels, uint8_t * pixelArray);
/*
isValidBlurhash : Checks if the Blurhash is valid or not.
Parameters :
blurhash : A string representing the blurhash
Returns : bool (true if it is a valid blurhash, else false)
*/
bool isValidBlurhash(uint8_t * blurhash);
#endif

26
package.json Normal file
View file

@ -0,0 +1,26 @@
{
"type": "module",
"name": "blurhash-c-wasm",
"version": "1.0.0",
"description": "",
"main": "dist/library.js",
"types": "dist/library.d.ts",
"scripts": {
"build": "make && rollup -c rollup.config.js",
"prepublishOnly": "build"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-typescript": "^11.1.2",
"@rollup/plugin-wasm": "^6.1.3",
"rollup": "^3.28.0",
"tslib": "^2.6.1",
"typescript": "^5.1.6",
"vite": "^4.4.9",
"vite-plugin-dts": "^3.5.2",
"vite-plugin-top-level-await": "^1.3.1",
"vite-plugin-wasm": "^3.2.2"
}
}

1035
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load diff

17
rollup.config.js Normal file
View file

@ -0,0 +1,17 @@
import { defineConfig } from "rollup";
import path from "node:path";
import url from "node:url"
import Typescript from "@rollup/plugin-typescript";
import Wasm from "@rollup/plugin-wasm";
const dirname = path.dirname(url.fileURLToPath(import.meta.url))
export default defineConfig({
plugins: [Typescript(), Wasm({targetEnv: "auto-inline"})],
input: path.resolve(dirname, "src/library.ts"),
output: {
dir: "dist",
format: "es",
sourcemap: "inline"
}
})

91
src/library.ts Normal file
View file

@ -0,0 +1,91 @@
// @ts-ignore
import wasm from "./blurhash-decode.wasm";
type InstanceType = {
memory: WebAssembly.Memory;
malloc: CallableFunction;
free: CallableFunction;
decodeToArray: CallableFunction;
isValidBlurhash: CallableFunction;
};
const wasmInstance = new WebAssembly.Instance(await wasm());
const instance = wasmInstance.exports as InstanceType;
function encodeStringToWasmArray(string: string): number {
const encoder = new TextEncoder();
const encodedString = encoder.encode(string);
const stringPtr: number = instance.malloc(encodedString.byteLength);
const stringBuf = new Uint8Array(
<ArrayBuffer>instance.memory.buffer,
stringPtr,
encodedString.byteLength + 1
);
stringBuf.set(encodedString);
// terminate the string.
stringBuf[encodedString.byteLength] = 0;
return stringPtr;
}
/**
* Decode a Blurhash string into a Pixel Array that you can use to generate a Blurhash image.
* @param blurhashString A valid Blurhash string.
* @param width The width of the image you want to generate.
* @param height The height of the image you want to generate.
* @returns A `Uint8ClampedArray` pixel array.
*/
export function decode(
blurhashString: string,
width: number,
height: number
): Uint8ClampedArray {
if (!width || !height) {
throw Error("You are required to give the width or height.")
}
const pixelsPtrSize = width * 4 * width;
const pixelsPtr = instance.malloc(pixelsPtrSize);
const pixelsBuf = new Uint8ClampedArray(
<ArrayBuffer>instance.memory.buffer,
pixelsPtr,
pixelsPtrSize
);
const stringPtr: number = encodeStringToWasmArray(blurhashString);
const result = instance.decodeToArray(
stringPtr,
width,
height,
1,
4,
pixelsPtr
);
if (result == -1) {
instance.free(pixelsPtr);
instance.free(stringPtr);
throw Error("Decoding the Blurhash string has failed.");
}
const clonedBuffer = pixelsBuf.slice(0);
instance.free(pixelsPtr);
instance.free(stringPtr);
return clonedBuffer;
}
/**
* Check if your Blurhash string is valid.
* @param blurhashString A Blurhash string.
* @returns `true` if your string is valid, `false` elsewise.
*/
export function isValidBlurhash(blurhashString: string) {
const stringPtr = encodeStringToWasmArray(blurhashString);
const result: number = instance.isValidBlurhash(stringPtr);
instance.free(stringPtr);
return Boolean(result);
}
export { instance as weed };

109
tsconfig.json Normal file
View file

@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [""], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ES2022", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "NodeNext",
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
"allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": false, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": false, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

27
vite.config.js Normal file
View file

@ -0,0 +1,27 @@
import { defineConfig } from "vite";
import path from "node:path";
import Wasm from "vite-plugin-wasm";
import TopLevelAwait from "vite-plugin-top-level-await";
import Dts from "vite-plugin-dts";
import Typescript from "@rollup/plugin-typescript";
export default defineConfig({
plugins: [Wasm(), TopLevelAwait(), Dts()],
build: {
// lib: {
// entry: path.resolve(__dirname, "src/library.ts"),
// name: "blurhash-c-wasm",
// formats: ["es"],
// },
minify: false,
sourcemap: true,
rollupOptions: {
input: path.resolve(__dirname, "src/library.ts"),
output: {
dir: "dist",
format: "es",
sourcemap: "inline"
}
}
},
});