mirror of
https://github.com/GoogleChromeLabs/squoosh.git
synced 2025-11-12 08:47:31 +00:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b831aa0075 | ||
|
|
bf4d4b78cb | ||
|
|
496896e36e | ||
|
|
6b88ec1f8a | ||
|
|
3af5f3a96d | ||
|
|
ddc5564515 | ||
|
|
bc5da7ef06 | ||
|
|
45221c0b03 | ||
|
|
d29cf2ffa7 | ||
|
|
f6c0b89d1f | ||
|
|
ecd9e06665 | ||
|
|
9e5b66d5f4 | ||
|
|
8c35c3cdaa | ||
|
|
828a6240fe |
6
codecs/resize/.gitignore
vendored
Normal file
6
codecs/resize/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
**/*.rs.bk
|
||||||
|
target
|
||||||
|
Cargo.lock
|
||||||
|
bin/
|
||||||
|
pkg/README.md
|
||||||
|
lut.inc
|
||||||
37
codecs/resize/Cargo.toml
Normal file
37
codecs/resize/Cargo.toml
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
[package]
|
||||||
|
name = "squooshresize"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Surma <surma@surma.link>"]
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
#crate-type = ["cdylib", "rlib"]
|
||||||
|
crate-type = ["cdylib"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["console_error_panic_hook", "wee_alloc"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
cfg-if = "0.1.2"
|
||||||
|
wasm-bindgen = "0.2.38"
|
||||||
|
resize = "0.3.0"
|
||||||
|
|
||||||
|
# The `console_error_panic_hook` crate provides better debugging of panics by
|
||||||
|
# logging them with `console.error`. This is great for development, but requires
|
||||||
|
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
|
||||||
|
# code size when deploying.
|
||||||
|
console_error_panic_hook = { version = "0.1.1", optional = true }
|
||||||
|
|
||||||
|
# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size
|
||||||
|
# compared to the default allocator's ~10K. It is slower than the default
|
||||||
|
# allocator, however.
|
||||||
|
#
|
||||||
|
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
|
||||||
|
wee_alloc = { version = "0.4.2", optional = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
wasm-bindgen-test = "0.2"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
# Tell `rustc` to optimize for small code size.
|
||||||
|
opt-level = "s"
|
||||||
|
lto = true
|
||||||
18
codecs/resize/Dockerfile
Normal file
18
codecs/resize/Dockerfile
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
FROM ubuntu
|
||||||
|
RUN apt-get update && \
|
||||||
|
apt-get install -qqy git build-essential cmake python2.7
|
||||||
|
RUN git clone --recursive https://github.com/WebAssembly/wabt /usr/src/wabt
|
||||||
|
RUN mkdir -p /usr/src/wabt/build
|
||||||
|
WORKDIR /usr/src/wabt/build
|
||||||
|
RUN cmake .. -DCMAKE_INSTALL_PREFIX=/opt/wabt && \
|
||||||
|
make && \
|
||||||
|
make install
|
||||||
|
|
||||||
|
FROM rust
|
||||||
|
RUN rustup install nightly && \
|
||||||
|
rustup target add --toolchain nightly wasm32-unknown-unknown && \
|
||||||
|
cargo install wasm-pack
|
||||||
|
|
||||||
|
COPY --from=0 /opt/wabt /opt/wabt
|
||||||
|
ENV PATH="/opt/wabt/bin:${PATH}"
|
||||||
|
WORKDIR /src
|
||||||
53
codecs/resize/benchmark.js
Normal file
53
codecs/resize/benchmark.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
// THIS IS NOT A NODE SCRIPT
|
||||||
|
// This is a d8 script. Please install jsvu[1] and install v8.
|
||||||
|
// Then run `npm run --silent benchmark`.
|
||||||
|
// [1]: https://github.com/GoogleChromeLabs/jsvu
|
||||||
|
|
||||||
|
self = global = this;
|
||||||
|
load("./pkg/resize.js");
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
// Adjustable constants.
|
||||||
|
const inputDimensions = 2000;
|
||||||
|
const outputDimensions = 1500;
|
||||||
|
const algorithm = 3; // Lanczos
|
||||||
|
const iterations = new Array(100);
|
||||||
|
|
||||||
|
// Constants. Don’t change.
|
||||||
|
const imageByteSize = inputDimensions * inputDimensions * 4;
|
||||||
|
const imageBuffer = new Uint8ClampedArray(imageByteSize);
|
||||||
|
|
||||||
|
const module = await WebAssembly.compile(readbuffer("./pkg/resize_bg.wasm"));
|
||||||
|
await wasm_bindgen(module);
|
||||||
|
[[false, false], [true, false], [false, true], [true, true]].forEach(
|
||||||
|
opts => {
|
||||||
|
print(`\npremultiplication: ${opts[0]}`);
|
||||||
|
print(`color space conversion: ${opts[1]}`);
|
||||||
|
print(`==============================`);
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const start = Date.now();
|
||||||
|
wasm_bindgen.resize(
|
||||||
|
imageBuffer,
|
||||||
|
inputDimensions,
|
||||||
|
inputDimensions,
|
||||||
|
outputDimensions,
|
||||||
|
outputDimensions,
|
||||||
|
algorithm,
|
||||||
|
...opts
|
||||||
|
);
|
||||||
|
iterations[i] = Date.now() - start;
|
||||||
|
}
|
||||||
|
const average =
|
||||||
|
iterations.reduce((sum, c) => sum + c) / iterations.length;
|
||||||
|
const stddev = Math.sqrt(
|
||||||
|
iterations
|
||||||
|
.map(i => Math.pow(i - average, 2))
|
||||||
|
.reduce((sum, c) => sum + c) / iterations.length
|
||||||
|
);
|
||||||
|
print(`n = ${iterations.length}`);
|
||||||
|
print(`Average: ${average}`);
|
||||||
|
print(`StdDev: ${stddev}`);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
init().catch(e => console.error(e, e.stack));
|
||||||
23
codecs/resize/build.rs
Normal file
23
codecs/resize/build.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
include!("./src/srgb.rs");
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
let mut srgb_to_linear_lut = String::from("static SRGB_TO_LINEAR_LUT: [f32; 256] = [");
|
||||||
|
let mut linear_to_srgb_lut = String::from("static LINEAR_TO_SRGB_LUT: [f32; 256] = [");
|
||||||
|
for i in 0..256 {
|
||||||
|
srgb_to_linear_lut.push_str(&format!("{0:.7}", srgb_to_linear((i as f32) / 255.0)));
|
||||||
|
srgb_to_linear_lut.push_str(",");
|
||||||
|
linear_to_srgb_lut.push_str(&format!("{0:.7}", linear_to_srgb((i as f32) / 255.0)));
|
||||||
|
linear_to_srgb_lut.push_str(",");
|
||||||
|
}
|
||||||
|
srgb_to_linear_lut.pop().unwrap();
|
||||||
|
linear_to_srgb_lut.pop().unwrap();
|
||||||
|
srgb_to_linear_lut.push_str("];");
|
||||||
|
linear_to_srgb_lut.push_str("];");
|
||||||
|
|
||||||
|
let mut file = std::fs::File::create("src/lut.inc")?;
|
||||||
|
file.write_all(srgb_to_linear_lut.as_bytes())?;
|
||||||
|
file.write_all(linear_to_srgb_lut.as_bytes())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
22
codecs/resize/build.sh
Executable file
22
codecs/resize/build.sh
Executable file
@@ -0,0 +1,22 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "============================================="
|
||||||
|
echo "Compiling wasm"
|
||||||
|
echo "============================================="
|
||||||
|
(
|
||||||
|
rustup run nightly \
|
||||||
|
wasm-pack build --target no-modules
|
||||||
|
wasm-strip pkg/resize_bg.wasm
|
||||||
|
)
|
||||||
|
echo "============================================="
|
||||||
|
echo "Compiling wasm done"
|
||||||
|
echo "============================================="
|
||||||
|
|
||||||
|
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
|
||||||
|
echo "Did you update your docker image?"
|
||||||
|
echo "Run \`docker pull ubuntu\`"
|
||||||
|
echo "Run \`docker pull rust\`"
|
||||||
|
echo "Run \`docker build -t squoosh-resize .\`"
|
||||||
|
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
|
||||||
4
codecs/resize/package-lock.json
generated
Normal file
4
codecs/resize/package-lock.json
generated
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"name": "resize",
|
||||||
|
"lockfileVersion": 1
|
||||||
|
}
|
||||||
8
codecs/resize/package.json
Normal file
8
codecs/resize/package.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"name": "resize",
|
||||||
|
"scripts": {
|
||||||
|
"build:image": "docker build -t squoosh-resize .",
|
||||||
|
"build": "docker run --rm -v $(pwd):/src squoosh-resize ./build.sh",
|
||||||
|
"benchmark": "v8 --no-liftoff --no-wasm-tier-up ./benchmark.js"
|
||||||
|
}
|
||||||
|
}
|
||||||
13
codecs/resize/pkg/resize.d.ts
vendored
Normal file
13
codecs/resize/pkg/resize.d.ts
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/* tslint:disable */
|
||||||
|
/**
|
||||||
|
* @param {Uint8Array} arg0
|
||||||
|
* @param {number} arg1
|
||||||
|
* @param {number} arg2
|
||||||
|
* @param {number} arg3
|
||||||
|
* @param {number} arg4
|
||||||
|
* @param {number} arg5
|
||||||
|
* @param {boolean} arg6
|
||||||
|
* @param {boolean} arg7
|
||||||
|
* @returns {Uint8Array}
|
||||||
|
*/
|
||||||
|
export function resize(arg0: Uint8Array, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number, arg6: boolean, arg7: boolean): Uint8Array;
|
||||||
114
codecs/resize/pkg/resize.js
Normal file
114
codecs/resize/pkg/resize.js
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
(function() {
|
||||||
|
var wasm;
|
||||||
|
const __exports = {};
|
||||||
|
|
||||||
|
|
||||||
|
let cachegetUint8Memory = null;
|
||||||
|
function getUint8Memory() {
|
||||||
|
if (cachegetUint8Memory === null || cachegetUint8Memory.buffer !== wasm.memory.buffer) {
|
||||||
|
cachegetUint8Memory = new Uint8Array(wasm.memory.buffer);
|
||||||
|
}
|
||||||
|
return cachegetUint8Memory;
|
||||||
|
}
|
||||||
|
|
||||||
|
let WASM_VECTOR_LEN = 0;
|
||||||
|
|
||||||
|
function passArray8ToWasm(arg) {
|
||||||
|
const ptr = wasm.__wbindgen_malloc(arg.length * 1);
|
||||||
|
getUint8Memory().set(arg, ptr / 1);
|
||||||
|
WASM_VECTOR_LEN = arg.length;
|
||||||
|
return ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getArrayU8FromWasm(ptr, len) {
|
||||||
|
return getUint8Memory().subarray(ptr / 1, ptr / 1 + len);
|
||||||
|
}
|
||||||
|
|
||||||
|
let cachedGlobalArgumentPtr = null;
|
||||||
|
function globalArgumentPtr() {
|
||||||
|
if (cachedGlobalArgumentPtr === null) {
|
||||||
|
cachedGlobalArgumentPtr = wasm.__wbindgen_global_argument_ptr();
|
||||||
|
}
|
||||||
|
return cachedGlobalArgumentPtr;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cachegetUint32Memory = null;
|
||||||
|
function getUint32Memory() {
|
||||||
|
if (cachegetUint32Memory === null || cachegetUint32Memory.buffer !== wasm.memory.buffer) {
|
||||||
|
cachegetUint32Memory = new Uint32Array(wasm.memory.buffer);
|
||||||
|
}
|
||||||
|
return cachegetUint32Memory;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @param {Uint8Array} arg0
|
||||||
|
* @param {number} arg1
|
||||||
|
* @param {number} arg2
|
||||||
|
* @param {number} arg3
|
||||||
|
* @param {number} arg4
|
||||||
|
* @param {number} arg5
|
||||||
|
* @param {boolean} arg6
|
||||||
|
* @param {boolean} arg7
|
||||||
|
* @returns {Uint8Array}
|
||||||
|
*/
|
||||||
|
__exports.resize = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
|
||||||
|
const ptr0 = passArray8ToWasm(arg0);
|
||||||
|
const len0 = WASM_VECTOR_LEN;
|
||||||
|
const retptr = globalArgumentPtr();
|
||||||
|
wasm.resize(retptr, ptr0, len0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
|
||||||
|
const mem = getUint32Memory();
|
||||||
|
const rustptr = mem[retptr / 4];
|
||||||
|
const rustlen = mem[retptr / 4 + 1];
|
||||||
|
|
||||||
|
const realRet = getArrayU8FromWasm(rustptr, rustlen).slice();
|
||||||
|
wasm.__wbindgen_free(rustptr, rustlen * 1);
|
||||||
|
return realRet;
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
const heap = new Array(32);
|
||||||
|
|
||||||
|
heap.fill(undefined);
|
||||||
|
|
||||||
|
heap.push(undefined, null, true, false);
|
||||||
|
|
||||||
|
let heap_next = heap.length;
|
||||||
|
|
||||||
|
function dropObject(idx) {
|
||||||
|
if (idx < 36) return;
|
||||||
|
heap[idx] = heap_next;
|
||||||
|
heap_next = idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
__exports.__wbindgen_object_drop_ref = function(i) { dropObject(i); };
|
||||||
|
|
||||||
|
function init(path_or_module) {
|
||||||
|
let instantiation;
|
||||||
|
const imports = { './resize': __exports };
|
||||||
|
if (path_or_module instanceof WebAssembly.Module) {
|
||||||
|
instantiation = WebAssembly.instantiate(path_or_module, imports)
|
||||||
|
.then(instance => {
|
||||||
|
return { instance, module: path_or_module }
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const data = fetch(path_or_module);
|
||||||
|
if (typeof WebAssembly.instantiateStreaming === 'function') {
|
||||||
|
instantiation = WebAssembly.instantiateStreaming(data, imports)
|
||||||
|
.catch(e => {
|
||||||
|
console.warn("`WebAssembly.instantiateStreaming` failed. Assuming this is because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
|
||||||
|
return data
|
||||||
|
.then(r => r.arrayBuffer())
|
||||||
|
.then(bytes => WebAssembly.instantiate(bytes, imports));
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
instantiation = data
|
||||||
|
.then(response => response.arrayBuffer())
|
||||||
|
.then(buffer => WebAssembly.instantiate(buffer, imports));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return instantiation.then(({instance}) => {
|
||||||
|
wasm = init.wasm = instance.exports;
|
||||||
|
|
||||||
|
});
|
||||||
|
};
|
||||||
|
self.wasm_bindgen = Object.assign(init, __exports);
|
||||||
|
})();
|
||||||
6
codecs/resize/pkg/resize_bg.d.ts
vendored
Normal file
6
codecs/resize/pkg/resize_bg.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
/* tslint:disable */
|
||||||
|
export const memory: WebAssembly.Memory;
|
||||||
|
export function __wbindgen_global_argument_ptr(): number;
|
||||||
|
export function __wbindgen_malloc(a: number): number;
|
||||||
|
export function __wbindgen_free(a: number, b: number): void;
|
||||||
|
export function resize(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number): void;
|
||||||
BIN
codecs/resize/pkg/resize_bg.wasm
Normal file
BIN
codecs/resize/pkg/resize_bg.wasm
Normal file
Binary file not shown.
121
codecs/resize/src/lib.rs
Normal file
121
codecs/resize/src/lib.rs
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
extern crate cfg_if;
|
||||||
|
extern crate resize;
|
||||||
|
extern crate wasm_bindgen;
|
||||||
|
|
||||||
|
mod utils;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
use resize::Pixel::RGBA;
|
||||||
|
use resize::Type;
|
||||||
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
|
mod srgb;
|
||||||
|
use srgb::Clamp;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
|
||||||
|
// allocator.
|
||||||
|
if #[cfg(feature = "wee_alloc")] {
|
||||||
|
extern crate wee_alloc;
|
||||||
|
#[global_allocator]
|
||||||
|
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
include!("./lut.inc");
|
||||||
|
|
||||||
|
// If `with_space_conversion` is true, this function returns 2 functions that
|
||||||
|
// convert from sRGB to linear RGB and vice versa. If `with_space_conversion` is
|
||||||
|
// false, the 2 functions returned do nothing.
|
||||||
|
fn converter_funcs(with_space_conversion: bool) -> ((fn(u8) -> f32), (fn(f32) -> u8)) {
|
||||||
|
if with_space_conversion {
|
||||||
|
(
|
||||||
|
|v| SRGB_TO_LINEAR_LUT[v as usize] * 255.0,
|
||||||
|
|v| (LINEAR_TO_SRGB_LUT[v as usize] * 255.0) as u8,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(|v| v as f32, |v| v as u8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If `with_alpha_premultiplication` is true, this function returns a function
|
||||||
|
// that premultiply the alpha channel with the given channel value and another
|
||||||
|
// function that reverses that process. If `with_alpha_premultiplication` is
|
||||||
|
// false, the functions just return the channel value.
|
||||||
|
fn alpha_multiplier_funcs(
|
||||||
|
with_alpha_premultiplication: bool,
|
||||||
|
) -> ((fn(f32, u8) -> u8), (fn(u8, u8) -> f32)) {
|
||||||
|
if with_alpha_premultiplication {
|
||||||
|
(
|
||||||
|
|v, a| (v * (a as f32) / 255.0) as u8,
|
||||||
|
|v, a| (v as f32) * 255.0 / (a as f32).clamp(0.0, 255.0),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(|v, _a| v as u8, |v, _a| v as f32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
#[no_mangle]
|
||||||
|
pub fn resize(
|
||||||
|
mut input_image: Vec<u8>,
|
||||||
|
input_width: usize,
|
||||||
|
input_height: usize,
|
||||||
|
output_width: usize,
|
||||||
|
output_height: usize,
|
||||||
|
typ_idx: usize,
|
||||||
|
premultiply: bool,
|
||||||
|
color_space_conversion: bool,
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let typ = match typ_idx {
|
||||||
|
0 => Type::Triangle,
|
||||||
|
1 => Type::Catrom,
|
||||||
|
2 => Type::Mitchell,
|
||||||
|
3 => Type::Lanczos3,
|
||||||
|
_ => panic!("Nope"),
|
||||||
|
};
|
||||||
|
let num_input_pixels = input_width * input_height;
|
||||||
|
let num_output_pixels = output_width * output_height;
|
||||||
|
|
||||||
|
let (to_linear, to_color_space) = converter_funcs(color_space_conversion);
|
||||||
|
let (premultiplier, demultiplier) = alpha_multiplier_funcs(premultiply);
|
||||||
|
|
||||||
|
// If both options are false, there is no preprocessing on the pixel valus
|
||||||
|
// and we can skip the loop.
|
||||||
|
if premultiply || color_space_conversion {
|
||||||
|
for i in 0..num_input_pixels {
|
||||||
|
for j in 0..3 {
|
||||||
|
input_image[4 * i + j] =
|
||||||
|
premultiplier(to_linear(input_image[4 * i + j]), input_image[4 * i + 3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut resizer = resize::new(
|
||||||
|
input_width,
|
||||||
|
input_height,
|
||||||
|
output_width,
|
||||||
|
output_height,
|
||||||
|
RGBA,
|
||||||
|
typ,
|
||||||
|
);
|
||||||
|
let mut output_image = Vec::<u8>::with_capacity(num_output_pixels * 4);
|
||||||
|
output_image.resize(num_output_pixels * 4, 0);
|
||||||
|
resizer.resize(input_image.as_slice(), output_image.as_mut_slice());
|
||||||
|
|
||||||
|
if premultiply || color_space_conversion {
|
||||||
|
for i in 0..num_output_pixels {
|
||||||
|
for j in 0..3 {
|
||||||
|
// We don’t need to worry about division by zero, as division by zero
|
||||||
|
// is well-defined on floats to return ±Inf. ±Inf is converted to 0
|
||||||
|
// when casting to integers.
|
||||||
|
output_image[4 * i + j] = to_color_space(demultiplier(
|
||||||
|
output_image[4 * i + j],
|
||||||
|
output_image[4 * i + 3],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output_image;
|
||||||
|
}
|
||||||
29
codecs/resize/src/srgb.rs
Normal file
29
codecs/resize/src/srgb.rs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
pub trait Clamp: std::cmp::PartialOrd + Sized {
|
||||||
|
fn clamp(self, min: Self, max: Self) -> Self {
|
||||||
|
if self.lt(&min) {
|
||||||
|
min
|
||||||
|
} else if self.gt(&max) {
|
||||||
|
max
|
||||||
|
} else {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clamp for f32 {}
|
||||||
|
|
||||||
|
pub fn srgb_to_linear(v: f32) -> f32 {
|
||||||
|
if v < 0.04045 {
|
||||||
|
v / 12.92
|
||||||
|
} else {
|
||||||
|
((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn linear_to_srgb(v: f32) -> f32 {
|
||||||
|
if v < 0.0031308 {
|
||||||
|
v * 12.92
|
||||||
|
} else {
|
||||||
|
(1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
17
codecs/resize/src/utils.rs
Normal file
17
codecs/resize/src/utils.rs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
// When the `console_error_panic_hook` feature is enabled, we can call the
|
||||||
|
// `set_panic_hook` function at least once during initialization, and then
|
||||||
|
// we will get better error messages if our code ever panics.
|
||||||
|
//
|
||||||
|
// For more details see
|
||||||
|
// https://github.com/rustwasm/console_error_panic_hook#readme
|
||||||
|
if #[cfg(feature = "console_error_panic_hook")] {
|
||||||
|
extern crate console_error_panic_hook;
|
||||||
|
pub use self::console_error_panic_hook::set_once as set_panic_hook;
|
||||||
|
} else {
|
||||||
|
#[inline]
|
||||||
|
pub fn set_panic_hook() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
27
package-lock.json
generated
27
package-lock.json
generated
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "squoosh",
|
"name": "squoosh",
|
||||||
"version": "1.3.4",
|
"version": "1.6.0",
|
||||||
"lockfileVersion": 1,
|
"lockfileVersion": 1,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -124,9 +124,9 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"@types/node": {
|
"@types/node": {
|
||||||
"version": "10.12.29",
|
"version": "10.12.30",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.29.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.30.tgz",
|
||||||
"integrity": "sha512-J/tnbnj8HcsBgCe2apZbdUpQ7hs4d7oZNTYA5bekWdP0sr2NGsOpI/HRdDroEi209tEvTcTtxhD0FfED3DhEcw==",
|
"integrity": "sha512-nsqTN6zUcm9xtdJiM9OvOJ5EF0kOI8f1Zuug27O/rgtxCRJHGqncSWfCMZUP852dCKPsDsYXGvBhxfRjDBkF5Q==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"@types/pretty-bytes": {
|
"@types/pretty-bytes": {
|
||||||
@@ -3232,13 +3232,14 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"copy-webpack-plugin": {
|
"copy-webpack-plugin": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-5.0.1.tgz",
|
||||||
"integrity": "sha512-iiDj+8nnZeW/i8vYJ3+ABSZkOefJnDYIGLojiZKKFDvf1wcEInABXH1+hN7axQMn04qvJxKjgVOee0e14XPtCg==",
|
"integrity": "sha512-yMTURAkYZO/6h6pGMbHQl2jpKtRNC+0Cy/4kRRP6qUHmpbGGAzNnyMecE6aHgGFCb4ksrL3YcDqYGb8ds3J9cw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"requires": {
|
"requires": {
|
||||||
"cacache": "^11.3.1",
|
"cacache": "^11.3.1",
|
||||||
"find-cache-dir": "^2.0.0",
|
"find-cache-dir": "^2.0.0",
|
||||||
|
"glob-parent": "^3.1.0",
|
||||||
"globby": "^7.1.1",
|
"globby": "^7.1.1",
|
||||||
"is-glob": "^4.0.0",
|
"is-glob": "^4.0.0",
|
||||||
"loader-utils": "^1.1.0",
|
"loader-utils": "^1.1.0",
|
||||||
@@ -3256,9 +3257,9 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"p-limit": {
|
"p-limit": {
|
||||||
"version": "2.1.0",
|
"version": "2.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz",
|
||||||
"integrity": "sha512-NhURkNcrVB+8hNfLuysU8enY5xn2KXphsHBaC2YmRNTZRc7RWusw6apSpdEj3jo4CMb6W9nrF6tTnsJsJeyu6g==",
|
"integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"requires": {
|
"requires": {
|
||||||
"p-try": "^2.0.0"
|
"p-try": "^2.0.0"
|
||||||
@@ -15178,9 +15179,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"typed-css-modules": {
|
"typed-css-modules": {
|
||||||
"version": "0.4.1",
|
"version": "0.4.2",
|
||||||
"resolved": "https://registry.npmjs.org/typed-css-modules/-/typed-css-modules-0.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/typed-css-modules/-/typed-css-modules-0.4.2.tgz",
|
||||||
"integrity": "sha512-aOMv55N5s2oRYnlitEDQXdBjSqULg/X68UeYs2AwSZyUk7TgrOZlnZ38/ZEpA1GF5wcHAovk4YR7Db+mYtoL2A==",
|
"integrity": "sha512-8L6efZplgnraEw1RWz1Nc6swfLm6PAawivvdwFhzkFa3CJu+cPbK9712i4CAAf+JA0/Ufe19iDTPIk1WSpoz/w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"requires": {
|
"requires": {
|
||||||
"camelcase": "^4.1.0",
|
"camelcase": "^4.1.0",
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "squoosh",
|
"name": "squoosh",
|
||||||
"version": "1.3.4",
|
"version": "1.6.0",
|
||||||
"license": "apache-2.0",
|
"license": "apache-2.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "webpack-dev-server --host 0.0.0.0 --hot",
|
"start": "webpack-dev-server --host 0.0.0.0 --hot",
|
||||||
"build": "webpack -p",
|
"build": "webpack -p",
|
||||||
"lint": "tslint -c tslint.json -p tsconfig.json -t verbose 'src/**/*.{ts,tsx,js,jsx}'",
|
"lint": "tslint -c tslint.json -p tsconfig.json -t verbose",
|
||||||
"lintfix": "tslint -c tslint.json -p tsconfig.json -t verbose --fix 'src/**/*.{ts,tsx,js,jsx}'",
|
"lintfix": "tslint -c tslint.json -p tsconfig.json -t verbose --fix 'src/**/*.{ts,tsx,js,jsx}'",
|
||||||
"sizereport": "node config/size-report.js"
|
"sizereport": "node config/size-report.js"
|
||||||
},
|
},
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "10.12.29",
|
"@types/node": "10.12.30",
|
||||||
"@types/pretty-bytes": "5.1.0",
|
"@types/pretty-bytes": "5.1.0",
|
||||||
"@types/webassembly-js-api": "0.0.2",
|
"@types/webassembly-js-api": "0.0.2",
|
||||||
"@webcomponents/custom-elements": "1.2.1",
|
"@webcomponents/custom-elements": "1.2.1",
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
"classnames": "2.2.6",
|
"classnames": "2.2.6",
|
||||||
"clean-webpack-plugin": "1.0.1",
|
"clean-webpack-plugin": "1.0.1",
|
||||||
"comlink": "3.1.1",
|
"comlink": "3.1.1",
|
||||||
"copy-webpack-plugin": "5.0.0",
|
"copy-webpack-plugin": "5.0.1",
|
||||||
"critters-webpack-plugin": "2.3.0",
|
"critters-webpack-plugin": "2.3.0",
|
||||||
"css-loader": "1.0.1",
|
"css-loader": "1.0.1",
|
||||||
"ejs": "2.6.1",
|
"ejs": "2.6.1",
|
||||||
@@ -63,7 +63,7 @@
|
|||||||
"tslint-config-airbnb": "5.11.1",
|
"tslint-config-airbnb": "5.11.1",
|
||||||
"tslint-config-semistandard": "7.0.0",
|
"tslint-config-semistandard": "7.0.0",
|
||||||
"tslint-react": "3.6.0",
|
"tslint-react": "3.6.0",
|
||||||
"typed-css-modules": "0.4.1",
|
"typed-css-modules": "0.4.2",
|
||||||
"typescript": "3.3.3333",
|
"typescript": "3.3.3333",
|
||||||
"url-loader": "1.1.2",
|
"url-loader": "1.1.2",
|
||||||
"webpack": "4.28.0",
|
"webpack": "4.28.0",
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import imagequant, { QuantizerModule } from '../../../codecs/imagequant/imagequant';
|
import imagequant, { QuantizerModule } from '../../../codecs/imagequant/imagequant';
|
||||||
import wasmUrl from '../../../codecs/imagequant/imagequant.wasm';
|
import wasmUrl from '../../../codecs/imagequant/imagequant.wasm';
|
||||||
import { QuantizeOptions } from './processor-meta';
|
import { QuantizeOptions } from './processor-meta';
|
||||||
import { initWasmModule } from '../util';
|
import { initEmscriptenModule } from '../util';
|
||||||
|
|
||||||
let emscriptenModule: Promise<QuantizerModule>;
|
let emscriptenModule: Promise<QuantizerModule>;
|
||||||
|
|
||||||
export async function process(data: ImageData, opts: QuantizeOptions): Promise<ImageData> {
|
export async function process(data: ImageData, opts: QuantizeOptions): Promise<ImageData> {
|
||||||
if (!emscriptenModule) emscriptenModule = initWasmModule(imagequant, wasmUrl);
|
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(imagequant, wasmUrl);
|
||||||
|
|
||||||
const module = await emscriptenModule;
|
const module = await emscriptenModule;
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg_enc/mozjpeg_enc';
|
import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg_enc/mozjpeg_enc';
|
||||||
import wasmUrl from '../../../codecs/mozjpeg_enc/mozjpeg_enc.wasm';
|
import wasmUrl from '../../../codecs/mozjpeg_enc/mozjpeg_enc.wasm';
|
||||||
import { EncodeOptions } from './encoder-meta';
|
import { EncodeOptions } from './encoder-meta';
|
||||||
import { initWasmModule } from '../util';
|
import { initEmscriptenModule } from '../util';
|
||||||
|
|
||||||
let emscriptenModule: Promise<MozJPEGModule>;
|
let emscriptenModule: Promise<MozJPEGModule>;
|
||||||
|
|
||||||
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
|
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
|
||||||
if (!emscriptenModule) emscriptenModule = initWasmModule(mozjpeg_enc, wasmUrl);
|
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(mozjpeg_enc, wasmUrl);
|
||||||
|
|
||||||
const module = await emscriptenModule;
|
const module = await emscriptenModule;
|
||||||
const resultView = module.encode(data.data, data.width, data.height, options);
|
const resultView = module.encode(data.data, data.width, data.height, options);
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import optipng, { OptiPngModule } from '../../../codecs/optipng/optipng';
|
import optipng, { OptiPngModule } from '../../../codecs/optipng/optipng';
|
||||||
import wasmUrl from '../../../codecs/optipng/optipng.wasm';
|
import wasmUrl from '../../../codecs/optipng/optipng.wasm';
|
||||||
import { EncodeOptions } from './encoder-meta';
|
import { EncodeOptions } from './encoder-meta';
|
||||||
import { initWasmModule } from '../util';
|
import { initEmscriptenModule } from '../util';
|
||||||
|
|
||||||
let emscriptenModule: Promise<OptiPngModule>;
|
let emscriptenModule: Promise<OptiPngModule>;
|
||||||
|
|
||||||
export async function compress(data: BufferSource, options: EncodeOptions): Promise<ArrayBuffer> {
|
export async function compress(data: BufferSource, options: EncodeOptions): Promise<ArrayBuffer> {
|
||||||
if (!emscriptenModule) emscriptenModule = initWasmModule(optipng, wasmUrl);
|
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(optipng, wasmUrl);
|
||||||
|
|
||||||
const module = await emscriptenModule;
|
const module = await emscriptenModule;
|
||||||
const resultView = module.compress(data, options);
|
const resultView = module.compress(data, options);
|
||||||
|
|||||||
@@ -28,6 +28,16 @@ async function rotate(
|
|||||||
return rotate(data, opts);
|
return rotate(data, opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resize(
|
||||||
|
data: ImageData, opts: import('../resize/processor-meta').WorkerResizeOptions,
|
||||||
|
): Promise<ImageData> {
|
||||||
|
const { resize } = await import(
|
||||||
|
/* webpackChunkName: "process-resize" */
|
||||||
|
'../resize/processor');
|
||||||
|
|
||||||
|
return resize(data, opts);
|
||||||
|
}
|
||||||
|
|
||||||
async function optiPngEncode(
|
async function optiPngEncode(
|
||||||
data: BufferSource, options: import('../optipng/encoder-meta').EncodeOptions,
|
data: BufferSource, options: import('../optipng/encoder-meta').EncodeOptions,
|
||||||
): Promise<ArrayBuffer> {
|
): Promise<ArrayBuffer> {
|
||||||
@@ -53,7 +63,7 @@ async function webpDecode(data: ArrayBuffer): Promise<ImageData> {
|
|||||||
return decode(data);
|
return decode(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exports = { mozjpegEncode, quantize, rotate, optiPngEncode, webpEncode, webpDecode };
|
const exports = { mozjpegEncode, quantize, rotate, resize, optiPngEncode, webpEncode, webpDecode };
|
||||||
export type ProcessorWorkerApi = typeof exports;
|
export type ProcessorWorkerApi = typeof exports;
|
||||||
|
|
||||||
expose(exports, self);
|
expose(exports, self);
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import { EncodeOptions as OptiPNGEncoderOptions } from './optipng/encoder-meta';
|
|||||||
import { EncodeOptions as WebPEncoderOptions } from './webp/encoder-meta';
|
import { EncodeOptions as WebPEncoderOptions } from './webp/encoder-meta';
|
||||||
import { EncodeOptions as BrowserJPEGOptions } from './browser-jpeg/encoder-meta';
|
import { EncodeOptions as BrowserJPEGOptions } from './browser-jpeg/encoder-meta';
|
||||||
import { EncodeOptions as BrowserWebpEncodeOptions } from './browser-webp/encoder-meta';
|
import { EncodeOptions as BrowserWebpEncodeOptions } from './browser-webp/encoder-meta';
|
||||||
import { BitmapResizeOptions, VectorResizeOptions } from './resize/processor-meta';
|
import { BrowserResizeOptions, VectorResizeOptions } from './resize/processor-meta';
|
||||||
import { resize, vectorResize } from './resize/processor';
|
import { browserResize, vectorResize } from './resize/processor-sync';
|
||||||
import * as browserBMP from './browser-bmp/encoder';
|
import * as browserBMP from './browser-bmp/encoder';
|
||||||
import * as browserPNG from './browser-png/encoder';
|
import * as browserPNG from './browser-png/encoder';
|
||||||
import * as browserJPEG from './browser-jpeg/encoder';
|
import * as browserJPEG from './browser-jpeg/encoder';
|
||||||
@@ -130,6 +130,13 @@ export default class Processor {
|
|||||||
return this._workerApi!.rotate(data, opts);
|
return this._workerApi!.rotate(data, opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Processor._processingJob({ needsWorker: true })
|
||||||
|
workerResize(
|
||||||
|
data: ImageData, opts: import('./resize/processor-meta').WorkerResizeOptions,
|
||||||
|
): Promise<ImageData> {
|
||||||
|
return this._workerApi!.resize(data, opts);
|
||||||
|
}
|
||||||
|
|
||||||
@Processor._processingJob({ needsWorker: true })
|
@Processor._processingJob({ needsWorker: true })
|
||||||
mozjpegEncode(
|
mozjpegEncode(
|
||||||
data: ImageData, opts: MozJPEGEncoderOptions,
|
data: ImageData, opts: MozJPEGEncoderOptions,
|
||||||
@@ -202,9 +209,9 @@ export default class Processor {
|
|||||||
|
|
||||||
// Synchronous jobs
|
// Synchronous jobs
|
||||||
|
|
||||||
resize(data: ImageData, opts: BitmapResizeOptions) {
|
resize(data: ImageData, opts: BrowserResizeOptions) {
|
||||||
this.abortCurrent();
|
this.abortCurrent();
|
||||||
return resize(data, opts);
|
return browserResize(data, opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
vectorResize(data: HTMLImageElement, opts: VectorResizeOptions) {
|
vectorResize(data: HTMLImageElement, opts: VectorResizeOptions) {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { h, Component } from 'preact';
|
import { h, Component } from 'preact';
|
||||||
import linkState from 'linkstate';
|
import linkState from 'linkstate';
|
||||||
import { bind, linkRef } from '../../lib/initial-util';
|
import { bind, linkRef } from '../../lib/initial-util';
|
||||||
import { inputFieldValueAsNumber, inputFieldValue, preventDefault } from '../../lib/util';
|
import {
|
||||||
import { ResizeOptions } from './processor-meta';
|
inputFieldValueAsNumber, inputFieldValue, preventDefault, inputFieldChecked,
|
||||||
|
} from '../../lib/util';
|
||||||
|
import { ResizeOptions, isWorkerOptions } from './processor-meta';
|
||||||
import * as style from '../../components/Options/style.scss';
|
import * as style from '../../components/Options/style.scss';
|
||||||
import Checkbox from '../../components/checkbox';
|
import Checkbox from '../../components/checkbox';
|
||||||
import Expander from '../../components/expander';
|
import Expander from '../../components/expander';
|
||||||
@@ -38,6 +40,8 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
width: inputFieldValueAsNumber(width),
|
width: inputFieldValueAsNumber(width),
|
||||||
height: inputFieldValueAsNumber(height),
|
height: inputFieldValueAsNumber(height),
|
||||||
method: form.resizeMethod.value,
|
method: form.resizeMethod.value,
|
||||||
|
premultiply: inputFieldChecked(form.premultiply, true),
|
||||||
|
linearRGB: inputFieldChecked(form.linearRGB, true),
|
||||||
// Casting, as the formfield only returns the correct values.
|
// Casting, as the formfield only returns the correct values.
|
||||||
fitMethod: inputFieldValue(form.fitMethod, options.fitMethod) as ResizeOptions['fitMethod'],
|
fitMethod: inputFieldValue(form.fitMethod, options.fitMethod) as ResizeOptions['fitMethod'],
|
||||||
};
|
};
|
||||||
@@ -87,6 +91,10 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
onChange={this.onChange}
|
onChange={this.onChange}
|
||||||
>
|
>
|
||||||
{isVector && <option value="vector">Vector</option>}
|
{isVector && <option value="vector">Vector</option>}
|
||||||
|
<option value="lanczos3">Lanczos3</option>
|
||||||
|
<option value="mitchell">Mitchell</option>
|
||||||
|
<option value="catrom">Catmull-Rom</option>
|
||||||
|
<option value="triangle">Triangle (bilinear)</option>
|
||||||
<option value="browser-pixelated">Browser pixelated</option>
|
<option value="browser-pixelated">Browser pixelated</option>
|
||||||
<option value="browser-low">Browser low quality</option>
|
<option value="browser-low">Browser low quality</option>
|
||||||
<option value="browser-medium">Browser medium quality</option>
|
<option value="browser-medium">Browser medium quality</option>
|
||||||
@@ -117,6 +125,30 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
onInput={this.onHeightInput}
|
onInput={this.onHeightInput}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<Expander>
|
||||||
|
{isWorkerOptions(options) ?
|
||||||
|
<label class={style.optionInputFirst}>
|
||||||
|
<Checkbox
|
||||||
|
name="premultiply"
|
||||||
|
checked={options.premultiply}
|
||||||
|
onChange={this.onChange}
|
||||||
|
/>
|
||||||
|
Premultiply alpha channel
|
||||||
|
</label>
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
{isWorkerOptions(options) ?
|
||||||
|
<label class={style.optionInputFirst}>
|
||||||
|
<Checkbox
|
||||||
|
name="linearRGB"
|
||||||
|
checked={options.linearRGB}
|
||||||
|
onChange={this.onChange}
|
||||||
|
/>
|
||||||
|
Linear RGB
|
||||||
|
</label>
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
</Expander>
|
||||||
<label class={style.optionInputFirst}>
|
<label class={style.optionInputFirst}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
name="maintainAspect"
|
name="maintainAspect"
|
||||||
|
|||||||
@@ -1,26 +1,46 @@
|
|||||||
type BitmapResizeMethods = 'browser-pixelated' | 'browser-low' | 'browser-medium' | 'browser-high';
|
type BrowserResizeMethods = 'browser-pixelated' | 'browser-low' | 'browser-medium' | 'browser-high';
|
||||||
|
type WorkerResizeMethods = 'triangle' | 'catrom' | 'mitchell' | 'lanczos3';
|
||||||
|
const workerResizeMethods: WorkerResizeMethods[] = ['triangle', 'catrom', 'mitchell', 'lanczos3'];
|
||||||
|
|
||||||
export interface ResizeOptions {
|
export type ResizeOptions = BrowserResizeOptions | WorkerResizeOptions | VectorResizeOptions;
|
||||||
|
|
||||||
|
export interface ResizeOptionsCommon {
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
method: 'vector' | BitmapResizeMethods;
|
|
||||||
fitMethod: 'stretch' | 'contain';
|
fitMethod: 'stretch' | 'contain';
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BitmapResizeOptions extends ResizeOptions {
|
export interface BrowserResizeOptions extends ResizeOptionsCommon {
|
||||||
method: BitmapResizeMethods;
|
method: BrowserResizeMethods;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VectorResizeOptions extends ResizeOptions {
|
export interface WorkerResizeOptions extends ResizeOptionsCommon {
|
||||||
|
method: WorkerResizeMethods;
|
||||||
|
premultiply: boolean;
|
||||||
|
linearRGB: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VectorResizeOptions extends ResizeOptionsCommon {
|
||||||
method: 'vector';
|
method: 'vector';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return whether a set of options are worker resize options.
|
||||||
|
*
|
||||||
|
* @param opts
|
||||||
|
*/
|
||||||
|
export function isWorkerOptions(opts: ResizeOptions): opts is WorkerResizeOptions {
|
||||||
|
return (workerResizeMethods as string[]).includes(opts.method);
|
||||||
|
}
|
||||||
|
|
||||||
export const defaultOptions: ResizeOptions = {
|
export const defaultOptions: ResizeOptions = {
|
||||||
// Width and height will always default to the image size.
|
// Width and height will always default to the image size.
|
||||||
// This is set elsewhere.
|
// This is set elsewhere.
|
||||||
width: 1,
|
width: 1,
|
||||||
height: 1,
|
height: 1,
|
||||||
// This will be set to 'vector' if the input is SVG.
|
// This will be set to 'vector' if the input is SVG.
|
||||||
method: 'browser-high',
|
method: 'lanczos3',
|
||||||
fitMethod: 'stretch',
|
fitMethod: 'stretch',
|
||||||
|
premultiply: true,
|
||||||
|
linearRGB: true,
|
||||||
};
|
};
|
||||||
|
|||||||
35
src/codecs/resize/processor-sync.ts
Normal file
35
src/codecs/resize/processor-sync.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { nativeResize, NativeResizeMethod, drawableToImageData } from '../../lib/util';
|
||||||
|
import { BrowserResizeOptions, VectorResizeOptions } from './processor-meta';
|
||||||
|
import { getContainOffsets } from './util';
|
||||||
|
|
||||||
|
export function browserResize(data: ImageData, opts: BrowserResizeOptions): ImageData {
|
||||||
|
let sx = 0;
|
||||||
|
let sy = 0;
|
||||||
|
let sw = data.width;
|
||||||
|
let sh = data.height;
|
||||||
|
|
||||||
|
if (opts.fitMethod === 'contain') {
|
||||||
|
({ sx, sy, sw, sh } = getContainOffsets(sw, sh, opts.width, opts.height));
|
||||||
|
}
|
||||||
|
|
||||||
|
return nativeResize(
|
||||||
|
data, sx, sy, sw, sh, opts.width, opts.height,
|
||||||
|
opts.method.slice('browser-'.length) as NativeResizeMethod,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function vectorResize(data: HTMLImageElement, opts: VectorResizeOptions): ImageData {
|
||||||
|
let sx = 0;
|
||||||
|
let sy = 0;
|
||||||
|
let sw = data.width;
|
||||||
|
let sh = data.height;
|
||||||
|
|
||||||
|
if (opts.fitMethod === 'contain') {
|
||||||
|
({ sx, sy, sw, sh } = getContainOffsets(sw, sh, opts.width, opts.height));
|
||||||
|
}
|
||||||
|
|
||||||
|
return drawableToImageData(data, {
|
||||||
|
sx, sy, sw, sh,
|
||||||
|
width: opts.width, height: opts.height,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,49 +1,52 @@
|
|||||||
import { nativeResize, NativeResizeMethod, drawableToImageData } from '../../lib/util';
|
import wasmUrl from '../../../codecs/resize/pkg/resize_bg.wasm';
|
||||||
import { BitmapResizeOptions, VectorResizeOptions } from './processor-meta';
|
import '../../../codecs/resize/pkg/resize';
|
||||||
|
import { WorkerResizeOptions } from './processor-meta';
|
||||||
|
import { getContainOffsets } from './util';
|
||||||
|
|
||||||
function getContainOffsets(sw: number, sh: number, dw: number, dh: number) {
|
interface WasmBindgenExports {
|
||||||
const currentAspect = sw / sh;
|
resize: typeof import('../../../codecs/resize/pkg/resize').resize;
|
||||||
const endAspect = dw / dh;
|
|
||||||
|
|
||||||
if (endAspect > currentAspect) {
|
|
||||||
const newSh = sw / endAspect;
|
|
||||||
const newSy = (sh - newSh) / 2;
|
|
||||||
return { sw, sh: newSh, sx: 0, sy: newSy };
|
|
||||||
}
|
|
||||||
|
|
||||||
const newSw = sh * endAspect;
|
|
||||||
const newSx = (sw - newSw) / 2;
|
|
||||||
return { sh, sw: newSw, sx: newSx, sy: 0 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resize(data: ImageData, opts: BitmapResizeOptions): ImageData {
|
type WasmBindgen = ((url: string) => Promise<void>) & WasmBindgenExports;
|
||||||
let sx = 0;
|
|
||||||
let sy = 0;
|
|
||||||
let sw = data.width;
|
|
||||||
let sh = data.height;
|
|
||||||
|
|
||||||
if (opts.fitMethod === 'contain') {
|
declare var wasm_bindgen: WasmBindgen;
|
||||||
({ sx, sy, sw, sh } = getContainOffsets(sw, sh, opts.width, opts.height));
|
|
||||||
|
const ready = wasm_bindgen(wasmUrl);
|
||||||
|
|
||||||
|
function crop(data: ImageData, sx: number, sy: number, sw: number, sh: number): ImageData {
|
||||||
|
const inputPixels = new Uint32Array(data.data.buffer);
|
||||||
|
|
||||||
|
// Copy within the same buffer for speed and memory efficiency.
|
||||||
|
for (let y = 0; y < sh; y += 1) {
|
||||||
|
const start = ((y + sy) * data.width) + sx;
|
||||||
|
inputPixels.copyWithin(y * sw, start, start + sw);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nativeResize(
|
return new ImageData(
|
||||||
data, sx, sy, sw, sh, opts.width, opts.height,
|
new Uint8ClampedArray(inputPixels.buffer.slice(0, sw * sh * 4)),
|
||||||
opts.method.slice('browser-'.length) as NativeResizeMethod,
|
sw, sh,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function vectorResize(data: HTMLImageElement, opts: VectorResizeOptions): ImageData {
|
/** Resize methods by index */
|
||||||
let sx = 0;
|
const resizeMethods: WorkerResizeOptions['method'][] = [
|
||||||
let sy = 0;
|
'triangle', 'catrom', 'mitchell', 'lanczos3',
|
||||||
let sw = data.width;
|
];
|
||||||
let sh = data.height;
|
|
||||||
|
export async function resize(data: ImageData, opts: WorkerResizeOptions): Promise<ImageData> {
|
||||||
|
let input = data;
|
||||||
|
|
||||||
if (opts.fitMethod === 'contain') {
|
if (opts.fitMethod === 'contain') {
|
||||||
({ sx, sy, sw, sh } = getContainOffsets(sw, sh, opts.width, opts.height));
|
const { sx, sy, sw, sh } = getContainOffsets(data.width, data.height, opts.width, opts.height);
|
||||||
|
input = crop(input, Math.round(sx), Math.round(sy), Math.round(sw), Math.round(sh));
|
||||||
}
|
}
|
||||||
|
|
||||||
return drawableToImageData(data, {
|
await ready;
|
||||||
sx, sy, sw, sh,
|
|
||||||
width: opts.width, height: opts.height,
|
const result = wasm_bindgen.resize(
|
||||||
});
|
new Uint8Array(input.data.buffer), input.width, input.height, opts.width, opts.height,
|
||||||
|
resizeMethods.indexOf(opts.method), opts.premultiply, opts.linearRGB,
|
||||||
|
);
|
||||||
|
|
||||||
|
return new ImageData(new Uint8ClampedArray(result.buffer), opts.width, opts.height);
|
||||||
}
|
}
|
||||||
|
|||||||
14
src/codecs/resize/util.ts
Normal file
14
src/codecs/resize/util.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
export function getContainOffsets(sw: number, sh: number, dw: number, dh: number) {
|
||||||
|
const currentAspect = sw / sh;
|
||||||
|
const endAspect = dw / dh;
|
||||||
|
|
||||||
|
if (endAspect > currentAspect) {
|
||||||
|
const newSh = sw / endAspect;
|
||||||
|
const newSy = (sh - newSh) / 2;
|
||||||
|
return { sw, sh: newSh, sx: 0, sy: newSy };
|
||||||
|
}
|
||||||
|
|
||||||
|
const newSw = sh * endAspect;
|
||||||
|
const newSx = (sw - newSw) / 2;
|
||||||
|
return { sh, sw: newSw, sx: newSx, sy: 0 };
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ type ModuleFactory<M extends EmscriptenWasm.Module> = (
|
|||||||
opts: EmscriptenWasm.ModuleOpts,
|
opts: EmscriptenWasm.ModuleOpts,
|
||||||
) => M;
|
) => M;
|
||||||
|
|
||||||
export function initWasmModule<T extends EmscriptenWasm.Module>(
|
export function initEmscriptenModule<T extends EmscriptenWasm.Module>(
|
||||||
moduleFactory: ModuleFactory<T>,
|
moduleFactory: ModuleFactory<T>,
|
||||||
wasmUrl: string,
|
wasmUrl: string,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import webp_dec, { WebPModule } from '../../../codecs/webp_dec/webp_dec';
|
import webp_dec, { WebPModule } from '../../../codecs/webp_dec/webp_dec';
|
||||||
import wasmUrl from '../../../codecs/webp_dec/webp_dec.wasm';
|
import wasmUrl from '../../../codecs/webp_dec/webp_dec.wasm';
|
||||||
import { initWasmModule } from '../util';
|
import { initEmscriptenModule } from '../util';
|
||||||
|
|
||||||
let emscriptenModule: Promise<WebPModule>;
|
let emscriptenModule: Promise<WebPModule>;
|
||||||
|
|
||||||
export async function decode(data: ArrayBuffer): Promise<ImageData> {
|
export async function decode(data: ArrayBuffer): Promise<ImageData> {
|
||||||
if (!emscriptenModule) emscriptenModule = initWasmModule(webp_dec, wasmUrl);
|
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(webp_dec, wasmUrl);
|
||||||
|
|
||||||
const module = await emscriptenModule;
|
const module = await emscriptenModule;
|
||||||
const rawImage = module.decode(data);
|
const rawImage = module.decode(data);
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import webp_enc, { WebPModule } from '../../../codecs/webp_enc/webp_enc';
|
import webp_enc, { WebPModule } from '../../../codecs/webp_enc/webp_enc';
|
||||||
import wasmUrl from '../../../codecs/webp_enc/webp_enc.wasm';
|
import wasmUrl from '../../../codecs/webp_enc/webp_enc.wasm';
|
||||||
import { EncodeOptions } from './encoder-meta';
|
import { EncodeOptions } from './encoder-meta';
|
||||||
import { initWasmModule } from '../util';
|
import { initEmscriptenModule } from '../util';
|
||||||
|
|
||||||
let emscriptenModule: Promise<WebPModule>;
|
let emscriptenModule: Promise<WebPModule>;
|
||||||
|
|
||||||
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
|
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
|
||||||
if (!emscriptenModule) emscriptenModule = initWasmModule(webp_enc, wasmUrl);
|
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(webp_enc, wasmUrl);
|
||||||
|
|
||||||
const module = await emscriptenModule;
|
const module = await emscriptenModule;
|
||||||
const resultView = module.encode(data.data, data.width, data.height, options);
|
const resultView = module.encode(data.data, data.width, data.height, options);
|
||||||
|
|||||||
@@ -18,20 +18,14 @@ import * as browserTIFF from '../../codecs/browser-tiff/encoder-meta';
|
|||||||
import * as browserJP2 from '../../codecs/browser-jp2/encoder-meta';
|
import * as browserJP2 from '../../codecs/browser-jp2/encoder-meta';
|
||||||
import * as browserBMP from '../../codecs/browser-bmp/encoder-meta';
|
import * as browserBMP from '../../codecs/browser-bmp/encoder-meta';
|
||||||
import * as browserPDF from '../../codecs/browser-pdf/encoder-meta';
|
import * as browserPDF from '../../codecs/browser-pdf/encoder-meta';
|
||||||
import {
|
import { EncoderState, EncoderType, EncoderOptions, encoderMap } from '../../codecs/encoders';
|
||||||
EncoderState,
|
import { PreprocessorState, defaultPreprocessorState } from '../../codecs/preprocessors';
|
||||||
EncoderType,
|
|
||||||
EncoderOptions,
|
|
||||||
encoderMap,
|
|
||||||
} from '../../codecs/encoders';
|
|
||||||
import {
|
|
||||||
PreprocessorState,
|
|
||||||
defaultPreprocessorState,
|
|
||||||
} from '../../codecs/preprocessors';
|
|
||||||
import { decodeImage } from '../../codecs/decoders';
|
import { decodeImage } from '../../codecs/decoders';
|
||||||
import { cleanMerge, cleanSet } from '../../lib/clean-modify';
|
import { cleanMerge, cleanSet } from '../../lib/clean-modify';
|
||||||
import Processor from '../../codecs/processor';
|
import Processor from '../../codecs/processor';
|
||||||
import { VectorResizeOptions, BitmapResizeOptions } from '../../codecs/resize/processor-meta';
|
import {
|
||||||
|
BrowserResizeOptions, isWorkerOptions as isWorkerResizeOptions,
|
||||||
|
} from '../../codecs/resize/processor-meta';
|
||||||
import './custom-els/MultiPanel';
|
import './custom-els/MultiPanel';
|
||||||
import Results from '../results';
|
import Results from '../results';
|
||||||
import { ExpandIcon, CopyAcrossIconProps } from '../../lib/icons';
|
import { ExpandIcon, CopyAcrossIconProps } from '../../lib/icons';
|
||||||
@@ -110,10 +104,12 @@ async function preprocessImage(
|
|||||||
if (preprocessData.resize.method === 'vector' && source.vectorImage) {
|
if (preprocessData.resize.method === 'vector' && source.vectorImage) {
|
||||||
result = processor.vectorResize(
|
result = processor.vectorResize(
|
||||||
source.vectorImage,
|
source.vectorImage,
|
||||||
preprocessData.resize as VectorResizeOptions,
|
preprocessData.resize,
|
||||||
);
|
);
|
||||||
|
} else if (isWorkerResizeOptions(preprocessData.resize)) {
|
||||||
|
result = await processor.workerResize(result, preprocessData.resize);
|
||||||
} else {
|
} else {
|
||||||
result = processor.resize(result, preprocessData.resize as BitmapResizeOptions);
|
result = processor.resize(result, preprocessData.resize as BrowserResizeOptions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (preprocessData.quantizer.enabled) {
|
if (preprocessData.quantizer.enabled) {
|
||||||
@@ -441,7 +437,7 @@ export default class Compress extends Component<Props, State> {
|
|||||||
newState = cleanMerge(newState, `sides.${i}.latestSettings.preprocessorState.resize`, {
|
newState = cleanMerge(newState, `sides.${i}.latestSettings.preprocessorState.resize`, {
|
||||||
width: processed.width,
|
width: processed.width,
|
||||||
height: processed.height,
|
height: processed.height,
|
||||||
method: vectorImage ? 'vector' : 'browser-high',
|
method: vectorImage ? 'vector' : 'lanczos3',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user