@jimp/wasm-jxl 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +103 -2
- package/dist/browser/header.d.ts +27 -0
- package/dist/browser/header.d.ts.map +1 -0
- package/dist/browser/header.js +265 -0
- package/dist/browser/header.js.map +1 -0
- package/dist/browser/index.d.ts +52 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +156 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/load-wasm-browser.d.mts.map +1 -0
- package/dist/browser/load-wasm-browser.mjs.map +1 -0
- package/dist/browser/load-wasm.d.ts +3 -0
- package/dist/browser/load-wasm.js +6 -0
- package/dist/browser/package.json +3 -0
- package/dist/esm/header.d.ts +27 -0
- package/dist/esm/header.d.ts.map +1 -0
- package/dist/esm/header.js +265 -0
- package/dist/esm/header.js.map +1 -0
- package/dist/esm/index.d.ts +52 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +156 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/load-wasm.d.ts +6 -0
- package/dist/esm/load-wasm.d.ts.map +1 -0
- package/dist/esm/load-wasm.js +12 -0
- package/dist/esm/load-wasm.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +76 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Oliver Moran
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,104 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@jimp/wasm-jxl`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A format plugin for Jimp that adds support for JPEG XL images using [libjxl](https://github.com/libjxl/libjxl), as compiled to WebAssembly by [`@jsquash/jxl`](https://www.npmjs.com/package/@jsquash/jxl).
|
|
4
|
+
|
|
5
|
+
> NOTE: Only works in esm environments.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install jimp @jimp/core @jimp/wasm-jxl
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createJimp } from "@jimp/core";
|
|
15
|
+
import { defaultFormats, defaultPlugins } from "jimp";
|
|
16
|
+
import jxl from "@jimp/wasm-jxl";
|
|
17
|
+
|
|
18
|
+
// A custom jimp that supports JPEG XL
|
|
19
|
+
const Jimp = createJimp({
|
|
20
|
+
formats: [...defaultFormats, jxl],
|
|
21
|
+
plugins: defaultPlugins,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const image = await Jimp.read("photo.jxl");
|
|
25
|
+
|
|
26
|
+
await image.write("visually-lossless.jxl");
|
|
27
|
+
await image.write("lossless.jxl", { lossless: true });
|
|
28
|
+
await image.write("smaller.jxl", { quality: 75, effort: 9 });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Supported images
|
|
32
|
+
|
|
33
|
+
- Reads bare codestreams and files in the JPEG XL container, including recompressed JPEGs
|
|
34
|
+
- Grayscale and RGB, with or without alpha, at any bit depth, decoded to 8-bit RGBA
|
|
35
|
+
- Other colour spaces, like Display P3 or an embedded ICC profile, are converted to sRGB when decoding
|
|
36
|
+
- Animations decode their first frame
|
|
37
|
+
|
|
38
|
+
HDR images (with the PQ or HLG transfer function) throw an error: the codec would convert them to 8-bit sRGB without tone mapping, so they'd come out much too dark.
|
|
39
|
+
|
|
40
|
+
Writing always uses 8-bit sRGB with alpha, as a bare codestream. Images in another colour space (like Display P3) are converted to sRGB first.
|
|
41
|
+
|
|
42
|
+
Lossless files keep every pixel exactly. But the codec decodes in floating point and converts to sRGB, which can put a few colour samples 1 off (alpha is exact). Other decoders, like `djxl` and browsers, read the exact pixels.
|
|
43
|
+
|
|
44
|
+
### Options
|
|
45
|
+
|
|
46
|
+
Encode options, passed to `write` or `getBuffer`:
|
|
47
|
+
|
|
48
|
+
| Option | Default | Description |
|
|
49
|
+
| ------------------- | ------- | ------------------------------------------------------------------------------------------ |
|
|
50
|
+
| `quality` | `90` | 0 to 100. `90` (the `cjxl` default) is visually lossless, and `100` is lossless |
|
|
51
|
+
| `lossless` | `false` | Keep every pixel, including alpha, exactly. `quality` is ignored |
|
|
52
|
+
| `effort` | `7` | 1 (fastest) to 9 (slowest, smallest files) |
|
|
53
|
+
| `progressive` | `false` | Let a partially downloaded file show at a lower quality first. Makes files a little larger |
|
|
54
|
+
| `lossyModular` | `false` | Use the modular mode for lossy images too. Can be better for graphics, worse for photos |
|
|
55
|
+
| `epf` | `-1` | Edge-preserving filter strength for lossy images, 0 (off) to 3. `-1` picks one |
|
|
56
|
+
| `decodingSpeedTier` | `0` | 0 to 4: higher makes lossy images faster to decode, and larger |
|
|
57
|
+
| `photonNoiseIso` | `0` | Add synthetic film grain to lossy images, like a photo taken at this ISO |
|
|
58
|
+
|
|
59
|
+
Numbers outside of their range are clamped. With lossy encoding alpha is compressed too, but fully transparent and opaque pixels stay that way at the default quality.
|
|
60
|
+
|
|
61
|
+
Decode options, passed to `Jimp.read` under the MIME type:
|
|
62
|
+
|
|
63
|
+
| Option | Default | Description |
|
|
64
|
+
| ------------------- | ------- | ------------------------------------------------------------------- |
|
|
65
|
+
| `maxResolutionInMP` | `100` | Reject images larger than this many megapixels before decoding them |
|
|
66
|
+
|
|
67
|
+
The codec has at most 2 GB of memory, which is enough for about 40 megapixels lossless, or 60 lossy. Larger images throw `Failed to decode the WxH JPEG XL image: the codec ran out of memory`.
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
const image = await Jimp.read("upload.jxl", {
|
|
71
|
+
"image/jxl": { maxResolutionInMP: 24 },
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Bundler Setup
|
|
76
|
+
|
|
77
|
+
Vite 8 and webpack 5 need no config. Vite 7 and earlier do:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
// vite.config.js
|
|
81
|
+
export default {
|
|
82
|
+
// @jsquash/jxl loads its wasm relative to its own files, which
|
|
83
|
+
// pre-bundling breaks in the dev server
|
|
84
|
+
optimizeDeps: { exclude: ["@jsquash/jxl"] },
|
|
85
|
+
// Its multi-threaded encoder runs in a worker that `vite build` can't
|
|
86
|
+
// bundle in the default iife format
|
|
87
|
+
worker: { format: "es" },
|
|
88
|
+
};
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
See the [Vite section of the WASM plugins guide](https://jimp-dev.github.io/jimp/guides/webp/#vite).
|
|
92
|
+
|
|
93
|
+
In the browser, pages that are [cross-origin isolated](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated) encode with the codec's multi-threaded build.
|
|
94
|
+
|
|
95
|
+
For runtimes where the codecs can't load their own wasm, like Cloudflare Workers, compile `@jsquash/jxl/codec/dec/jxl_dec.wasm` and `@jsquash/jxl/codec/enc/jxl_enc.wasm` and pass them in:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
import decoder from "@jsquash/jxl/codec/dec/jxl_dec.wasm";
|
|
99
|
+
import encoder from "@jsquash/jxl/codec/enc/jxl_enc.wasm";
|
|
100
|
+
|
|
101
|
+
const Jimp = createJimp({
|
|
102
|
+
formats: [...defaultFormats, () => jxl({ wasm: { decoder, encoder } })],
|
|
103
|
+
});
|
|
104
|
+
```
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the start of a JPEG XL codestream (ISO/IEC 18181-1): the image size
|
|
3
|
+
* and, when the file describes its colours with an enum rather than an ICC
|
|
4
|
+
* profile, the transfer function. Field encodings follow libjxl's
|
|
5
|
+
* `SizeHeader`, `ImageMetadata` and `ColorEncoding`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const TransferFunction: {
|
|
8
|
+
readonly PQ: 16;
|
|
9
|
+
readonly HLG: 18;
|
|
10
|
+
};
|
|
11
|
+
export interface JxlHeader {
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
/**
|
|
15
|
+
* The CICP transfer characteristic, e.g. 13 for sRGB. Undefined when the
|
|
16
|
+
* colours are described by an ICC profile or with a custom gamma, or if
|
|
17
|
+
* the header couldn't be read that far.
|
|
18
|
+
*/
|
|
19
|
+
transferFunction?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Reads the size, and the transfer function if it's in the header, of a
|
|
23
|
+
* JPEG XL codestream or container. Returns undefined if the data isn't
|
|
24
|
+
* JPEG XL or is too short to have a size.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readJxlHeader(data: Uint8Array): JxlHeader | undefined;
|
|
27
|
+
//# sourceMappingURL=header.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"header.d.ts","sourceRoot":"","sources":["../../src/header.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AASH,eAAO,MAAM,gBAAgB;aAC3B,EAAE,EAAE,EAAE;aACN,GAAG,EAAE,EAAE;CACC,CAAC;AAEX,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AA+QD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,UAAU,GAAG,SAAS,GAAG,SAAS,CAgCrE"}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the start of a JPEG XL codestream (ISO/IEC 18181-1): the image size
|
|
3
|
+
* and, when the file describes its colours with an enum rather than an ICC
|
|
4
|
+
* profile, the transfer function. Field encodings follow libjxl's
|
|
5
|
+
* `SizeHeader`, `ImageMetadata` and `ColorEncoding`.
|
|
6
|
+
*/
|
|
7
|
+
/** The ISOBMFF signature box of the container format (ISO/IEC 18181-2) */
|
|
8
|
+
const CONTAINER_SIGNATURE = [
|
|
9
|
+
0x00, 0x00, 0x00, 0x0c, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a,
|
|
10
|
+
];
|
|
11
|
+
/** The header fields are a few hundred bytes at most */
|
|
12
|
+
const MAX_HEADER_BYTES = 65536;
|
|
13
|
+
export const TransferFunction = {
|
|
14
|
+
PQ: 16,
|
|
15
|
+
HLG: 18,
|
|
16
|
+
};
|
|
17
|
+
/** Thrown when a field runs past the end of the data */
|
|
18
|
+
class EndOfData extends Error {
|
|
19
|
+
}
|
|
20
|
+
class BitReader {
|
|
21
|
+
data;
|
|
22
|
+
position = 0;
|
|
23
|
+
constructor(data) {
|
|
24
|
+
this.data = data;
|
|
25
|
+
}
|
|
26
|
+
bits(count) {
|
|
27
|
+
let value = 0;
|
|
28
|
+
// Least significant bit first, from 32 bit values without overflowing
|
|
29
|
+
for (let i = 0; i < count; i++) {
|
|
30
|
+
const byte = this.data[this.position >> 3];
|
|
31
|
+
if (byte === undefined) {
|
|
32
|
+
throw new EndOfData();
|
|
33
|
+
}
|
|
34
|
+
value += ((byte >> (this.position & 7)) & 1) * 2 ** i;
|
|
35
|
+
this.position++;
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
bool() {
|
|
40
|
+
return this.bits(1) === 1;
|
|
41
|
+
}
|
|
42
|
+
u32(...distributions) {
|
|
43
|
+
const distribution = distributions[this.bits(2)];
|
|
44
|
+
return typeof distribution === "number"
|
|
45
|
+
? distribution
|
|
46
|
+
: this.bits(distribution[0]) + distribution[1];
|
|
47
|
+
}
|
|
48
|
+
enum() {
|
|
49
|
+
return this.u32(0, 1, [4, 2], [6, 18]);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Whole-number ratios of width to height that SizeHeader can store */
|
|
53
|
+
const ASPECT_RATIOS = [
|
|
54
|
+
[1, 1],
|
|
55
|
+
[12, 10],
|
|
56
|
+
[4, 3],
|
|
57
|
+
[3, 2],
|
|
58
|
+
[16, 9],
|
|
59
|
+
[5, 4],
|
|
60
|
+
[2, 1],
|
|
61
|
+
];
|
|
62
|
+
function readSize(reader) {
|
|
63
|
+
const small = reader.bool();
|
|
64
|
+
const readDimension = () => small
|
|
65
|
+
? (reader.bits(5) + 1) * 8
|
|
66
|
+
: reader.u32([9, 1], [13, 1], [18, 1], [30, 1]);
|
|
67
|
+
const height = readDimension();
|
|
68
|
+
const ratio = reader.bits(3);
|
|
69
|
+
if (ratio === 0) {
|
|
70
|
+
return { width: readDimension(), height };
|
|
71
|
+
}
|
|
72
|
+
const [numerator, denominator] = ASPECT_RATIOS[ratio - 1];
|
|
73
|
+
return { width: Math.floor((height * numerator) / denominator), height };
|
|
74
|
+
}
|
|
75
|
+
function skipPreviewSize(reader) {
|
|
76
|
+
const div8 = reader.bool();
|
|
77
|
+
const skipDimension = () => div8
|
|
78
|
+
? reader.u32(16, 32, [5, 1], [9, 33])
|
|
79
|
+
: reader.u32([6, 1], [8, 65], [10, 321], [12, 1345]);
|
|
80
|
+
skipDimension();
|
|
81
|
+
if (reader.bits(3) === 0) {
|
|
82
|
+
skipDimension();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function skipBitDepth(reader) {
|
|
86
|
+
if (reader.bool()) {
|
|
87
|
+
reader.u32(32, 16, 24, [6, 1]);
|
|
88
|
+
reader.bits(4);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
reader.u32(8, 10, 12, [6, 1]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function skipExtraChannelInfo(reader) {
|
|
95
|
+
if (reader.bool()) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const type = reader.enum();
|
|
99
|
+
skipBitDepth(reader);
|
|
100
|
+
// Dimension shift
|
|
101
|
+
reader.u32(0, 3, 4, [3, 1]);
|
|
102
|
+
// Name, in bytes
|
|
103
|
+
reader.bits(reader.u32(0, [4, 0], [5, 16], [10, 48]) * 8);
|
|
104
|
+
if (type === 0) {
|
|
105
|
+
// Alpha: whether it's premultiplied
|
|
106
|
+
reader.bits(1);
|
|
107
|
+
}
|
|
108
|
+
else if (type === 2) {
|
|
109
|
+
// Spot colour: four 16 bit floats
|
|
110
|
+
reader.bits(64);
|
|
111
|
+
}
|
|
112
|
+
else if (type === 5) {
|
|
113
|
+
// CFA channel
|
|
114
|
+
reader.u32(1, [2, 0], [4, 3], [8, 19]);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function skipCustomXy(reader) {
|
|
118
|
+
for (let i = 0; i < 2; i++) {
|
|
119
|
+
reader.u32([19, 0], [19, 524288], [20, 1048576], [21, 2097152]);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** The transfer function of the image's colour encoding */
|
|
123
|
+
function readTransferFunction(reader) {
|
|
124
|
+
if (reader.bool()) {
|
|
125
|
+
// Fields are all default: sRGB
|
|
126
|
+
return 13;
|
|
127
|
+
}
|
|
128
|
+
const wantIcc = reader.bool();
|
|
129
|
+
const colorSpace = reader.enum();
|
|
130
|
+
const gray = colorSpace === 1;
|
|
131
|
+
const xyb = colorSpace === 2;
|
|
132
|
+
if (wantIcc || xyb) {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
if (reader.enum() === 2) {
|
|
136
|
+
// Custom white point
|
|
137
|
+
skipCustomXy(reader);
|
|
138
|
+
}
|
|
139
|
+
if (!gray && reader.enum() === 2) {
|
|
140
|
+
// Custom primaries
|
|
141
|
+
for (let i = 0; i < 3; i++) {
|
|
142
|
+
skipCustomXy(reader);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// Images with a gamma exponent don't have a transfer function
|
|
146
|
+
return reader.bool() ? undefined : reader.enum();
|
|
147
|
+
}
|
|
148
|
+
function readTransferFunctionFromMetadata(reader) {
|
|
149
|
+
if (reader.bool()) {
|
|
150
|
+
// Fields are all default: sRGB
|
|
151
|
+
return 13;
|
|
152
|
+
}
|
|
153
|
+
if (reader.bool()) {
|
|
154
|
+
// Orientation
|
|
155
|
+
reader.bits(3);
|
|
156
|
+
if (reader.bool()) {
|
|
157
|
+
// Intrinsic size
|
|
158
|
+
readSize(reader);
|
|
159
|
+
}
|
|
160
|
+
if (reader.bool()) {
|
|
161
|
+
skipPreviewSize(reader);
|
|
162
|
+
}
|
|
163
|
+
if (reader.bool()) {
|
|
164
|
+
// Animation: ticks per second, number of loops and timecodes
|
|
165
|
+
reader.u32(100, 1000, [10, 1], [30, 1]);
|
|
166
|
+
reader.u32(1, 1001, [8, 1], [10, 1]);
|
|
167
|
+
reader.u32(0, [3, 0], [16, 0], [32, 0]);
|
|
168
|
+
reader.bits(1);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
skipBitDepth(reader);
|
|
172
|
+
// Whether 16 bit buffers are enough for modular images
|
|
173
|
+
reader.bits(1);
|
|
174
|
+
const extraChannels = reader.u32(0, 1, [4, 2], [12, 1]);
|
|
175
|
+
for (let i = 0; i < extraChannels; i++) {
|
|
176
|
+
skipExtraChannelInfo(reader);
|
|
177
|
+
}
|
|
178
|
+
// Whether it's XYB encoded, which doesn't change the colour encoding
|
|
179
|
+
reader.bits(1);
|
|
180
|
+
return readTransferFunction(reader);
|
|
181
|
+
}
|
|
182
|
+
/** The codestream, from a bare codestream or the boxes of a container */
|
|
183
|
+
function getCodestream(data) {
|
|
184
|
+
if (data[0] === 0xff && data[1] === 0x0a) {
|
|
185
|
+
return data;
|
|
186
|
+
}
|
|
187
|
+
if (CONTAINER_SIGNATURE.some((byte, i) => data[i] !== byte)) {
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
191
|
+
const parts = [];
|
|
192
|
+
let length = 0;
|
|
193
|
+
let offset = 0;
|
|
194
|
+
while (offset + 8 <= data.length && length < MAX_HEADER_BYTES) {
|
|
195
|
+
let size = view.getUint32(offset);
|
|
196
|
+
let headerSize = 8;
|
|
197
|
+
const type = String.fromCharCode(...data.subarray(offset + 4, offset + 8));
|
|
198
|
+
if (size === 1) {
|
|
199
|
+
if (offset + 16 > data.length) {
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
size = Number(view.getBigUint64(offset + 8));
|
|
203
|
+
headerSize = 16;
|
|
204
|
+
}
|
|
205
|
+
else if (size === 0) {
|
|
206
|
+
// The last box, to the end of the file
|
|
207
|
+
size = data.length - offset;
|
|
208
|
+
}
|
|
209
|
+
if (size < headerSize) {
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
const contents = data.subarray(offset + headerSize, offset + size);
|
|
213
|
+
if (type === "jxlc") {
|
|
214
|
+
return contents;
|
|
215
|
+
}
|
|
216
|
+
if (type === "jxlp") {
|
|
217
|
+
// Partial codestreams start with their index
|
|
218
|
+
parts.push(contents.subarray(4));
|
|
219
|
+
length += contents.length - 4;
|
|
220
|
+
}
|
|
221
|
+
offset += size;
|
|
222
|
+
}
|
|
223
|
+
const codestream = new Uint8Array(length);
|
|
224
|
+
let position = 0;
|
|
225
|
+
for (const part of parts) {
|
|
226
|
+
codestream.set(part, position);
|
|
227
|
+
position += part.length;
|
|
228
|
+
}
|
|
229
|
+
return codestream;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Reads the size, and the transfer function if it's in the header, of a
|
|
233
|
+
* JPEG XL codestream or container. Returns undefined if the data isn't
|
|
234
|
+
* JPEG XL or is too short to have a size.
|
|
235
|
+
*/
|
|
236
|
+
export function readJxlHeader(data) {
|
|
237
|
+
const codestream = getCodestream(data);
|
|
238
|
+
if (!codestream || codestream[0] !== 0xff || codestream[1] !== 0x0a) {
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
const reader = new BitReader(codestream.subarray(2));
|
|
242
|
+
let size;
|
|
243
|
+
try {
|
|
244
|
+
size = readSize(reader);
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (error instanceof EndOfData) {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
return {
|
|
254
|
+
...size,
|
|
255
|
+
transferFunction: readTransferFunctionFromMetadata(reader),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (error instanceof EndOfData) {
|
|
260
|
+
return size;
|
|
261
|
+
}
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
//# sourceMappingURL=header.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"header.js","sourceRoot":"","sources":["../../src/header.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,0EAA0E;AAC1E,MA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,UAAU,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QACpE,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IACrD,IAAI,IAAI,CAAC;IAET,IAAI,CAAC;QACH,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,SAAS,EAAE,CAAC;YAC/B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,OAAO;YACL,GAAG,IAAI;YACP,gBAAgB,EAAE,gCAAgC,CAAC,MAAM,CAAC;SAC3D,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,SAAS,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/**\n * Reads the start of a JPEG XL codestream (ISO/IEC 18181-1): the image size\n * and, when the file describes its colours with an enum rather than an ICC\n * profile, the transfer function. Field encodings follow libjxl's\n * `SizeHeader`, `ImageMetadata` and `ColorEncoding`.\n */\n\n/** The ISOBMFF signature box of the container format (ISO/IEC 18181-2) */\nconst CONTAINER_SIGNATURE = [\n 0x00, 0x00, 0x00, 0x0c, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a,\n];\n/** The header fields are a few hundred bytes at most */\nconst MAX_HEADER_BYTES = 65536;\n\nexport const TransferFunction = {\n PQ: 16,\n HLG: 18,\n} as const;\n\nexport interface JxlHeader {\n width: number;\n height: number;\n /**\n * The CICP transfer characteristic, e.g. 13 for sRGB. Undefined when the\n * colours are described by an ICC profile or with a custom gamma, or if\n * the header couldn't be read that far.\n */\n transferFunction?: number;\n}\n\n/** Thrown when a field runs past the end of the data */\nclass EndOfData extends Error {}\n\n/** A distribution of U32 fields: a value, or [extra bits, offset] */\ntype U32Distribution = number | [bits: number, offset: number];\n\nclass BitReader {\n private readonly data: Uint8Array;\n private position = 0;\n\n constructor(data: Uint8Array) {\n this.data = data;\n }\n\n bits(count: number) {\n let value = 0;\n\n // Least significant bit first, from 32 bit values without overflowing\n for (let i = 0; i < count; i++) {\n const byte = this.data[this.position >> 3];\n\n if (byte === undefined) {\n throw new EndOfData();\n }\n\n value += ((byte >> (this.position & 7)) & 1) * 2 ** i;\n this.position++;\n }\n\n return value;\n }\n\n bool() {\n return this.bits(1) === 1;\n }\n\n u32(...distributions: U32Distribution[]) {\n const distribution = distributions[this.bits(2)]!;\n\n return typeof distribution === \"number\"\n ? distribution\n : this.bits(distribution[0]) + distribution[1];\n }\n\n enum() {\n return this.u32(0, 1, [4, 2], [6, 18]);\n }\n}\n\n/** Whole-number ratios of width to height that SizeHeader can store */\nconst ASPECT_RATIOS = [\n [1, 1],\n [12, 10],\n [4, 3],\n [3, 2],\n [16, 9],\n [5, 4],\n [2, 1],\n] as const;\n\nfunction readSize(reader: BitReader) {\n const small = reader.bool();\n const readDimension = () =>\n small\n ? (reader.bits(5) + 1) * 8\n : reader.u32([9, 1], [13, 1], [18, 1], [30, 1]);\n const height = readDimension();\n const ratio = reader.bits(3);\n\n if (ratio === 0) {\n return { width: readDimension(), height };\n }\n\n const [numerator, denominator] = ASPECT_RATIOS[ratio - 1]!;\n return { width: Math.floor((height * numerator) / denominator), height };\n}\n\nfunction skipPreviewSize(reader: BitReader) {\n const div8 = reader.bool();\n const skipDimension = () =>\n div8\n ? reader.u32(16, 32, [5, 1], [9, 33])\n : reader.u32([6, 1], [8, 65], [10, 321], [12, 1345]);\n\n skipDimension();\n\n if (reader.bits(3) === 0) {\n skipDimension();\n }\n}\n\nfunction skipBitDepth(reader: BitReader) {\n if (reader.bool()) {\n reader.u32(32, 16, 24, [6, 1]);\n reader.bits(4);\n } else {\n reader.u32(8, 10, 12, [6, 1]);\n }\n}\n\nfunction skipExtraChannelInfo(reader: BitReader) {\n if (reader.bool()) {\n return;\n }\n\n const type = reader.enum();\n\n skipBitDepth(reader);\n // Dimension shift\n reader.u32(0, 3, 4, [3, 1]);\n // Name, in bytes\n reader.bits(reader.u32(0, [4, 0], [5, 16], [10, 48]) * 8);\n\n if (type === 0) {\n // Alpha: whether it's premultiplied\n reader.bits(1);\n } else if (type === 2) {\n // Spot colour: four 16 bit floats\n reader.bits(64);\n } else if (type === 5) {\n // CFA channel\n reader.u32(1, [2, 0], [4, 3], [8, 19]);\n }\n}\n\nfunction skipCustomXy(reader: BitReader) {\n for (let i = 0; i < 2; i++) {\n reader.u32([19, 0], [19, 524288], [20, 1048576], [21, 2097152]);\n }\n}\n\n/** The transfer function of the image's colour encoding */\nfunction readTransferFunction(reader: BitReader) {\n if (reader.bool()) {\n // Fields are all default: sRGB\n return 13;\n }\n\n const wantIcc = reader.bool();\n const colorSpace = reader.enum();\n const gray = colorSpace === 1;\n const xyb = colorSpace === 2;\n\n if (wantIcc || xyb) {\n return undefined;\n }\n\n if (reader.enum() === 2) {\n // Custom white point\n skipCustomXy(reader);\n }\n\n if (!gray && reader.enum() === 2) {\n // Custom primaries\n for (let i = 0; i < 3; i++) {\n skipCustomXy(reader);\n }\n }\n\n // Images with a gamma exponent don't have a transfer function\n return reader.bool() ? undefined : reader.enum();\n}\n\nfunction readTransferFunctionFromMetadata(reader: BitReader) {\n if (reader.bool()) {\n // Fields are all default: sRGB\n return 13;\n }\n\n if (reader.bool()) {\n // Orientation\n reader.bits(3);\n\n if (reader.bool()) {\n // Intrinsic size\n readSize(reader);\n }\n\n if (reader.bool()) {\n skipPreviewSize(reader);\n }\n\n if (reader.bool()) {\n // Animation: ticks per second, number of loops and timecodes\n reader.u32(100, 1000, [10, 1], [30, 1]);\n reader.u32(1, 1001, [8, 1], [10, 1]);\n reader.u32(0, [3, 0], [16, 0], [32, 0]);\n reader.bits(1);\n }\n }\n\n skipBitDepth(reader);\n // Whether 16 bit buffers are enough for modular images\n reader.bits(1);\n\n const extraChannels = reader.u32(0, 1, [4, 2], [12, 1]);\n\n for (let i = 0; i < extraChannels; i++) {\n skipExtraChannelInfo(reader);\n }\n\n // Whether it's XYB encoded, which doesn't change the colour encoding\n reader.bits(1);\n\n return readTransferFunction(reader);\n}\n\n/** The codestream, from a bare codestream or the boxes of a container */\nfunction getCodestream(data: Uint8Array) {\n if (data[0] === 0xff && data[1] === 0x0a) {\n return data;\n }\n\n if (CONTAINER_SIGNATURE.some((byte, i) => data[i] !== byte)) {\n return undefined;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const parts: Uint8Array[] = [];\n let length = 0;\n let offset = 0;\n\n while (offset + 8 <= data.length && length < MAX_HEADER_BYTES) {\n let size = view.getUint32(offset);\n let headerSize = 8;\n const type = String.fromCharCode(...data.subarray(offset + 4, offset + 8));\n\n if (size === 1) {\n if (offset + 16 > data.length) {\n break;\n }\n\n size = Number(view.getBigUint64(offset + 8));\n headerSize = 16;\n } else if (size === 0) {\n // The last box, to the end of the file\n size = data.length - offset;\n }\n\n if (size < headerSize) {\n break;\n }\n\n const contents = data.subarray(offset + headerSize, offset + size);\n\n if (type === \"jxlc\") {\n return contents;\n }\n\n if (type === \"jxlp\") {\n // Partial codestreams start with their index\n parts.push(contents.subarray(4));\n length += contents.length - 4;\n }\n\n offset += size;\n }\n\n const codestream = new Uint8Array(length);\n let position = 0;\n\n for (const part of parts) {\n codestream.set(part, position);\n position += part.length;\n }\n\n return codestream;\n}\n\n/**\n * Reads the size, and the transfer function if it's in the header, of a\n * JPEG XL codestream or container. Returns undefined if the data isn't\n * JPEG XL or is too short to have a size.\n */\nexport function readJxlHeader(data: Uint8Array): JxlHeader | undefined {\n const codestream = getCodestream(data);\n\n if (!codestream || codestream[0] !== 0xff || codestream[1] !== 0x0a) {\n return undefined;\n }\n\n const reader = new BitReader(codestream.subarray(2));\n let size;\n\n try {\n size = readSize(reader);\n } catch (error) {\n if (error instanceof EndOfData) {\n return undefined;\n }\n\n throw error;\n }\n\n try {\n return {\n ...size,\n transferFunction: readTransferFunctionFromMetadata(reader),\n };\n } catch (error) {\n if (error instanceof EndOfData) {\n return size;\n }\n\n throw error;\n }\n}\n"]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { Bitmap } from "@jimp/types";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
declare const JxlOptionsSchema: z.ZodObject<{
|
|
5
|
+
quality: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
6
|
+
lossless: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
7
|
+
effort: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
8
|
+
progressive: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
9
|
+
lossyModular: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
|
|
10
|
+
epf: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
11
|
+
decodingSpeedTier: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
12
|
+
photonNoiseIso: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
|
|
13
|
+
}, z.core.$strict>;
|
|
14
|
+
type JxlOptions = z.infer<typeof JxlOptionsSchema>;
|
|
15
|
+
export interface DecodeJxlOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Largest image, in megapixels, that will be decoded. Larger images are
|
|
18
|
+
* rejected before any pixel memory is allocated.
|
|
19
|
+
* @default 100
|
|
20
|
+
*/
|
|
21
|
+
maxResolutionInMP?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface JxlWasm {
|
|
24
|
+
/** The compiled `@jsquash/jxl/codec/dec/jxl_dec.wasm` */
|
|
25
|
+
decoder?: WebAssembly.Module;
|
|
26
|
+
/**
|
|
27
|
+
* The compiled `@jsquash/jxl/codec/enc/jxl_enc.wasm`, the single-threaded
|
|
28
|
+
* encoder that @jsquash/jxl uses in Node and Cloudflare Workers
|
|
29
|
+
*/
|
|
30
|
+
encoder?: WebAssembly.Module;
|
|
31
|
+
}
|
|
32
|
+
export interface JxlFormatOptions {
|
|
33
|
+
/**
|
|
34
|
+
* Precompiled wasm modules for runtimes where the codecs can't load their
|
|
35
|
+
* own wasm, like Cloudflare Workers.
|
|
36
|
+
* Each codec is initialized once, by the first instance that encodes or
|
|
37
|
+
* decodes, so pass the same modules to every instance.
|
|
38
|
+
*/
|
|
39
|
+
wasm?: JxlWasm;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* JPEG XL images (.jxl), as bare codestreams or in the ISOBMFF container.
|
|
43
|
+
* Images are decoded to 8-bit sRGB, and written as 8-bit sRGB with alpha.
|
|
44
|
+
*/
|
|
45
|
+
export default function jxl({ wasm }?: JxlFormatOptions): {
|
|
46
|
+
mime: "image/jxl";
|
|
47
|
+
hasAlpha: true;
|
|
48
|
+
encode: (bitmap: Bitmap, options?: Partial<JxlOptions>) => Promise<Buffer<ArrayBuffer>>;
|
|
49
|
+
decode: (data: Buffer<ArrayBufferLike>, options?: DecodeJxlOptions) => Promise<Bitmap>;
|
|
50
|
+
};
|
|
51
|
+
export {};
|
|
52
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,MAAM,EAAU,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,QAAA,MAAM,gBAAgB;;;;;;;;;kBAkDX,CAAC;AAEZ,KAAK,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEnD,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,OAAO;IACtB,yDAAyD;IACzD,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC;CAC9B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AA2JD;;;GAGG;AACH,MAAM,CAAC,OAAO,UAAU,GAAG,CAAC,EAAE,IAAI,EAAE,GAAE,gBAAqB;;;uCAI7B,OAAO,CAAC,UAAU,CAAC;sDAErB,gBAAgB;EAG3C"}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import decode, { init as initDecoder } from "@jsquash/jxl/decode.js";
|
|
3
|
+
import encode, { init as initEncoder } from "@jsquash/jxl/encode.js";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { readJxlHeader, TransferFunction } from "./header.js";
|
|
6
|
+
import { loadWasm } from "./load-wasm.js";
|
|
7
|
+
const JxlOptionsSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
/**
|
|
10
|
+
* Image quality, between 0 and 100. 90 (the `cjxl` default) is
|
|
11
|
+
* visually lossless for most images. 100 is lossless, like `lossless`.
|
|
12
|
+
* @default 90
|
|
13
|
+
*/
|
|
14
|
+
quality: z.number().optional().default(90),
|
|
15
|
+
/**
|
|
16
|
+
* Store every pixel exactly, including alpha. `quality` is ignored.
|
|
17
|
+
* @default false
|
|
18
|
+
*/
|
|
19
|
+
lossless: z.boolean().optional().default(false),
|
|
20
|
+
/**
|
|
21
|
+
* How hard the encoder tries to make the file smaller, between 1 (fastest)
|
|
22
|
+
* and 9 (slowest).
|
|
23
|
+
* @default 7
|
|
24
|
+
*/
|
|
25
|
+
effort: z.number().optional().default(7),
|
|
26
|
+
/**
|
|
27
|
+
* Order the data so a partially downloaded file can be shown at a lower
|
|
28
|
+
* quality first. Makes files a little larger.
|
|
29
|
+
* @default false
|
|
30
|
+
*/
|
|
31
|
+
progressive: z.boolean().optional().default(false),
|
|
32
|
+
/**
|
|
33
|
+
* Use the modular mode for lossy images too, rather than the DCT based
|
|
34
|
+
* VarDCT mode. It can do better on graphics, and worse on photos.
|
|
35
|
+
* @default false
|
|
36
|
+
*/
|
|
37
|
+
lossyModular: z.boolean().optional().default(false),
|
|
38
|
+
/**
|
|
39
|
+
* Strength of the edge-preserving filter applied when decoding lossy
|
|
40
|
+
* images, between 0 (off) and 3. -1 picks one from the quality.
|
|
41
|
+
* @default -1
|
|
42
|
+
*/
|
|
43
|
+
epf: z.number().optional().default(-1),
|
|
44
|
+
/**
|
|
45
|
+
* Make lossy images faster to decode, between 0 (slowest, smallest
|
|
46
|
+
* files) and 4 (fastest).
|
|
47
|
+
* @default 0
|
|
48
|
+
*/
|
|
49
|
+
decodingSpeedTier: z.number().optional().default(0),
|
|
50
|
+
/**
|
|
51
|
+
* Add synthetic film grain to lossy images, like a photo taken at this
|
|
52
|
+
* ISO. 0 adds none.
|
|
53
|
+
* @default 0
|
|
54
|
+
*/
|
|
55
|
+
photonNoiseIso: z.number().optional().default(0),
|
|
56
|
+
})
|
|
57
|
+
.strict();
|
|
58
|
+
let decoderReady;
|
|
59
|
+
let encoderReady;
|
|
60
|
+
function initDecoderOnce(module) {
|
|
61
|
+
decoderReady ??= Promise.resolve(module ?? loadWasm("@jsquash/jxl/codec/dec/jxl_dec.wasm")).then(initDecoder);
|
|
62
|
+
return decoderReady;
|
|
63
|
+
}
|
|
64
|
+
function initEncoderOnce(module) {
|
|
65
|
+
// @jsquash/jxl only uses the multi-threaded encoder outside of Node
|
|
66
|
+
encoderReady ??= Promise.resolve(module ?? loadWasm("@jsquash/jxl/codec/enc/jxl_enc.wasm")).then(initEncoder);
|
|
67
|
+
return encoderReady;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The codecs return null for data they can't handle. Anything else they
|
|
71
|
+
* throw is a wasm trap, almost always from running out of memory (wasm has
|
|
72
|
+
* at most 2 GB), which can leave the codec in a bad state.
|
|
73
|
+
*/
|
|
74
|
+
function isTrap(error) {
|
|
75
|
+
return !(error instanceof Error && /^(De|En)coding error/.test(error.message));
|
|
76
|
+
}
|
|
77
|
+
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
|
|
78
|
+
async function decodeJxl(data, { maxResolutionInMP = 100 }, wasm) {
|
|
79
|
+
const header = readJxlHeader(data);
|
|
80
|
+
if (header) {
|
|
81
|
+
const { width, height, transferFunction } = header;
|
|
82
|
+
if (width * height > maxResolutionInMP * 1_000_000) {
|
|
83
|
+
throw new Error(`JPEG XL dimensions ${width}x${height} exceed the maximum resolution of ${maxResolutionInMP} megapixels`);
|
|
84
|
+
}
|
|
85
|
+
if (transferFunction === TransferFunction.PQ ||
|
|
86
|
+
transferFunction === TransferFunction.HLG) {
|
|
87
|
+
throw new Error(`Unsupported JPEG XL image: HDR images (with the ${transferFunction === TransferFunction.PQ ? "PQ" : "HLG"} transfer function) can't be decoded, because the codec would convert them to 8-bit sRGB without tone mapping`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
await initDecoderOnce(wasm);
|
|
91
|
+
let result;
|
|
92
|
+
try {
|
|
93
|
+
result = await decode(new Uint8Array(data).buffer);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (!isTrap(error)) {
|
|
97
|
+
throw new Error("Failed to decode the JPEG XL image: it's invalid, or uses a feature the codec doesn't support", { cause: error });
|
|
98
|
+
}
|
|
99
|
+
// Start again with a fresh instance
|
|
100
|
+
decoderReady = undefined;
|
|
101
|
+
throw new Error(`Failed to decode the ${header ? `${header.width}x${header.height} ` : ""}JPEG XL image: the codec ran out of memory`, { cause: error });
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
data: Buffer.from(result.data.buffer, result.data.byteOffset, result.data.byteLength),
|
|
105
|
+
width: result.width,
|
|
106
|
+
height: result.height,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
async function encodeJxl({ width, height, data }, options, wasm) {
|
|
110
|
+
const { quality, lossless, effort, progressive, lossyModular, epf, decodingSpeedTier, photonNoiseIso, } = JxlOptionsSchema.parse(options);
|
|
111
|
+
await initEncoderOnce(wasm);
|
|
112
|
+
try {
|
|
113
|
+
const arrayBuffer = await encode({
|
|
114
|
+
width,
|
|
115
|
+
height,
|
|
116
|
+
data: new Uint8ClampedArray(data.buffer, data.byteOffset, data.length),
|
|
117
|
+
// ImageData needs one, but the codec only reads the pixels
|
|
118
|
+
colorSpace: "srgb",
|
|
119
|
+
}, {
|
|
120
|
+
// Quality 100 is what makes the codec lossless. Its own lossless
|
|
121
|
+
// option does the same, but warns about the other options.
|
|
122
|
+
quality: lossless ? 100 : clamp(quality, 0, 100),
|
|
123
|
+
lossless: false,
|
|
124
|
+
lossyModular: lossless ? false : lossyModular,
|
|
125
|
+
// Larger values make the codec fail
|
|
126
|
+
effort: clamp(Math.round(effort), 1, 9),
|
|
127
|
+
epf: clamp(Math.round(epf), -1, 3),
|
|
128
|
+
decodingSpeedTier: clamp(Math.round(decodingSpeedTier), 0, 4),
|
|
129
|
+
photonNoiseIso: Math.max(photonNoiseIso, 0),
|
|
130
|
+
progressive,
|
|
131
|
+
// Makes files much larger, and isn't lossless, in this build of libjxl
|
|
132
|
+
lossyPalette: false,
|
|
133
|
+
});
|
|
134
|
+
return Buffer.from(arrayBuffer);
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (isTrap(error)) {
|
|
138
|
+
encoderReady = undefined;
|
|
139
|
+
throw new Error(`Failed to encode the ${width}x${height} JPEG XL image: the codec ran out of memory`, { cause: error });
|
|
140
|
+
}
|
|
141
|
+
throw new Error("Failed to encode the JPEG XL image", { cause: error });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* JPEG XL images (.jxl), as bare codestreams or in the ISOBMFF container.
|
|
146
|
+
* Images are decoded to 8-bit sRGB, and written as 8-bit sRGB with alpha.
|
|
147
|
+
*/
|
|
148
|
+
export default function jxl({ wasm } = {}) {
|
|
149
|
+
return {
|
|
150
|
+
mime: "image/jxl",
|
|
151
|
+
hasAlpha: true,
|
|
152
|
+
encode: (bitmap, options = {}) => encodeJxl(bitmap, options, wasm?.encoder),
|
|
153
|
+
decode: (data, options = {}) => decodeJxl(data, options, wasm?.decoder),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
//# sourceMappingURL=index.js.map
|