├── demo ├── .gitignore ├── .travis.yml ├── public │ └── images │ │ ├── 1.jpg │ │ ├── 2.jpg │ │ └── 3.jpg ├── .babelrc ├── bootstrap.js ├── index.js ├── .bin │ └── create-wasm-app.js ├── data.json ├── LICENSE-MIT ├── package.json ├── webpack.config.js ├── index.html ├── README.md ├── App.js └── LICENSE-APACHE ├── .gitignore ├── tests ├── data │ ├── encode-test-input.jpg │ ├── decode-test-expected.png │ ├── encode-test-input-2.jpg │ └── roundtrip-test-input-decode.png ├── web.rs └── integration_test.rs ├── src ├── utils.rs └── lib.rs ├── .vscode └── tasks.json ├── LICENSE.md ├── netlify.toml ├── Cargo.toml └── README.md /demo/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | .vscode/ 8 | -------------------------------------------------------------------------------- /demo/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: "10" 3 | 4 | script: 5 | - ./node_modules/.bin/webpack 6 | -------------------------------------------------------------------------------- /demo/public/images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/demo/public/images/1.jpg -------------------------------------------------------------------------------- /demo/public/images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/demo/public/images/2.jpg -------------------------------------------------------------------------------- /demo/public/images/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/demo/public/images/3.jpg -------------------------------------------------------------------------------- /demo/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | ["@babel/plugin-transform-react-jsx", { "pragma":"h" }] 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /tests/data/encode-test-input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/tests/data/encode-test-input.jpg -------------------------------------------------------------------------------- /tests/data/decode-test-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/tests/data/decode-test-expected.png -------------------------------------------------------------------------------- /tests/data/encode-test-input-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/tests/data/encode-test-input-2.jpg -------------------------------------------------------------------------------- /tests/data/roundtrip-test-input-decode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fpapado/blurhash-rust-wasm/HEAD/tests/data/roundtrip-test-input-decode.png -------------------------------------------------------------------------------- /demo/bootstrap.js: -------------------------------------------------------------------------------- 1 | // A dependency graph that contains any wasm must all be imported 2 | // asynchronously. This `bootstrap.js` file does the single async import, so 3 | // that no one else needs to worry about it again. 4 | import("./index.js") 5 | .catch(e => console.error("Error importing `index.js`:", e)); 6 | -------------------------------------------------------------------------------- /tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /demo/index.js: -------------------------------------------------------------------------------- 1 | import "tachyons" 2 | import { App } from "./App"; 3 | import { render, h } from "preact"; 4 | 5 | // You can imagine a similar data structure coming from your backend. 6 | // Note how the blurhash is included in the fields! 7 | import data from "./data.json"; 8 | 9 | function main() { 10 | const root = document.getElementById("root"); 11 | render(, root); 12 | } 13 | 14 | main(); 15 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn set_panic_hook() { 2 | // When the `console_error_panic_hook` feature is enabled, we can call the 3 | // `set_panic_hook` function at least once during initialization, and then 4 | // we will get better error messages if our code ever panics. 5 | // 6 | // For more details see 7 | // https://github.com/rustwasm/console_error_panic_hook#readme 8 | #[cfg(feature = "console_error_panic_hook")] 9 | console_error_panic_hook::set_once(); 10 | } 11 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "cargo", 8 | "subcommand": "test", 9 | "problemMatcher": [ 10 | "$rustc" 11 | ], 12 | "group": { 13 | "kind": "test", 14 | "isDefault": true 15 | } 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /demo/.bin/create-wasm-app.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { spawn } = require("child_process"); 4 | const fs = require("fs"); 5 | 6 | let folderName = '.'; 7 | 8 | if (process.argv.length >= 3) { 9 | folderName = process.argv[2]; 10 | if (!fs.existsSync(folderName)) { 11 | fs.mkdirSync(folderName); 12 | } 13 | } 14 | 15 | const clone = spawn("git", ["clone", "https://github.com/rustwasm/create-wasm-app.git", folderName]); 16 | 17 | clone.on("close", code => { 18 | if (code !== 0) { 19 | console.error("cloning the template failed!") 20 | process.exit(code); 21 | } else { 22 | console.log("🦀 Rust + 🕸 Wasm = ❤"); 23 | } 24 | }); 25 | -------------------------------------------------------------------------------- /demo/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "images": [ 3 | { 4 | "id": 1, 5 | "src": "/images/1.jpg", 6 | "alt": "A mountain range in blue and pale purple colours.", 7 | "hash": "LUDT3yayV?ay%jWBa#a}9Xj[j@fP", 8 | "ratio": "4x6", 9 | "credit": { "username": "eth_gaaar", "displayName": "Edgar Hernández" } 10 | }, 11 | { 12 | "id": 2, 13 | "src": "/images/2.jpg", 14 | "alt": "A panoramic view of white and blue roofs on a Greek island.", 15 | "hash": "L3JkcZ^+00~V00009G0000R:%$4T", 16 | "ratio": "4x6", 17 | "credit": { 18 | "username": "hellothisisbenjamin", 19 | "displayName": "Benjamin Behre" 20 | } 21 | }, 22 | { 23 | "id": 3, 24 | "src": "/images/3.jpg", 25 | "alt": "A row of coloured buildings, on a curved stret.", 26 | "hash": "LFF$O@O,znM*~XNZ#+t8IUV@S5xu", 27 | "ratio": "6x4", 28 | "credit": { 29 | "username": "jonathanricci", 30 | "displayName": "Jonathan Ricci" 31 | } 32 | } 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Fotis Papadogeorgopoulos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /demo/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) [year] [name] 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blurhash-wasm-demo", 3 | "version": "0.1.0", 4 | "description": "A demo app for blurhash-wasm", 5 | "main": "index.js", 6 | "bin": { 7 | "create-wasm-app": ".bin/create-wasm-app.js" 8 | }, 9 | "scripts": { 10 | "build": "webpack --config webpack.config.js", 11 | "start": "webpack-dev-server" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/rustwasm/create-wasm-app.git" 16 | }, 17 | "keywords": [ 18 | "webassembly", 19 | "wasm", 20 | "rust", 21 | "blurhash" 22 | ], 23 | "author": "Fotis Papadogeorgopoulos ", 24 | "license": "(MIT OR Apache-2.0)", 25 | "homepage": "https://github.com/fpapado/blurhash-rust-wasm", 26 | "dependencies": { 27 | "blurhash-wasm": "^0.2.0", 28 | "preact": "^10.0.0-rc.0", 29 | "tachyons": "^4.11.1" 30 | }, 31 | "devDependencies": { 32 | "@babel/core": "^7.5.5", 33 | "@babel/plugin-transform-react-jsx": "^7.3.0", 34 | "@babel/preset-env": "^7.5.5", 35 | "babel-loader": "^8.0.6", 36 | "copy-webpack-plugin": "^5.0.0", 37 | "css-loader": "^3.1.0", 38 | "hello-wasm-pack": "^0.1.0", 39 | "mini-css-extract-plugin": "^0.8.0", 40 | "webpack": "^4.29.3", 41 | "webpack-cli": "^3.1.0", 42 | "webpack-dev-server": "^3.1.5" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /netlify.toml: -------------------------------------------------------------------------------- 1 | # This file configures the headers and redirect rules for Netlify. 2 | # Some are important for the page to work correctly, and other 3 | # are for performance. 4 | # Reference: https://www.netlify.com/docs/netlify-toml-reference/ 5 | 6 | # Global settings applied to the whole site. 7 | # 8 | # “base” is the directory to change to before starting build. If you set base: 9 | # that is where we will look for package.json/.nvmrc/etc, not repo root! 10 | # “command” is your build command. 11 | # “publish” is the directory to publish (relative to the root of your repo). 12 | 13 | [build] 14 | base = "demo" 15 | publish = "demo/dist" 16 | command = "npm run build" 17 | 18 | # Redirects 19 | # Anything else, we redirect to index.html 20 | [[redirects]] 21 | from = "/*" 22 | to = "/index.html" 23 | status = 200 24 | 25 | # Headers 26 | [[headers]] 27 | # Anything under /static is hashed, so we can cache indefinitely 28 | for = "/static/*" 29 | 30 | [headers.values] 31 | cache-control = ''' 32 | public, 33 | max-age=31536000, 34 | immutable''' 35 | 36 | [[headers]] 37 | # Assets under images/ are mutable, but large-ish 38 | # We cache them for a short time, to avoid excessive data consumption 39 | for = "/images/*" 40 | 41 | [headers.values] 42 | cache-control = ''' 43 | public, 44 | max-age=600, 45 | must-revalidate''' 46 | -------------------------------------------------------------------------------- /demo/webpack.config.js: -------------------------------------------------------------------------------- 1 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 2 | const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 3 | const path = require("path"); 4 | 5 | module.exports = { 6 | entry: "./bootstrap.js", 7 | output: { 8 | path: path.resolve(__dirname, "dist"), 9 | filename: "bootstrap.js" 10 | }, 11 | mode: "development", 12 | plugins: [ 13 | new CopyWebpackPlugin(["index.html", "public"]), 14 | new MiniCssExtractPlugin({ 15 | // Options similar to the same options in webpackOptions.output 16 | // all options are optional 17 | filename: "[name].[contenthash].css", 18 | chunkFilename: "[id].css", 19 | ignoreOrder: false // Enable to remove warnings about conflicting order 20 | }) 21 | ], 22 | module: { 23 | rules: [ 24 | { 25 | test: /\.m?js$/, 26 | exclude: /(node_modules|bower_components)/, 27 | use: { 28 | loader: "babel-loader", 29 | options: { 30 | presets: ["@babel/preset-env"], 31 | plugins: [["@babel/plugin-transform-react-jsx", { pragma: "h" }]] 32 | } 33 | } 34 | }, 35 | { 36 | test: /\.css$/, 37 | use: [ 38 | { 39 | loader: MiniCssExtractPlugin.loader, 40 | options: { 41 | hmr: process.env.NODE_ENV === "development" 42 | } 43 | }, 44 | "css-loader" 45 | ] 46 | } 47 | ] 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "blurhash-wasm" 3 | version = "0.2.0" 4 | authors = ["fpapado "] 5 | edition = "2018" 6 | 7 | description = "A Rust and WASM implementation of the blurhash algorithm" 8 | repository = "https://github.com/fpapado/blurhash-rust-wasm" 9 | license = "MIT" 10 | 11 | [lib] 12 | crate-type = ["cdylib", "rlib"] 13 | 14 | [features] 15 | default = ["console_error_panic_hook"] 16 | 17 | [dependencies] 18 | wasm-bindgen = "0.2" 19 | js-sys = "0.3" 20 | thiserror = "1" 21 | 22 | # The `console_error_panic_hook` crate provides better debugging of panics by 23 | # logging them with `console.error`. This is great for development, but requires 24 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 25 | # code size when deploying. 26 | console_error_panic_hook = { version = "0.1.1", optional = true } 27 | 28 | # `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size 29 | # compared to the default allocator's ~10K. It is slower than the default 30 | # allocator, however. 31 | # 32 | # Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. 33 | wee_alloc = { version = "0.4.2", optional = true } 34 | 35 | [dev-dependencies] 36 | wasm-bindgen-test = "0.2" 37 | image = "0.22.0" 38 | 39 | [profile.release] 40 | # Tell `rustc` to optimize for small code size. 41 | # When measuring, this didn't really change size much (it actually increased!). 42 | # For that reason, we've left it out for now. 43 | # opt-level = 's' 44 | lto = true 45 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Rust Wasm Blurhash 7 | 8 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /demo/README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

create-wasm-app

4 | 5 | An npm init template for kick starting a project that uses NPM packages containing Rust-generated WebAssembly and bundles them with Webpack. 6 | 7 |

8 | Build Status 9 |

10 | 11 |

12 | Usage 13 | | 14 | Chat 15 |

16 | 17 | Built with 🦀🕸 by The Rust and WebAssembly Working Group 18 |
19 | 20 | ## About 21 | 22 | This template is designed for depending on NPM packages that contain 23 | Rust-generated WebAssembly and using them to create a Website. 24 | 25 | * Want to create an NPM package with Rust and WebAssembly? [Check out 26 | `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template) 27 | * Want to make a monorepo-style Website without publishing to NPM? Check out 28 | [`rust-webpack-template`](https://github.com/rustwasm/rust-webpack-template) 29 | and/or 30 | [`rust-parcel-template`](https://github.com/rustwasm/rust-parcel-template). 31 | 32 | ## 🚴 Usage 33 | 34 | ``` 35 | npm init wasm-app 36 | ``` 37 | 38 | ## 🔋 Batteries Included 39 | 40 | - `.gitignore`: ignores `node_modules` 41 | - `LICENSE-APACHE` and `LICENSE-MIT`: most Rust projects are licensed this way, so these are included for you 42 | - `README.md`: the file you are reading now! 43 | - `index.html`: a bare bones html document that includes the webpack bundle 44 | - `index.js`: example js file with a comment showing how to import and use a wasm pkg 45 | - `package.json` and `package-lock.json`: 46 | - pulls in devDependencies for using webpack: 47 | - [`webpack`](https://www.npmjs.com/package/webpack) 48 | - [`webpack-cli`](https://www.npmjs.com/package/webpack-cli) 49 | - [`webpack-dev-server`](https://www.npmjs.com/package/webpack-dev-server) 50 | - defines a `start` script to run `webpack-dev-server` 51 | - `webpack.config.js`: configuration file for bundling your js with webpack 52 | 53 | ## License 54 | 55 | Licensed under either of 56 | 57 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 58 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 59 | 60 | at your option. 61 | 62 | ### Contribution 63 | 64 | Unless you explicitly state otherwise, any contribution intentionally 65 | submitted for inclusion in the work by you, as defined in the Apache-2.0 66 | license, shall be dual licensed as above, without any additional terms or 67 | conditions. 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # blurhash-wasm 2 | 3 | A Rust implementation of the [blurhash algorithm](https://github.com/woltapp/blurhash). 4 | 5 | It is compiled to WebAssembly (WASM), and [available on npm as `blurhash-wasm`](https://npmjs.com/blurhash-wasm). 6 | 7 | BlurHash is an algorithm written by [Dag Ågren](https://github.com/DagAgren) and folks at [Wolt (woltapp/blurhash)](https://github.com/woltapp/blurhash). BlurHash is "a compact representation of a placeholder for an image." It enables you to store that representation in your database. It can then be transferred together with the initial data, in order to decode and show it, before the main image request has finished (or even started). 8 | 9 | [Online Demo](https://blurhash-wasm.netlify.com). 10 | 11 | ## Usage in JS 12 | 13 | ### Installation 14 | 15 | You will need a package manager, either npm ([comes with node](https://nodejs.org/en/download/)) or [yarn](https://yarnpkg.com/lang/en/docs/install/). 16 | 17 | You will also need a bundler, [webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/guide/en/), configured for your project. 18 | 19 | Then, in a terminal: 20 | 21 | ```shell 22 | npm install blurhash-wasm 23 | # Or, yarn add blurhash-wasm 24 | ``` 25 | 26 | The [demo app source](/demo) has a complete example of using `blurhash-wasm`. 27 | 28 | ### decode 29 | 30 | ```js 31 | import * as blurhash from "blurhash-wasm"; 32 | 33 | // You can use this to construct canvas-compatible resources 34 | try { 35 | const pixels = blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30); 36 | } catch (error) { 37 | console.log(error); 38 | } 39 | ``` 40 | 41 | ### encode 42 | 43 | Implented, aim to be published in 0.3.0 44 | 45 | ## Usage in Rust 46 | 47 | ### Installation 48 | 49 | You will need [Rust and Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html). 50 | 51 | Add the version you want to `Cargo.toml`: 52 | 53 | ``` 54 | [dependencies] 55 | blurhash-wasm = "0.1.0" 56 | ``` 57 | 58 | ### decode 59 | 60 | ```rust 61 | use blurhash_wasm; 62 | 63 | // Result, blurhash::Error> 64 | let res = blurhash::decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30); 65 | ``` 66 | 67 | ### encode 68 | 69 | Implented, aim to be published in 0.3.0 70 | 71 | ## About the setup 72 | 73 | [**Based on the rust wasm-pack template**][template-docs] 74 | 75 | This template is designed for compiling Rust libraries into WebAssembly and 76 | publishing the resulting package to NPM. 77 | 78 | Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other 79 | templates and usages of `wasm-pack`. 80 | 81 | [tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html 82 | [template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html 83 | 84 | ## 🚴 Usage 85 | 86 | ### 🛠️ Build with `wasm-pack build` 87 | 88 | ``` 89 | wasm-pack build 90 | ``` 91 | 92 | ### 🔬 Test in Headless Browsers with `wasm-pack test` 93 | 94 | ``` 95 | wasm-pack test --headless --firefox 96 | ``` 97 | 98 | ### 🎁 Publish to NPM with `wasm-pack publish` 99 | 100 | ``` 101 | wasm-pack publish 102 | ``` 103 | 104 | ## 🔋 Batteries Included 105 | 106 | - [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating 107 | between WebAssembly and JavaScript. 108 | - [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) 109 | for logging panic messages to the developer console. 110 | - [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized 111 | for small code size. 112 | -------------------------------------------------------------------------------- /tests/integration_test.rs: -------------------------------------------------------------------------------- 1 | use blurhash_wasm::{decode, encode}; 2 | use image; 3 | use std::convert::TryFrom; 4 | 5 | #[test] 6 | fn err_if_hash_length_less_than_6() { 7 | assert_eq!( 8 | Err(blurhash_wasm::Error::LengthInvalid), 9 | decode("L", 40, 30) 10 | ); 11 | } 12 | 13 | #[test] 14 | fn decodes_ok() { 15 | // From the online demo 16 | let res = decode("LUDT3yayV?ay%jWBa#a}9Xj[j@fP", 40, 30); 17 | 18 | // From a known encode/decode 19 | let expected = image::open("tests/data/decode-test-expected.png") 20 | .unwrap() 21 | .to_rgba(); 22 | 23 | match res { 24 | Ok(img) => { 25 | // image::save_buffer("decode-test-out.png", &img, 40, 30, image::RGBA(8)); 26 | assert_eq!(expected.to_vec(), img); 27 | } 28 | 29 | Err(_err) => assert!(false), 30 | } 31 | } 32 | 33 | #[test] 34 | fn encodes_ok() { 35 | // From a known encode/decode 36 | let input = image::open("tests/data/encode-test-input.jpg") 37 | .unwrap() 38 | .to_rgba(); 39 | let (width, height) = input.dimensions(); 40 | 41 | // From the online demo 42 | // let expected = "LKO2?U%2Tw=w]~RBVZRi};RPxuwH"; 43 | 44 | // From our encoding, not sure why they differ 45 | let expected = "LKO2?V%2Tw=^]~RBVZRi};RPxuwH"; 46 | 47 | let res = encode( 48 | input.into_vec(), 49 | 4, 50 | 3, 51 | usize::try_from(width).unwrap(), 52 | usize::try_from(height).unwrap(), 53 | ); 54 | 55 | match res { 56 | Ok(actual) => { 57 | assert_eq!(expected, actual); 58 | } 59 | 60 | Err(_err) => assert!(false), 61 | } 62 | } 63 | 64 | #[test] 65 | fn encodes_ok_2() { 66 | // From a known encode/decode 67 | let input = image::open("tests/data/encode-test-input-2.jpg") 68 | .unwrap() 69 | .to_rgba(); 70 | let (width, height) = input.dimensions(); 71 | 72 | // From the online demo 73 | // let expected = "LGF5]+Yk^6#M@-5c,1J5@[or[Q6."; 74 | 75 | // From our encoding 76 | // Again, weird mismatch 77 | let expected = "LGFFaXYk^6#M@-5c,1Ex@@or[j6o"; 78 | 79 | let res = encode( 80 | input.into_vec(), 81 | 4, 82 | 3, 83 | usize::try_from(width).unwrap(), 84 | usize::try_from(height).unwrap(), 85 | ); 86 | 87 | match res { 88 | Ok(actual) => { 89 | assert_eq!(expected, actual); 90 | } 91 | 92 | Err(_err) => assert!(false), 93 | } 94 | } 95 | 96 | #[test] 97 | fn round_trips_ok() { 98 | // From a known encode/decode 99 | let input = image::open("tests/data/encode-test-input.jpg") 100 | .unwrap() 101 | .to_rgba(); 102 | let (width, height) = input.dimensions(); 103 | 104 | // From the online demo 105 | // let expected = "LKO2?U%2Tw=w]~RBVZRi};RPxuwH"; 106 | 107 | // From our encoding, not sure why they differ 108 | let expected_encode = "LKO2?V%2Tw=^]~RBVZRi};RPxuwH"; 109 | 110 | let encode_res = encode( 111 | input.into_vec(), 112 | 4, 113 | 3, 114 | usize::try_from(width).unwrap(), 115 | usize::try_from(height).unwrap(), 116 | ); 117 | 118 | match encode_res { 119 | Ok(actual_encode) => { 120 | assert_eq!(expected_encode, actual_encode); 121 | let expected_decode = image::open("tests/data/roundtrip-test-input-decode.png") 122 | .unwrap() 123 | .to_rgba(); 124 | 125 | let decode_res = decode(&actual_encode, 32, 32); 126 | 127 | match decode_res { 128 | Ok(actual_decode) => { 129 | assert_eq!(expected_decode.to_vec(), actual_decode); 130 | } 131 | 132 | Err(_err) => assert!(false), 133 | } 134 | } 135 | 136 | Err(_err) => assert!(false), 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /demo/App.js: -------------------------------------------------------------------------------- 1 | import * as blurhash from 'blurhash-wasm'; 2 | 3 | // Using react/preact in this demo mostly for convenience and habit. 4 | // You can of course render blurhashes however you want! 5 | import {h, Component} from 'preact'; 6 | import {useState, useRef, useEffect} from 'preact/hooks'; 7 | 8 | export function App(props) { 9 | const {images} = props; 10 | return ( 11 |
12 | 13 |
14 |

Demo

15 | {images.map(image => ( 16 |
17 |
18 | 19 |
20 | 21 |
22 | ))} 23 |
24 |
25 | ); 26 | } 27 | 28 | function CustomImage(props) { 29 | const {src, alt, hash, ratio} = props.image; 30 | 31 | // Hardcoded width/height for the decode and canvas 32 | // We keep these low and let the UI scale them up 33 | const WIDTH = 32; // pixels 34 | const HEIGHT = 32; // pixels 35 | 36 | const canvasRef = useRef(null); 37 | 38 | // Cycle the opacity of the final image, for demo purposes 39 | // (You could also do this with CSS animation keyframes :) ) 40 | const [opacity, setOpacity] = useState(-1); 41 | 42 | useInterval(() => { 43 | setOpacity(prevOpacity => prevOpacity * -1); 44 | }, 2000); 45 | 46 | // When the component mounts, set the image placeholder 47 | useEffect( 48 | () => { 49 | // Decode the hash into pixels 50 | try { 51 | const pixels = blurhash.decode(hash, WIDTH, HEIGHT); 52 | // Set the pixels to the canvas 53 | const asClamped = new Uint8ClampedArray(pixels); 54 | const imageData = new ImageData(asClamped, WIDTH, HEIGHT); 55 | 56 | const canvasEl = canvasRef.current; 57 | 58 | if (canvasEl) { 59 | const ctx = canvasEl.getContext('2d'); 60 | ctx.putImageData(imageData, 0, 0); 61 | } 62 | } catch (error) { 63 | console.error(error); 64 | } 65 | }, 66 | [hash] 67 | ); 68 | 69 | // Layout notes: 70 | // canvas goes below the img 71 | // both canvas and img have a fixed aspect-ratio placeholder 72 | // to preserve the layout size before either has loaded. 73 | return ( 74 |
75 |
76 | 82 | {alt} 88 |
89 |
90 | ); 91 | } 92 | 93 | function ImageCredit(props) { 94 | const {username, displayName} = props.credit; 95 | return ( 96 |

97 | Photo by {displayName}{' '} 98 | on Unsplash 99 |

100 | ); 101 | } 102 | 103 | function Pitch() { 104 | return ( 105 |
106 |
107 |

Rust Wasm BlurHash

108 | Skip to Demo 109 |

110 | A Rust and WebAssembly implementation of the{' '} 111 | BlurHash algorithm. 112 |

113 |

114 | BlurHash is "a compact representation of a placeholder for an image." 115 | It enables you to store that representation in your database. It can 116 | then be transferred together with the initial data, in order to decode 117 | and show it, before the main image request has finished (or even 118 | started). 119 |

120 |

121 | You can seamlessly use it in the browser through JS imports and 122 | bundling. 123 |

124 |
125 |
126 |         {`npm install blurhash-wasm`}
127 |       
128 |
129 |         
130 |           {`import * as blurhash from "blurhash-wasm";
131 | 
132 | // You can use this to construct canvas-compatible resources
133 | try {
134 |   const pixels = blurhash.decode("LKO2?U%2Tw=w]~RBVZRi};RPxuwH", 40, 30);
135 | } catch (error) {
136 |   console.log(error);
137 | }`}
138 |         
139 |       
140 |
141 |

Credits

142 | 160 |
161 |
162 |

Sources and installation

163 | 183 |
184 |
185 | ); 186 | } 187 | 188 | /** 189 | * Internal custom hook to periodically call a function 190 | * @see https://overreacted.io/making-setinterval-declarative-with-react-hooks/ 191 | */ 192 | function useInterval(callback, delay) { 193 | const savedCallback = useRef(); 194 | 195 | // Remember the latest callback. 196 | useEffect( 197 | () => { 198 | savedCallback.current = callback; 199 | }, 200 | [callback] 201 | ); 202 | 203 | // Set up the interval. 204 | useEffect( 205 | () => { 206 | function tick() { 207 | savedCallback.current(); 208 | } 209 | if (delay !== null) { 210 | let id = setInterval(tick, delay); 211 | return () => clearInterval(id); 212 | } 213 | }, 214 | [delay] 215 | ); 216 | } 217 | -------------------------------------------------------------------------------- /demo/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use std::cmp::Ordering; 4 | use std::convert::TryFrom; 5 | use std::f64::consts::PI; 6 | use thiserror::*; 7 | use wasm_bindgen::prelude::*; 8 | 9 | // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global 10 | // allocator. 11 | #[cfg(feature = "wee_alloc")] 12 | #[global_allocator] 13 | static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 14 | 15 | // TODO: Add adjustable 'punch' 16 | // TODO: Avoid panicing infrasturcture (checked division, .get, no unwrap) 17 | 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Error)] 19 | pub enum Error { 20 | #[error("the length of the hash is invalid")] 21 | LengthInvalid, 22 | #[error("the specified number of components does not match the actual length")] 23 | LengthMismatch, 24 | } 25 | 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Error)] 27 | pub enum EncodingError { 28 | #[error("cannot encode this number of components")] 29 | ComponentsNumberInvalid, 30 | #[error("the bytes per pixel does not match the pixel count")] 31 | BytesPerPixelMismatch, 32 | } 33 | 34 | // Decode 35 | 36 | /// Decode for WASM target. If an error occurs, the function will throw a `JsError`. 37 | #[wasm_bindgen(js_name = "decode")] 38 | pub fn wasm_decode(blur_hash: &str, width: usize, height: usize) -> Result, JsValue> { 39 | decode(blur_hash, width, height).map_err(|err| js_sys::Error::new(&err.to_string()).into()) 40 | } 41 | 42 | pub fn decode(blur_hash: &str, width: usize, height: usize) -> Result, Error> { 43 | if blur_hash.len() < 6 { 44 | return Err(Error::LengthInvalid); 45 | } 46 | 47 | // 1. Number of components 48 | // For a BlurHash with nx components along the X axis and ny components 49 | // along the Y axis, this is equal to (nx - 1) + (ny - 1) * 9. 50 | let size_flag = decode_base83_string(blur_hash.get(0..1).unwrap()); 51 | 52 | let num_y = (size_flag / 9) + 1; 53 | let num_x = (size_flag % 9) + 1; 54 | 55 | // Validate that the number of digits is what we expect: 56 | // 1 (size flag) + 1 (maximum value) + 4 (average colour) + (num_x - num_y - 1) components * 2 digits each 57 | let expected_digits = 4 + 2 * num_x * num_y; 58 | 59 | if blur_hash.len() != expected_digits { 60 | return Err(Error::LengthMismatch); 61 | } 62 | 63 | // 2. Maximum AC component value, 1 digit. 64 | // All AC components are scaled by this value. 65 | // It represents a floating-point value of (max + 1) / 166. 66 | let quantised_maximum_value = decode_base83_string(blur_hash.get(1..2).unwrap()); 67 | let maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64; 68 | 69 | let mut colours: Vec<[f64; 3]> = Vec::with_capacity(num_x * num_y); 70 | 71 | for i in 0..(num_x * num_y) { 72 | if i == 0 { 73 | // 3. Average colour, 4 digits. 74 | let value = decode_base83_string(blur_hash.get(2..6).unwrap()); 75 | colours.push(decode_dc(value)); 76 | } else { 77 | // 4. AC components, 2 digits each, nx * ny - 1 components in total. 78 | let value = decode_base83_string(blur_hash.get((4 + i * 2)..(4 + i * 2 + 2)).unwrap()); 79 | colours.push(decode_ac(value, maximum_value * 1.0)); 80 | } 81 | } 82 | 83 | // Now, construct the image 84 | // NOTE: We include an alpha channel of 255 as well, because it is more convenient, 85 | // for various representations (browser canvas, for example). 86 | // This could probably be configured 87 | let bytes_per_row = width * 4; 88 | 89 | let mut pixels = vec![0; bytes_per_row * height]; 90 | 91 | for y in 0..height { 92 | for x in 0..width { 93 | let mut r = 0f64; 94 | let mut g = 0f64; 95 | let mut b = 0f64; 96 | 97 | for j in 0..num_y { 98 | for i in 0..num_x { 99 | let basis = f64::cos(PI * (x as f64) * (i as f64) / (width as f64)) 100 | * f64::cos(PI * (y as f64) * (j as f64) / (height as f64)); 101 | let colour = colours[i + j * num_x]; 102 | r += colour[0] * basis; 103 | g += colour[1] * basis; 104 | b += colour[2] * basis; 105 | } 106 | } 107 | 108 | let int_r = linear_to_srgb(r); 109 | let int_g = linear_to_srgb(g); 110 | let int_b = linear_to_srgb(b); 111 | 112 | pixels[4 * x + y * bytes_per_row] = int_r as u8; 113 | pixels[4 * x + 1 + y * bytes_per_row] = int_g as u8; 114 | pixels[4 * x + 2 + y * bytes_per_row] = int_b as u8; 115 | pixels[4 * x + 3 + y * bytes_per_row] = 255 as u8; 116 | } 117 | } 118 | 119 | Ok(pixels) 120 | } 121 | 122 | fn decode_dc(value: usize) -> [f64; 3] { 123 | let int_r = value >> 16; 124 | let int_g = (value >> 8) & 255; 125 | let int_b = value & 255; 126 | [ 127 | srgb_to_linear(int_r), 128 | srgb_to_linear(int_g), 129 | srgb_to_linear(int_b), 130 | ] 131 | } 132 | 133 | fn decode_ac(value: usize, maximum_value: f64) -> [f64; 3] { 134 | let quant_r = f64::floor((value / (19 * 19)) as f64); 135 | let quant_g = f64::floor(((value / 19) as f64) % 19f64); 136 | let quant_b = (value as f64) % 19f64; 137 | [ 138 | sign_pow((quant_r - 9f64) / 9f64, 2f64) * maximum_value, 139 | sign_pow((quant_g - 9f64) / 9f64, 2f64) * maximum_value, 140 | sign_pow((quant_b - 9f64) / 9f64, 2f64) * maximum_value, 141 | ] 142 | } 143 | 144 | fn sign_pow(value: f64, exp: f64) -> f64 { 145 | value.abs().powf(exp).copysign(value) 146 | } 147 | 148 | fn linear_to_srgb(value: f64) -> usize { 149 | let v = f64::max(0f64, f64::min(1f64, value)); 150 | if v <= 0.003_130_8 { 151 | (v * 12.92 * 255f64 + 0.5) as usize 152 | } else { 153 | ((1.055 * f64::powf(v, 1f64 / 2.4) - 0.055) * 255f64 + 0.5) as usize 154 | } 155 | } 156 | 157 | fn srgb_to_linear(value: usize) -> f64 { 158 | let v = (value as f64) / 255f64; 159 | if v <= 0.04045 { 160 | v / 12.92 161 | } else { 162 | ((v + 0.055) / 1.055).powf(2.4) 163 | } 164 | } 165 | 166 | // Encode 167 | 168 | // TODO: Think about argument order here... 169 | // What is more common in Rust? Data or config first? 170 | pub fn encode( 171 | pixels: Vec, 172 | cx: usize, 173 | cy: usize, 174 | width: usize, 175 | height: usize, 176 | ) -> Result { 177 | // Should we assume RGBA for round-trips? Or does it not matter? 178 | let bytes_per_row = width * 4; 179 | let bytes_per_pixel = 4; 180 | 181 | // NOTE: We could clamp instead of Err. 182 | // The TS version does that. Not sure which one is better. 183 | // We also could (should?) be checking for the color space 184 | if cx < 1 || cx > 9 || cy < 1 || cy > 9 { 185 | return Err(EncodingError::ComponentsNumberInvalid); 186 | } 187 | 188 | if width * height * 4 != pixels.len() { 189 | return Err(EncodingError::BytesPerPixelMismatch); 190 | } 191 | 192 | let mut dc: [f64; 3] = [0., 0., 0.]; 193 | let mut ac: Vec<[f64; 3]> = Vec::with_capacity(cy * cx - 1); 194 | 195 | for y in 0..cy { 196 | for x in 0..cx { 197 | let normalisation = if x == 0 && y == 0 { 1f64 } else { 2f64 }; 198 | let factor = multiply_basis_function( 199 | &pixels, 200 | width, 201 | height, 202 | bytes_per_row, 203 | bytes_per_pixel, 204 | 0, 205 | |a, b| { 206 | (normalisation 207 | * f64::cos((PI * x as f64 * a) / width as f64) 208 | * f64::cos((PI * y as f64 * b) / height as f64)) 209 | }, 210 | ); 211 | 212 | if x == 0 && y == 0 { 213 | // The first iteration is the dc 214 | dc = factor; 215 | } else { 216 | // All others are the ac 217 | ac.push(factor); 218 | } 219 | } 220 | } 221 | 222 | let mut hash = String::new(); 223 | 224 | let size_flag = ((cx - 1) + (cy - 1) * 9) as usize; 225 | hash += &encode_base83_string(size_flag, 1); 226 | 227 | let maximum_value: f64; 228 | 229 | if !ac.is_empty() { 230 | // I'm sure there's a better way to write this; following the Swift atm :) 231 | let actual_maximum_value = ac 232 | .clone() 233 | .into_iter() 234 | .map(|[a, b, c]| f64::max(f64::max(f64::abs(a), f64::abs(b)), f64::abs(c))) 235 | .max_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)) 236 | .unwrap(); 237 | let quantised_maximum_value = usize::max( 238 | 0, 239 | usize::min(82, f64::floor(actual_maximum_value * 166f64 - 0.5) as usize), 240 | ); 241 | maximum_value = ((quantised_maximum_value + 1) as f64) / 166f64; 242 | hash += &encode_base83_string(quantised_maximum_value, 1); 243 | } else { 244 | maximum_value = 1f64; 245 | hash += &encode_base83_string(0, 1); 246 | } 247 | 248 | hash += &encode_base83_string(encode_dc(dc), 4); 249 | 250 | for factor in ac { 251 | hash += &encode_base83_string(encode_ac(factor, maximum_value), 2); 252 | } 253 | 254 | Ok(hash) 255 | } 256 | 257 | fn multiply_basis_function( 258 | pixels: &[u8], 259 | width: usize, 260 | height: usize, 261 | bytes_per_row: usize, 262 | bytes_per_pixel: usize, 263 | pixel_offset: usize, 264 | basis_function: F, 265 | ) -> [f64; 3] 266 | where 267 | F: Fn(f64, f64) -> f64, 268 | { 269 | let mut r = 0f64; 270 | let mut g = 0f64; 271 | let mut b = 0f64; 272 | 273 | for x in 0..width { 274 | for y in 0..height { 275 | let basis = basis_function(x as f64, y as f64); 276 | r += basis 277 | * srgb_to_linear( 278 | usize::try_from(pixels[bytes_per_pixel * x + pixel_offset + y * bytes_per_row]) 279 | .unwrap(), 280 | ); 281 | g += basis 282 | * srgb_to_linear( 283 | usize::try_from( 284 | pixels[bytes_per_pixel * x + pixel_offset + 1 + y * bytes_per_row], 285 | ) 286 | .unwrap(), 287 | ); 288 | b += basis 289 | * srgb_to_linear( 290 | usize::try_from( 291 | pixels[bytes_per_pixel * x + pixel_offset + 2 + y * bytes_per_row], 292 | ) 293 | .unwrap(), 294 | ); 295 | } 296 | } 297 | 298 | let scale = 1f64 / ((width * height) as f64); 299 | 300 | [r * scale, g * scale, b * scale] 301 | } 302 | 303 | fn encode_dc(value: [f64; 3]) -> usize { 304 | let rounded_r = linear_to_srgb(value[0]); 305 | let rounded_g = linear_to_srgb(value[1]); 306 | let rounded_b = linear_to_srgb(value[2]); 307 | ((rounded_r << 16) + (rounded_g << 8) + rounded_b) as usize 308 | } 309 | 310 | fn encode_ac(value: [f64; 3], maximum_value: f64) -> usize { 311 | let quant_r = f64::floor(f64::max( 312 | 0f64, 313 | f64::min( 314 | 18f64, 315 | f64::floor(sign_pow(value[0] / maximum_value, 0.5) * 9f64 + 9.5), 316 | ), 317 | )); 318 | let quant_g = f64::floor(f64::max( 319 | 0f64, 320 | f64::min( 321 | 18f64, 322 | f64::floor(sign_pow(value[1] / maximum_value, 0.5) * 9f64 + 9.5), 323 | ), 324 | )); 325 | let quant_b = f64::floor(f64::max( 326 | 0f64, 327 | f64::min( 328 | 18f64, 329 | f64::floor(sign_pow(value[2] / maximum_value, 0.5) * 9f64 + 9.5), 330 | ), 331 | )); 332 | 333 | (quant_r * 19f64 * 19f64 + quant_g * 19f64 + quant_b) as usize 334 | } 335 | 336 | // Base83 337 | 338 | // I considered using lazy_static! for this, but other implementations 339 | // seem to hard-code these as well. Doing that for consistency. 340 | static ENCODE_CHARACTERS: [char; 83] = [ 341 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 342 | 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 343 | 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 344 | 'v', 'w', 'x', 'y', 'z', '#', '$', '%', '*', '+', ',', '-', '.', ':', ';', '=', '?', '@', '[', 345 | ']', '^', '_', '{', '|', '}', '~', 346 | ]; 347 | 348 | fn decode_base83_string(string: &str) -> usize { 349 | string 350 | .chars() 351 | .filter_map(|character| ENCODE_CHARACTERS.iter().position(|&c| c == character)) 352 | .fold(0, |value, digit| value * 83 + digit) 353 | } 354 | 355 | fn encode_base83_string(value: usize, length: u32) -> String { 356 | (1..=length) 357 | .map(|i| (value / usize::pow(83, length - i)) % 83) 358 | .map(|digit| ENCODE_CHARACTERS[digit]) 359 | .collect() 360 | } 361 | 362 | #[cfg(test)] 363 | mod tests { 364 | use super::*; 365 | 366 | #[test] 367 | fn it_decodes_size_flag() { 368 | assert_eq!(21, decode_base83_string("L")); 369 | assert_eq!(0, decode_base83_string("0")); 370 | } 371 | #[test] 372 | fn decodes_size_0_out_of_range() { 373 | let res = decode_base83_string("/"); 374 | assert_eq!( 375 | 0, res, 376 | "Did not expect to decode size for input out of range (expected 0), but got {}", 377 | res 378 | ); 379 | } 380 | } 381 | --------------------------------------------------------------------------------