imagescript 3.9.0 → 3.10.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/README.md +16 -14
- package/dist/animation-encoder.js +3 -3
- package/dist/animation.d.ts +2 -0
- package/dist/animation.js +5 -2
- package/dist/codecs/av1/encode.js +149 -44
- package/dist/codecs/avif-enc.js +35 -9
- package/dist/codecs/avif.js +152 -81
- package/dist/codecs/jxl/acs-enc.js +18 -6
- package/dist/codecs/jxl/aq-enc.js +38 -37
- package/dist/codecs/jxl/color.js +14 -3
- package/dist/codecs/jxl/filters.js +44 -34
- package/dist/codecs/jxl/frame.js +218 -37
- package/dist/codecs/jxl/modular.js +40 -29
- package/dist/codecs/jxl/patches-enc.js +15 -8
- package/dist/codecs/jxl/vardct-enc.js +184 -134
- package/dist/codecs/jxl/vardct.js +53 -19
- package/dist/codecs/jxl.js +32 -21
- package/dist/codecs/vp8-enc.js +2 -2
- package/dist/codecs/vp8l.js +94 -62
- package/dist/codecs/webp.js +32 -11
- package/dist/image.d.ts +32 -3
- package/dist/image.js +19 -9
- package/dist/render/svg.js +99 -25
- package/dist/util/threads.js +101 -0
- package/dist/util/worker.js +52 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, no
|
|
11
|
-
dependencies. It runs in Node.js 22.13+, Deno, Bun
|
|
12
|
-
definitions.
|
|
11
|
+
dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's Edge
|
|
12
|
+
Runtime, Deno Deploy), works with both `import` and `require()`, and ships with type definitions. Large images are
|
|
13
|
+
encoded and decoded on several threads wherever the runtime supports workers.
|
|
13
14
|
|
|
14
15
|
```sh
|
|
15
16
|
npm install imagescript # Node.js, Bun and bundlers
|
|
@@ -29,8 +30,8 @@ image.resize(256, Image.RESIZE_AUTO).roundCorners(16);
|
|
|
29
30
|
await writeFile('output.png', await image.encode());
|
|
30
31
|
```
|
|
31
32
|
|
|
32
|
-
Coordinates
|
|
33
|
-
[
|
|
33
|
+
Coordinates start at `(0, 0)`, the top left pixel. For a bigger example, see the
|
|
34
|
+
[script that generates this image](https://github.com/matmen/ImageScript/blob/master/tests/readme.js):
|
|
34
35
|
|
|
35
36
|
[](https://github.com/matmen/ImageScript/blob/master/tests/readme.js)
|
|
36
37
|
|
|
@@ -49,14 +50,15 @@ Coordinates are 0-based, `(0, 0)` is the top left pixel. A bigger example is the
|
|
|
49
50
|
| BMP, QOI, TGA, Netpbm | ✓ | ✓ |
|
|
50
51
|
| TIFF, ICO/CUR, Radiance HDR | ✓ | |
|
|
51
52
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
Embedded
|
|
53
|
+
[Animations](https://imagescript.matmen.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
|
|
54
|
+
and encoded as GIF, APNG or WebP, all at once or
|
|
55
|
+
[frame by frame](https://imagescript.matmen.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
|
|
56
|
+
P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them.
|
|
55
57
|
|
|
56
|
-
- [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts
|
|
57
|
-
|
|
58
|
-
- [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), text
|
|
59
|
-
|
|
58
|
+
- [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
|
|
59
|
+
all scripts, color emoji
|
|
60
|
+
- [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), including text (with fonts you pass
|
|
61
|
+
or fonts embedded in the SVG)
|
|
60
62
|
- [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
|
|
61
63
|
[cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
|
|
62
64
|
[rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
|
|
@@ -68,9 +70,9 @@ Embedded ICC color profiles (Display P3, Adobe RGB, ...) are converted to sRGB w
|
|
|
68
70
|
[brightness](https://imagescript.matmen.dev/classes/Image.html#brightness),
|
|
69
71
|
[hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...
|
|
70
72
|
|
|
71
|
-
|
|
72
|
-
[changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md)
|
|
73
|
-
|
|
73
|
+
The [documentation](https://imagescript.matmen.dev/) covers the full API. When upgrading from an older major version,
|
|
74
|
+
see the [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md). [bench/](bench/README.md)
|
|
75
|
+
compares ImageScript's speed and file sizes with Jimp, sharp and other libraries.
|
|
74
76
|
|
|
75
77
|
---
|
|
76
78
|
|
|
@@ -75,9 +75,9 @@ export class AnimationEncoder {
|
|
|
75
75
|
let alpha = false;
|
|
76
76
|
const compositor = optimize ? null : new Compositor(width, height);
|
|
77
77
|
let full = false;
|
|
78
|
-
const add = (f) => {
|
|
78
|
+
const add = async (f) => {
|
|
79
79
|
alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
|
|
80
|
-
chunks.push(webp.frameChunk(f, lossy));
|
|
80
|
+
chunks.push(await webp.frameChunk(f, lossy));
|
|
81
81
|
};
|
|
82
82
|
return new AnimationEncoder(width, height, {
|
|
83
83
|
optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
|
|
@@ -89,7 +89,7 @@ export class AnimationEncoder {
|
|
|
89
89
|
full ||= input.dispose === 2 || (input.dispose === 1 && !!(input.x & 1 || input.y & 1));
|
|
90
90
|
if (full)
|
|
91
91
|
return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
|
|
92
|
-
add(webpFrame(input));
|
|
92
|
+
await add(webpFrame(input));
|
|
93
93
|
},
|
|
94
94
|
file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
|
|
95
95
|
}, optimize);
|
package/dist/animation.d.ts
CHANGED
|
@@ -20,6 +20,8 @@ export interface AnimationDecodeOptions {
|
|
|
20
20
|
maxPixels?: number;
|
|
21
21
|
/** Whether to convert the colors of frames with an embedded ICC profile (APNGs, WebPs) to sRGB, like `applyColorProfile` of {@link Image.decode}. Default: `true` */
|
|
22
22
|
applyColorProfile?: boolean;
|
|
23
|
+
/** At most this many worker threads decode in parallel, like `threads` of {@link Image.decode}. Default: the processors available, at most 8 */
|
|
24
|
+
threads?: number;
|
|
23
25
|
}
|
|
24
26
|
/** The options all animation encoders have */
|
|
25
27
|
export interface AnimationEncodeOptions {
|
package/dist/animation.js
CHANGED
|
@@ -3,6 +3,7 @@ import * as gifCodec from "./codecs/gif.js";
|
|
|
3
3
|
import * as png from "./codecs/png.js";
|
|
4
4
|
import * as webp from "./codecs/webp.js";
|
|
5
5
|
import * as jxl from "./codecs/jxl.js";
|
|
6
|
+
import { availableThreads } from "./util/threads.js";
|
|
6
7
|
import { view } from "./util/mem.js";
|
|
7
8
|
import { Image } from "./image.js";
|
|
8
9
|
import { Frame } from "./frame.js";
|
|
@@ -187,7 +188,9 @@ export class Animation extends Array {
|
|
|
187
188
|
return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
|
|
188
189
|
}
|
|
189
190
|
static async __decode__(input, onlyFirstFrameOrOptions) {
|
|
190
|
-
const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
|
|
191
|
+
const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)) } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
|
|
192
|
+
if (!Number.isInteger(threads) || threads < 1)
|
|
193
|
+
throw new RangeError(`threads must be a positive integer, not ${threads}`);
|
|
191
194
|
const profile = (frames, icc) => {
|
|
192
195
|
const transform = applyColorProfile && icc ? profileTransform(icc) : null;
|
|
193
196
|
if (transform)
|
|
@@ -216,7 +219,7 @@ export class Animation extends Array {
|
|
|
216
219
|
if (type === 'jxl') {
|
|
217
220
|
const frames = [];
|
|
218
221
|
let loopCount = -1;
|
|
219
|
-
for (const decoded of jxl.frames(data, maxPixels)) {
|
|
222
|
+
for await (const decoded of jxl.frames(data, maxPixels, 'reinhard', threads)) {
|
|
220
223
|
const frame = new Frame(decoded.width, decoded.height, decoded.duration, 0, 0, Frame.DISPOSAL_BACKGROUND);
|
|
221
224
|
frame.bitmap = decoded.pixels;
|
|
222
225
|
frames.push(frame.__orient__(decoded.orientation));
|
|
@@ -79,7 +79,11 @@ class TileEncoder {
|
|
|
79
79
|
pairCounts = new Uint32Array(65536);
|
|
80
80
|
bits = 0;
|
|
81
81
|
coded = false;
|
|
82
|
-
|
|
82
|
+
static aboveBytes(f) {
|
|
83
|
+
const n = f.b4Stride + 32;
|
|
84
|
+
return 10 * n + (n >> 1) + 1 + 48 * n;
|
|
85
|
+
}
|
|
86
|
+
constructor(f, src, params, above) {
|
|
83
87
|
this.f = f;
|
|
84
88
|
this.src = src;
|
|
85
89
|
this.params = params;
|
|
@@ -87,17 +91,19 @@ class TileEncoder {
|
|
|
87
91
|
this.hdr = f.hdr;
|
|
88
92
|
this.ssx = f.ssx;
|
|
89
93
|
this.ssy = f.ssy;
|
|
90
|
-
const n = f.b4Stride + 32;
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
this.
|
|
94
|
-
this.
|
|
95
|
-
this.
|
|
96
|
-
this.
|
|
97
|
-
this.
|
|
98
|
-
this.
|
|
99
|
-
this.
|
|
100
|
-
this.
|
|
94
|
+
const n = f.b4Stride + 32, buffer = above ?? new ArrayBuffer(TileEncoder.aboveBytes(f));
|
|
95
|
+
let o = 0;
|
|
96
|
+
const bytes = (length) => new Uint8Array(buffer, (o += length) - length, length);
|
|
97
|
+
this.aMode = bytes(n);
|
|
98
|
+
this.aLcoef = bytes(n);
|
|
99
|
+
this.aCcoef = [bytes(n), bytes(n)];
|
|
100
|
+
this.aSkip = bytes(n);
|
|
101
|
+
this.aUvmode = bytes(n);
|
|
102
|
+
this.aPartition = bytes(n >> 1);
|
|
103
|
+
this.aPalSz = bytes(n);
|
|
104
|
+
this.aPalSzUv = bytes(n);
|
|
105
|
+
this.aTxIntra = new Int8Array(buffer, (o += n) - n, n);
|
|
106
|
+
this.aPal = new Uint16Array(buffer, o + 1 & ~1, n * 24);
|
|
101
107
|
this.cdefChoice = new Int8Array(f.cdefIdx.length);
|
|
102
108
|
this.lossless = this.hdr.allLossless;
|
|
103
109
|
const q = this.hdr.quant;
|
|
@@ -147,6 +153,29 @@ class TileEncoder {
|
|
|
147
153
|
}
|
|
148
154
|
return nodes;
|
|
149
155
|
}
|
|
156
|
+
startTile(tileRow, tileCol) {
|
|
157
|
+
this.tile(tileRow, tileCol);
|
|
158
|
+
this.resetAbove();
|
|
159
|
+
return this.rowEnd - this.rowStart + 15 >> 4;
|
|
160
|
+
}
|
|
161
|
+
searchRow(tileRow, tileCol, row, progress) {
|
|
162
|
+
this.tile(tileRow, tileCol);
|
|
163
|
+
const root = edgeTree(false), nodes = [], n = this.colEnd - this.colStart + 15 >> 4;
|
|
164
|
+
this.by = this.rowStart + row * 16;
|
|
165
|
+
this.resetLeft();
|
|
166
|
+
for (let k = 0; k < n; k++) {
|
|
167
|
+
if (row) {
|
|
168
|
+
const need = Math.min(k + 2, n);
|
|
169
|
+
for (let v; (v = Atomics.load(progress, row - 1)) < need;)
|
|
170
|
+
Atomics.wait(progress, row - 1, v);
|
|
171
|
+
}
|
|
172
|
+
this.bx = this.colStart + k * 16;
|
|
173
|
+
nodes.push(this.search(BL_64X64, root).node);
|
|
174
|
+
Atomics.store(progress, row, k + 1);
|
|
175
|
+
Atomics.notify(progress, row);
|
|
176
|
+
}
|
|
177
|
+
return nodes;
|
|
178
|
+
}
|
|
150
179
|
storeTile(tileRow, tileCol, nodes) {
|
|
151
180
|
this.tile(tileRow, tileCol);
|
|
152
181
|
let i = 0;
|
|
@@ -1446,7 +1475,7 @@ function level(width, height) {
|
|
|
1446
1475
|
return 16;
|
|
1447
1476
|
return 31;
|
|
1448
1477
|
}
|
|
1449
|
-
|
|
1478
|
+
function setup(image, params, shared) {
|
|
1450
1479
|
const { width, height, layout } = image;
|
|
1451
1480
|
const bitsFor = (v) => Math.max(1, 32 - Math.clz32(v - 1));
|
|
1452
1481
|
const seq = {
|
|
@@ -1494,22 +1523,89 @@ export function encodeAV1(image, params) {
|
|
|
1494
1523
|
const f = new Frame(seq, hdr);
|
|
1495
1524
|
const src = f.planes.map((plane, p) => {
|
|
1496
1525
|
const sx = p && layout === 1 ? 1 : 0, w = width + sx >> sx, h = height + sx >> sx, stride = f.strides[p];
|
|
1497
|
-
const pw = f.bw * 4 >> sx, ph = f.bh * 4 >> sx,
|
|
1526
|
+
const pw = f.bw * 4 >> sx, ph = f.bh * 4 >> sx, inp = image.planes[p];
|
|
1527
|
+
const out = shared ? new Uint16Array(new SharedArrayBuffer(plane.length * 2)) : new Uint16Array(plane.length);
|
|
1498
1528
|
for (let y = 0; y < ph; y++)
|
|
1499
1529
|
for (let x = 0; x < pw; x++)
|
|
1500
1530
|
out[y * stride + x] = inp[Math.min(y, h - 1) * w + Math.min(x, w - 1)];
|
|
1501
1531
|
return out;
|
|
1502
1532
|
});
|
|
1533
|
+
if (shared)
|
|
1534
|
+
f.planes = f.planes.map(plane => new Uint16Array(new SharedArrayBuffer(plane.length * 2)));
|
|
1535
|
+
return { seq, hdr, f, src, rows, cols };
|
|
1536
|
+
}
|
|
1537
|
+
export function encodeAV1(image, params) {
|
|
1538
|
+
const { seq, hdr, f, src, rows, cols } = setup(image, params, false);
|
|
1503
1539
|
const encoder = new TileEncoder(f, src, params);
|
|
1504
1540
|
const nodes = [];
|
|
1505
1541
|
for (let r = 0; r < rows; r++)
|
|
1506
1542
|
for (let c = 0; c < cols; c++)
|
|
1507
1543
|
nodes.push(encoder.searchTile(r, c));
|
|
1544
|
+
const g = finish(encoder, seq, hdr, f, params, nodes, rows, cols), dirs = new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1);
|
|
1545
|
+
for (let step = g.next();; step = g.next(runFilterTrials(f, src, step.value, dirs)))
|
|
1546
|
+
if (step.done)
|
|
1547
|
+
return step.value;
|
|
1548
|
+
}
|
|
1549
|
+
export function searchRows(task, post) {
|
|
1550
|
+
const f = new Frame(task.seq, task.hdr);
|
|
1551
|
+
f.planes = task.planes;
|
|
1552
|
+
const encoder = new TileEncoder(f, task.src, task.params, task.above.buffer);
|
|
1553
|
+
for (let row; (row = Atomics.add(task.counter, 0, 1)) < task.progress.length;)
|
|
1554
|
+
post({ row, nodes: encoder.searchRow(task.tileRow, task.tileCol, row, task.progress) });
|
|
1555
|
+
}
|
|
1556
|
+
const BLOCK_ARRAYS = ['lfLevels', 'txW', 'txH', 'uvTxW', 'uvTxH', 'skip', 'segMap', 'cdefIdx'];
|
|
1557
|
+
export function filterTrials(task) {
|
|
1558
|
+
const f = new Frame(task.seq, task.hdr);
|
|
1559
|
+
for (const name of BLOCK_ARRAYS)
|
|
1560
|
+
f[name] = task.blocks[name];
|
|
1561
|
+
return runFilterTrials(f, task.src, task, new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1));
|
|
1562
|
+
}
|
|
1563
|
+
async function threadTrials(threads, f, src, t) {
|
|
1564
|
+
const planes = t.planes.map(p => {
|
|
1565
|
+
const s = new Uint16Array(new SharedArrayBuffer(p.length * 2));
|
|
1566
|
+
s.set(p);
|
|
1567
|
+
return s;
|
|
1568
|
+
});
|
|
1569
|
+
const blocks = {};
|
|
1570
|
+
for (const name of BLOCK_ARRAYS)
|
|
1571
|
+
blocks[name] = f[name];
|
|
1572
|
+
const out = new Array(t.values.length), used = threads.slice(0, t.values.length);
|
|
1573
|
+
await Promise.all(used.map(async (thread, k) => {
|
|
1574
|
+
const values = t.values.filter((_, i) => i % used.length === k);
|
|
1575
|
+
const errors = await thread.run({ task: 'av1-filter', kind: t.kind, values, planes, seq: f.seq, hdr: f.hdr, src, blocks });
|
|
1576
|
+
errors.forEach((e, j) => out[k + j * used.length] = e);
|
|
1577
|
+
}));
|
|
1578
|
+
return out;
|
|
1579
|
+
}
|
|
1580
|
+
export async function encodeAV1Threaded(image, params, threads) {
|
|
1581
|
+
const { seq, hdr, f, src, rows, cols } = setup(image, params, true);
|
|
1582
|
+
const above = new Uint8Array(new SharedArrayBuffer(TileEncoder.aboveBytes(f)));
|
|
1583
|
+
const encoder = new TileEncoder(f, src, params, above.buffer);
|
|
1584
|
+
const nodes = [];
|
|
1585
|
+
for (let r = 0; r < rows; r++) {
|
|
1586
|
+
for (let c = 0; c < cols; c++) {
|
|
1587
|
+
const sbRows = encoder.startTile(r, c), rowNodes = new Array(sbRows);
|
|
1588
|
+
const counter = new Int32Array(new SharedArrayBuffer(4)), progress = new Int32Array(new SharedArrayBuffer(4 * sbRows));
|
|
1589
|
+
const task = { task: 'av1-search', seq, hdr, params, planes: f.planes, src, above, counter, progress, tileRow: r, tileCol: c };
|
|
1590
|
+
await Promise.all(threads.map(t => t.run(task, m => {
|
|
1591
|
+
const { row, nodes } = m;
|
|
1592
|
+
rowNodes[row] = nodes;
|
|
1593
|
+
})));
|
|
1594
|
+
nodes.push(rowNodes.flat());
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
const g = finish(encoder, seq, hdr, f, params, nodes, rows, cols);
|
|
1598
|
+
for (let step = g.next();; step = g.next(await threadTrials(threads, f, src, step.value)))
|
|
1599
|
+
if (step.done)
|
|
1600
|
+
return step.value;
|
|
1601
|
+
}
|
|
1602
|
+
function* finish(encoder, seq, hdr, f, params, nodes, rows, cols) {
|
|
1603
|
+
const { width, height } = f, qidx = hdr.quant.yac;
|
|
1508
1604
|
for (let r = 0; r < rows; r++)
|
|
1509
1605
|
for (let c = 0; c < cols; c++)
|
|
1510
1606
|
encoder.storeTile(r, c, nodes[r * cols + c]);
|
|
1511
1607
|
if (qidx)
|
|
1512
|
-
chooseFilters(f,
|
|
1608
|
+
yield* chooseFilters(f, qidx, params.effort, encoder.cdefChoice);
|
|
1513
1609
|
f.cdefIdx.fill(-1);
|
|
1514
1610
|
const tiles = [];
|
|
1515
1611
|
for (let r = 0; r < rows; r++)
|
|
@@ -1560,47 +1656,56 @@ function blockErrors(f, planes, src, ey, euv) {
|
|
|
1560
1656
|
});
|
|
1561
1657
|
}
|
|
1562
1658
|
const sum = (a) => a.reduce((s, v) => s + v, 0);
|
|
1563
|
-
function
|
|
1659
|
+
function setLevel(f, level) {
|
|
1660
|
+
f.hdr.loopFilter.levelY = [level, level];
|
|
1661
|
+
f.hdr.loopFilter.levelU = f.hdr.loopFilter.levelV = level;
|
|
1662
|
+
for (let i = 0; i < f.lfLevels.length; i += 4)
|
|
1663
|
+
f.lfLevels.set([level, level, level, level], i);
|
|
1664
|
+
}
|
|
1665
|
+
export function runFilterTrials(f, src, t, dirs) {
|
|
1666
|
+
const n = f.cdefIdx.length, planes = f.planes, coded = Int8Array.from(f.cdefIdx, i => i >= 0 ? 0 : -1);
|
|
1667
|
+
const out = t.values.map(value => {
|
|
1668
|
+
const e = [new Float64Array(n), new Float64Array(n)];
|
|
1669
|
+
f.planes = t.planes.map(p => p.slice());
|
|
1670
|
+
if (t.kind === 'deblock') {
|
|
1671
|
+
setLevel(f, value);
|
|
1672
|
+
deblock(f);
|
|
1673
|
+
}
|
|
1674
|
+
else {
|
|
1675
|
+
f.hdr.cdef.yStrengths = [value];
|
|
1676
|
+
f.hdr.cdef.uvStrengths = [value];
|
|
1677
|
+
f.cdefIdx.set(coded);
|
|
1678
|
+
if (value)
|
|
1679
|
+
cdef(f, t.planes, dirs);
|
|
1680
|
+
}
|
|
1681
|
+
blockErrors(f, f.planes, src, e[0], e[1]);
|
|
1682
|
+
return e;
|
|
1683
|
+
});
|
|
1684
|
+
f.planes = planes;
|
|
1685
|
+
return out;
|
|
1686
|
+
}
|
|
1687
|
+
function* chooseFilters(f, qidx, effort, choice) {
|
|
1564
1688
|
const hdr = f.hdr, q = dequant(0, qidx, 1), n = f.cdefIdx.length;
|
|
1565
1689
|
const recon = f.planes.map(p => p.slice());
|
|
1566
|
-
const ey = new Float64Array(n), euv = new Float64Array(n);
|
|
1567
|
-
const setLevel = (level) => {
|
|
1568
|
-
hdr.loopFilter.levelY = [level, level];
|
|
1569
|
-
hdr.loopFilter.levelU = hdr.loopFilter.levelV = level;
|
|
1570
|
-
for (let i = 0; i < f.lfLevels.length; i += 4)
|
|
1571
|
-
f.lfLevels.set([level, level, level, level], i);
|
|
1572
|
-
};
|
|
1573
1690
|
const guess = Math.max(0, Math.min(63, (q * 20723 + 1015158 + (1 << 17) >> 18) - 4));
|
|
1691
|
+
const levels = [[guess], [guess - 4, guess, guess + 4], [guess - 6, guess - 3, guess, guess + 3, guess + 6]][effort].filter(l => l >= 0 && l <= 63);
|
|
1692
|
+
const levelErrors = yield { kind: 'deblock', values: levels, planes: recon };
|
|
1574
1693
|
let bestLevel = guess, bestError = Infinity;
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
continue;
|
|
1578
|
-
setLevel(level);
|
|
1579
|
-
f.planes = recon.map(p => p.slice());
|
|
1580
|
-
deblock(f);
|
|
1581
|
-
blockErrors(f, f.planes, src, ey, euv);
|
|
1582
|
-
const e = sum(ey) + sum(euv);
|
|
1694
|
+
levels.forEach((level, k) => {
|
|
1695
|
+
const e = sum(levelErrors[k][0]) + sum(levelErrors[k][1]);
|
|
1583
1696
|
if (e < bestError) {
|
|
1584
1697
|
bestError = e;
|
|
1585
1698
|
bestLevel = level;
|
|
1586
1699
|
}
|
|
1587
|
-
}
|
|
1588
|
-
setLevel(bestLevel);
|
|
1700
|
+
});
|
|
1701
|
+
setLevel(f, bestLevel);
|
|
1589
1702
|
f.planes = recon.map(p => p.slice());
|
|
1590
1703
|
deblock(f);
|
|
1591
1704
|
const deblocked = f.planes;
|
|
1592
1705
|
const strengths = [[0, 5, 9, 17, 33], [0, 1, 4, 5, 9, 17, 33, 61], [0, 1, 4, 5, 8, 9, 13, 17, 25, 33, 41, 61]][effort];
|
|
1593
|
-
const
|
|
1594
|
-
const
|
|
1595
|
-
|
|
1596
|
-
hdr.cdef.yStrengths = [strength];
|
|
1597
|
-
hdr.cdef.uvStrengths = [strength];
|
|
1598
|
-
f.planes = deblocked.map(p => p.slice());
|
|
1599
|
-
f.cdefIdx.set(Int8Array.from(coded, c => c ? 0 : -1));
|
|
1600
|
-
if (strength)
|
|
1601
|
-
cdef(f, deblocked, dirs);
|
|
1602
|
-
blockErrors(f, f.planes, src, errY[k], errUv[k]);
|
|
1603
|
-
});
|
|
1706
|
+
const coded = Array.from(f.cdefIdx, i => i >= 0);
|
|
1707
|
+
const strengthErrors = yield { kind: 'cdef', values: strengths, planes: deblocked };
|
|
1708
|
+
const errY = strengthErrors.map(e => e[0]), errUv = strengthErrors.map(e => e[1]);
|
|
1604
1709
|
const lambda = 0.08 * (q / 8) ** 2, blocks = coded.filter(c => c).length;
|
|
1605
1710
|
const pairs = [];
|
|
1606
1711
|
for (let y = 0; y < strengths.length; y++)
|
package/dist/codecs/avif-enc.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { encodeAV1 } from "./av1/encode.js";
|
|
1
|
+
import { encodeAV1, encodeAV1Threaded } from "./av1/encode.js";
|
|
2
|
+
import { startThreads } from "../util/threads.js";
|
|
3
|
+
const MIN_THREADED_PIXELS = [640 * 640, 448 * 448, 320 * 320], PIXELS_PER_THREAD = [512 << 10, 256 << 10, 256 << 10];
|
|
2
4
|
const QINDEX = [
|
|
3
5
|
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112,
|
|
4
6
|
116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196, 200, 204, 208,
|
|
@@ -149,7 +151,7 @@ function seqMonochrome(d, o) {
|
|
|
149
151
|
read(1);
|
|
150
152
|
return !!read(1);
|
|
151
153
|
}
|
|
152
|
-
export function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif }) {
|
|
154
|
+
export async function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads }) {
|
|
153
155
|
if (width < 1 || height < 1)
|
|
154
156
|
throw new RangeError('AVIF: dimensions must be at least 1');
|
|
155
157
|
if (width > 65536 || height > 65536)
|
|
@@ -173,13 +175,37 @@ export function encode(rgba, width, height, { quality, alphaQuality, subsampling
|
|
|
173
175
|
const cicp = lossless ? [1, 13, 0] : CICP;
|
|
174
176
|
const planes = gray ? [Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i])]
|
|
175
177
|
: lossless ? [1, 2, 0].map(c => Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i + c])) : toYUV(rgba, width, height, subsampled);
|
|
176
|
-
const
|
|
177
|
-
let
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
178
|
+
const n = Math.min(maxThreads, height + 63 >> 6, Math.ceil((width + 63 >> 6) / 2), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[effort])));
|
|
179
|
+
let threads = n > 1 && width * height >= MIN_THREADED_PIXELS[effort] ? startThreads(n) : null;
|
|
180
|
+
const stop = () => {
|
|
181
|
+
if (threads)
|
|
182
|
+
for (const t of threads)
|
|
183
|
+
t.terminate();
|
|
184
|
+
threads = null;
|
|
185
|
+
};
|
|
186
|
+
const av1 = async (image, params) => {
|
|
187
|
+
if (threads) {
|
|
188
|
+
try {
|
|
189
|
+
return await encodeAV1Threaded(image, params, threads);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
stop();
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return encodeAV1(image, params);
|
|
196
|
+
};
|
|
197
|
+
let color, alpha = null;
|
|
198
|
+
try {
|
|
199
|
+
color = await av1({ planes, width, height, layout: gray ? 0 : subsampled ? 1 : 3, cicp }, { qidx: qindex(quality), effort });
|
|
200
|
+
if (!opaque) {
|
|
201
|
+
const a = new Uint8Array(width * height);
|
|
202
|
+
for (let i = 0; i < a.length; i++)
|
|
203
|
+
a[i] = original[4 * i + 3];
|
|
204
|
+
alpha = await av1({ planes: [a], width, height, layout: 0, cicp: [2, 2, 2] }, { qidx: qindex(alphaQuality), effort });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
stop();
|
|
183
209
|
}
|
|
184
210
|
const profile = subsampled || gray ? 'MA1B' : 'MA1A';
|
|
185
211
|
const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile));
|