@nodetool-ai/image-nodes 0.8.1
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 +94 -0
- package/dist/.nodetool-build-stamp +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/nodes/game.d.ts +68 -0
- package/dist/nodes/game.d.ts.map +1 -0
- package/dist/nodes/game.js +551 -0
- package/dist/nodes/game.js.map +1 -0
- package/dist/nodes/gpu-device.d.ts +59 -0
- package/dist/nodes/gpu-device.d.ts.map +1 -0
- package/dist/nodes/gpu-device.js +144 -0
- package/dist/nodes/gpu-device.js.map +1 -0
- package/dist/nodes/image-io.d.ts +122 -0
- package/dist/nodes/image-io.d.ts.map +1 -0
- package/dist/nodes/image-io.js +381 -0
- package/dist/nodes/image-io.js.map +1 -0
- package/dist/nodes/image.d.ts +649 -0
- package/dist/nodes/image.d.ts.map +1 -0
- package/dist/nodes/image.js +2827 -0
- package/dist/nodes/image.js.map +1 -0
- package/dist/nodes/lib-grid.d.ts +19 -0
- package/dist/nodes/lib-grid.d.ts.map +1 -0
- package/dist/nodes/lib-grid.js +134 -0
- package/dist/nodes/lib-grid.js.map +1 -0
- package/dist/nodes/lib-image-channel.d.ts +38 -0
- package/dist/nodes/lib-image-channel.d.ts.map +1 -0
- package/dist/nodes/lib-image-channel.js +55 -0
- package/dist/nodes/lib-image-channel.js.map +1 -0
- package/dist/nodes/lib-image-color-grading.d.ts +3 -0
- package/dist/nodes/lib-image-color-grading.d.ts.map +1 -0
- package/dist/nodes/lib-image-color-grading.js +1080 -0
- package/dist/nodes/lib-image-color-grading.js.map +1 -0
- package/dist/nodes/lib-image-color.d.ts +96 -0
- package/dist/nodes/lib-image-color.d.ts.map +1 -0
- package/dist/nodes/lib-image-color.js +150 -0
- package/dist/nodes/lib-image-color.js.map +1 -0
- package/dist/nodes/lib-image-draw.d.ts +4 -0
- package/dist/nodes/lib-image-draw.d.ts.map +1 -0
- package/dist/nodes/lib-image-draw.js +464 -0
- package/dist/nodes/lib-image-draw.js.map +1 -0
- package/dist/nodes/lib-image-effects.d.ts +72 -0
- package/dist/nodes/lib-image-effects.d.ts.map +1 -0
- package/dist/nodes/lib-image-effects.js +123 -0
- package/dist/nodes/lib-image-effects.js.map +1 -0
- package/dist/nodes/lib-image-enhance.d.ts +3 -0
- package/dist/nodes/lib-image-enhance.d.ts.map +1 -0
- package/dist/nodes/lib-image-enhance.js +442 -0
- package/dist/nodes/lib-image-enhance.js.map +1 -0
- package/dist/nodes/lib-image-filter-extras.d.ts +72 -0
- package/dist/nodes/lib-image-filter-extras.d.ts.map +1 -0
- package/dist/nodes/lib-image-filter-extras.js +110 -0
- package/dist/nodes/lib-image-filter-extras.js.map +1 -0
- package/dist/nodes/lib-image-filter.d.ts +3 -0
- package/dist/nodes/lib-image-filter.d.ts.map +1 -0
- package/dist/nodes/lib-image-filter.js +588 -0
- package/dist/nodes/lib-image-filter.js.map +1 -0
- package/dist/nodes/lib-image-generators.d.ts +71 -0
- package/dist/nodes/lib-image-generators.d.ts.map +1 -0
- package/dist/nodes/lib-image-generators.js +158 -0
- package/dist/nodes/lib-image-generators.js.map +1 -0
- package/dist/nodes/lib-image-keyer.d.ts +34 -0
- package/dist/nodes/lib-image-keyer.d.ts.map +1 -0
- package/dist/nodes/lib-image-keyer.js +61 -0
- package/dist/nodes/lib-image-keyer.js.map +1 -0
- package/dist/nodes/lib-image-mask.d.ts +47 -0
- package/dist/nodes/lib-image-mask.d.ts.map +1 -0
- package/dist/nodes/lib-image-mask.js +59 -0
- package/dist/nodes/lib-image-mask.js.map +1 -0
- package/dist/nodes/lib-image-utils.d.ts +16 -0
- package/dist/nodes/lib-image-utils.d.ts.map +1 -0
- package/dist/nodes/lib-image-utils.js +61 -0
- package/dist/nodes/lib-image-utils.js.map +1 -0
- package/dist/nodes/lib-image-warp.d.ts +112 -0
- package/dist/nodes/lib-image-warp.d.ts.map +1 -0
- package/dist/nodes/lib-image-warp.js +236 -0
- package/dist/nodes/lib-image-warp.js.map +1 -0
- package/dist/nodes/lib-shader-utils.d.ts +105 -0
- package/dist/nodes/lib-shader-utils.d.ts.map +1 -0
- package/dist/nodes/lib-shader-utils.js +452 -0
- package/dist/nodes/lib-shader-utils.js.map +1 -0
- package/dist/nodes/sketch.d.ts +62 -0
- package/dist/nodes/sketch.d.ts.map +1 -0
- package/dist/nodes/sketch.js +325 -0
- package/dist/nodes/sketch.js.map +1 -0
- package/package.json +83 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
/**
|
|
3
|
+
* Shared GPU device + texture lifecycle for the image shader nodes.
|
|
4
|
+
*
|
|
5
|
+
* Owns the single cached `GPUContext` (Dawn on Node, `navigator.gpu` in the
|
|
6
|
+
* browser/worker) so every shader op and every read-back uses the same device,
|
|
7
|
+
* and hosts the run-scoped texture registry behind the in-flight GPU-texture
|
|
8
|
+
* `ImageRef` (see {@link gpuTextureImageRef}). Sits below both `lib-shader-utils`
|
|
9
|
+
* (which runs shaders) and `image-io` (which decodes/encodes), so the
|
|
10
|
+
* texture-readback seam is reachable from either without a circular import.
|
|
11
|
+
*
|
|
12
|
+
* GPU-texture refs exist only in the browser, for one run, and are never
|
|
13
|
+
* serialized: `releaseRunTextures(jobId)` frees them when the runner ends a job,
|
|
14
|
+
* and any boundary (transport / CPU / server) resolves them to bytes first.
|
|
15
|
+
*/
|
|
16
|
+
import { createLabeledTexture } from "@nodetool-ai/gpu/pool";
|
|
17
|
+
import { createNodeGPUContext } from "@nodetool-ai/gpu/node";
|
|
18
|
+
import { createBrowserGPUContext } from "@nodetool-ai/gpu/webgpu";
|
|
19
|
+
import { IS_NODE } from "@nodetool-ai/config";
|
|
20
|
+
import { GPU_TEXTURE_MIME } from "@nodetool-ai/protocol";
|
|
21
|
+
export { createLabeledTexture };
|
|
22
|
+
/** GPU-texture refs are browser-only; Node/Dawn always reads back to RGBA. */
|
|
23
|
+
export const GPU_TEXTURES_ENABLED = !IS_NODE;
|
|
24
|
+
let cachedContext = null;
|
|
25
|
+
/** The single cached GPU context (Dawn on Node, `navigator.gpu` in browser). */
|
|
26
|
+
export async function getGpuContext() {
|
|
27
|
+
if (!cachedContext) {
|
|
28
|
+
cachedContext = (IS_NODE ? createNodeGPUContext() : createBrowserGPUContext()).catch((err) => {
|
|
29
|
+
cachedContext = null;
|
|
30
|
+
throw err;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return cachedContext;
|
|
34
|
+
}
|
|
35
|
+
/** Premultiply straight-alpha RGBA in place. Mutates and returns `pixels`. */
|
|
36
|
+
export function premultiplyInPlace(pixels) {
|
|
37
|
+
for (let i = 0; i < pixels.length; i += 4) {
|
|
38
|
+
const a = pixels[i + 3] / 255;
|
|
39
|
+
pixels[i] = Math.round(pixels[i] * a);
|
|
40
|
+
pixels[i + 1] = Math.round(pixels[i + 1] * a);
|
|
41
|
+
pixels[i + 2] = Math.round(pixels[i + 2] * a);
|
|
42
|
+
}
|
|
43
|
+
return pixels;
|
|
44
|
+
}
|
|
45
|
+
/** Un-premultiply RGBA in place. Mutates and returns `pixels`. */
|
|
46
|
+
export function unpremultiplyInPlace(pixels) {
|
|
47
|
+
for (let i = 0; i < pixels.length; i += 4) {
|
|
48
|
+
const a = pixels[i + 3];
|
|
49
|
+
if (a === 0)
|
|
50
|
+
continue;
|
|
51
|
+
const inv = 255 / a;
|
|
52
|
+
pixels[i] = Math.min(255, Math.round(pixels[i] * inv));
|
|
53
|
+
pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] * inv));
|
|
54
|
+
pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] * inv));
|
|
55
|
+
}
|
|
56
|
+
return pixels;
|
|
57
|
+
}
|
|
58
|
+
/** Read a premultiplied `rgba8unorm` texture back to straight-alpha RGBA bytes. */
|
|
59
|
+
export async function readbackTexture(device, texture, width, height) {
|
|
60
|
+
// `copyTextureToBuffer` requires `bytesPerRow` aligned to 256.
|
|
61
|
+
const rowStride = Math.ceil((width * 4) / 256) * 256;
|
|
62
|
+
const buffer = device.createBuffer({
|
|
63
|
+
size: rowStride * height,
|
|
64
|
+
usage: 0x09 /* COPY_DST | MAP_READ */
|
|
65
|
+
});
|
|
66
|
+
try {
|
|
67
|
+
const encoder = device.createCommandEncoder({ label: "shader-readback" });
|
|
68
|
+
encoder.copyTextureToBuffer({ texture }, { buffer, bytesPerRow: rowStride, rowsPerImage: height }, { width, height });
|
|
69
|
+
device.queue.submit([encoder.finish()]);
|
|
70
|
+
await buffer.mapAsync(GPUMapMode.READ);
|
|
71
|
+
const mapped = new Uint8Array(buffer.getMappedRange());
|
|
72
|
+
const out = new Uint8Array(width * height * 4);
|
|
73
|
+
for (let row = 0; row < height; row++) {
|
|
74
|
+
out.set(mapped.subarray(row * rowStride, row * rowStride + width * 4), row * width * 4);
|
|
75
|
+
}
|
|
76
|
+
buffer.unmap();
|
|
77
|
+
return unpremultiplyInPlace(out);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
// Destroy even if mapAsync rejects (device lost / validation error).
|
|
81
|
+
buffer.destroy();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Read a `LabeledTexture` back to straight-alpha RGBA bytes. */
|
|
85
|
+
export function readbackStraightAlpha(device, texture) {
|
|
86
|
+
return readbackTexture(device, texture.texture, texture.width, texture.height);
|
|
87
|
+
}
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
// Run-scoped GPU-texture lifecycle
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
const runTextures = new Map();
|
|
92
|
+
/**
|
|
93
|
+
* Track `texture` under the run `runId` (a job id) so it's destroyed when the
|
|
94
|
+
* runner ends the run via {@link releaseRunTextures}. Chained shader nodes hand
|
|
95
|
+
* textures to one another within a run; freeing them per-node would break the
|
|
96
|
+
* hand-off, so cleanup is deferred to the run boundary.
|
|
97
|
+
*/
|
|
98
|
+
export function trackRunTexture(runId, texture) {
|
|
99
|
+
let set = runTextures.get(runId);
|
|
100
|
+
if (!set) {
|
|
101
|
+
set = new Set();
|
|
102
|
+
runTextures.set(runId, set);
|
|
103
|
+
}
|
|
104
|
+
set.add(texture);
|
|
105
|
+
}
|
|
106
|
+
/** Destroy and forget every texture tracked for `runId`. Safe to call twice. */
|
|
107
|
+
export function releaseRunTextures(runId) {
|
|
108
|
+
const set = runTextures.get(runId);
|
|
109
|
+
if (!set)
|
|
110
|
+
return;
|
|
111
|
+
for (const texture of set) {
|
|
112
|
+
try {
|
|
113
|
+
texture.destroy();
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// Texture already destroyed / device lost — nothing to do.
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
runTextures.delete(runId);
|
|
120
|
+
}
|
|
121
|
+
/** Number of live tracked textures (debug/telemetry). */
|
|
122
|
+
export function trackedRunTextureCount() {
|
|
123
|
+
let total = 0;
|
|
124
|
+
for (const set of runTextures.values())
|
|
125
|
+
total += set.size;
|
|
126
|
+
return total;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Build the in-flight GPU-texture `ImageRef` (browser, single run). `texture`
|
|
130
|
+
* is the `LabeledTexture` the producing shader wrote — held opaque in the ref's
|
|
131
|
+
* `texture` field so a consuming node can sample it directly. It must already
|
|
132
|
+
* be tracked via {@link trackRunTexture}.
|
|
133
|
+
*/
|
|
134
|
+
export function gpuTextureImageRef(texture, width, height) {
|
|
135
|
+
return { type: "image", texture, mimeType: GPU_TEXTURE_MIME, width, height };
|
|
136
|
+
}
|
|
137
|
+
/** Read a GPU-texture `ImageRef`'s pixels back to straight-alpha RGBA. */
|
|
138
|
+
export async function readbackTextureRef(ref) {
|
|
139
|
+
const ctx = await getGpuContext();
|
|
140
|
+
const labeled = ref.texture;
|
|
141
|
+
const rgba = await readbackTexture(ctx.device, labeled.texture, ref.width, ref.height);
|
|
142
|
+
return { rgba, width: ref.width, height: ref.height };
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=gpu-device.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gpu-device.js","sourceRoot":"","sources":["../../src/nodes/gpu-device.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,oBAAoB,EAGrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAiB,MAAM,uBAAuB,CAAC;AAExE,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAGhC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,OAAO,CAAC;AAE7C,IAAI,aAAa,GAA+B,IAAI,CAAC;AAErD,gFAAgF;AAChF,MAAM,CAAC,KAAK,UAAU,aAAa;IACjC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,aAAa,GAAG,CACd,OAAO,CAAC,CAAC,CAAC,oBAAoB,EAAE,CAAC,CAAC,CAAC,uBAAuB,EAAE,CAC7D,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YACd,aAAa,GAAG,IAAI,CAAC;YACrB,MAAM,GAAG,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,kBAAkB,CAAC,MAAkB;IACnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC1C,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,GAA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,MAAM,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC;AAED,yDAAyD;AACzD,MAAM,UAAU,sBAAsB;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,GAAG,IAAI,WAAW,CAAC,MAAM,EAAE;QAAE,KAAK,IAAI,GAAG,CAAC,IAAI,CAAC;IAC1D,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAuB,EACvB,KAAa,EACb,MAAc;IAEd,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC/E,CAAC;AAED,0EAA0E;AAC1E,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,GAIxC;IACC,MAAM,GAAG,GAAG,MAAM,aAAa,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAyB,CAAC;IAC9C,MAAM,IAAI,GAAG,MAAM,eAAe,CAChC,GAAG,CAAC,MAAM,EACV,OAAO,CAAC,OAAO,EACf,GAAG,CAAC,KAAK,EACT,GAAG,CAAC,MAAM,CACX,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC;AACxD,CAAC"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment-aware, sharp-free image I/O for the GPU shader nodes.
|
|
3
|
+
*
|
|
4
|
+
* The GPU image nodes run on both Node (Dawn device + `sharp` codec) and the
|
|
5
|
+
* browser (`navigator.gpu` device + Canvas codec). This module is the codec
|
|
6
|
+
* seam: it decodes encoded image bytes to straight-alpha RGBA and re-encodes
|
|
7
|
+
* RGBA to PNG, picking the Canvas path in the browser and lazily loading
|
|
8
|
+
* `sharp` on Node. Keeping it free of any *static* `sharp` import is what lets
|
|
9
|
+
* the GPU node files bundle for the browser (`sharp` is a native addon that the
|
|
10
|
+
* web bundle must never resolve).
|
|
11
|
+
*
|
|
12
|
+
* It deliberately does not live in the big `image.ts` (which stays Node-only
|
|
13
|
+
* and keeps its static `sharp` import for the legacy sharp nodes). The GPU
|
|
14
|
+
* nodes import their codec from here instead.
|
|
15
|
+
*/
|
|
16
|
+
import { type ImageRef } from "@nodetool-ai/protocol";
|
|
17
|
+
import type { ProcessingContext } from "@nodetool-ai/runtime";
|
|
18
|
+
/** Straight-alpha RGBA8 pixels plus dimensions — the GPU upload contract. */
|
|
19
|
+
interface RawRgba {
|
|
20
|
+
rgba: Uint8Array;
|
|
21
|
+
width: number;
|
|
22
|
+
height: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Build a raw-RGBA `ImageRef`: `data` carries straight-alpha RGBA8 pixels and
|
|
26
|
+
* `mimeType` marks it as the in-flight raw format. GPU ops emit this so an
|
|
27
|
+
* adjacent GPU op reuses the pixels via {@link decodeRgba} instead of decoding
|
|
28
|
+
* an encoded image; the bytes are lazily encoded to PNG at any boundary that
|
|
29
|
+
* needs a portable image.
|
|
30
|
+
*/
|
|
31
|
+
export declare function rawRgbaImageRef(rgba: Uint8Array, width: number, height: number): ImageRef;
|
|
32
|
+
import { base64ToBytes, bytesToBase64 } from "@nodetool-ai/nodes-utils";
|
|
33
|
+
export { base64ToBytes, bytesToBase64 };
|
|
34
|
+
type SharpModuleNs = typeof import("sharp");
|
|
35
|
+
type SharpFn = SharpModuleNs["default"];
|
|
36
|
+
/**
|
|
37
|
+
* Actionable error for a missing/broken `sharp` native addon. Used by the
|
|
38
|
+
* Node-only codec entry points when {@link loadSharp} resolves null on Node
|
|
39
|
+
* (the addon failed to load) and no Canvas fallback applies.
|
|
40
|
+
*/
|
|
41
|
+
export declare const SHARP_UNAVAILABLE_MESSAGE: string;
|
|
42
|
+
/**
|
|
43
|
+
* Lazily load `sharp` via a bundler-hidden import. Resolves `null` — never
|
|
44
|
+
* throws an opaque module-load error — when sharp is unavailable: off Node
|
|
45
|
+
* (browser/edge), or on Node when the native addon can't load (musl, unbundled
|
|
46
|
+
* serverless, ABI mismatch, partial install). A rejected attempt is never
|
|
47
|
+
* cached, so a fixed install is picked up on the next call; a `null` result is
|
|
48
|
+
* cached because the addon won't appear later in the same process. Callers must
|
|
49
|
+
* handle `null` with a working fallback or a clear, actionable error.
|
|
50
|
+
*/
|
|
51
|
+
export declare function loadSharp(): Promise<SharpFn | null>;
|
|
52
|
+
/**
|
|
53
|
+
* Resolve an image ref to encoded bytes, environment-aware and `Buffer`-free.
|
|
54
|
+
*
|
|
55
|
+
* Inline data and raw-RGBA are handled here; everything else delegates to the
|
|
56
|
+
* shared {@link loadMediaRefBytes}. In the browser that loader returns `null`
|
|
57
|
+
* for a relative `/api/...` URI (it only fetches absolute http(s)), so we fall
|
|
58
|
+
* back to a direct `fetch`, which the browser resolves against the page origin.
|
|
59
|
+
*/
|
|
60
|
+
export declare function loadImageBytes(ref: unknown, context?: ProcessingContext): Promise<Uint8Array>;
|
|
61
|
+
/** Copy bytes into a fresh `ArrayBuffer` (a valid `BlobPart`, never shared). */
|
|
62
|
+
export declare function toArrayBuffer(bytes: Uint8Array): ArrayBuffer;
|
|
63
|
+
/**
|
|
64
|
+
* Read the pixels of a preview `ImageBitmap` back to straight-alpha RGBA via
|
|
65
|
+
* an OffscreenCanvas (browser only — bitmap refs never exist on Node). The
|
|
66
|
+
* bitmap is left open: the UI may still be painting the same instance.
|
|
67
|
+
*/
|
|
68
|
+
export declare function bitmapToRgba(bitmap: ImageBitmap): Promise<RawRgba>;
|
|
69
|
+
/**
|
|
70
|
+
* Decode an image input to straight-alpha RGBA. Reuses the pixels directly when
|
|
71
|
+
* the input is already raw (an upstream GPU op left them, no codec work);
|
|
72
|
+
* otherwise loads and decodes the encoded bytes. Returns an empty buffer for
|
|
73
|
+
* missing/empty input.
|
|
74
|
+
*/
|
|
75
|
+
export declare function decodeRgba(image: unknown, context?: ProcessingContext): Promise<RawRgba>;
|
|
76
|
+
/**
|
|
77
|
+
* Read just the pixel dimensions of an image input, cheaply. In-flight refs
|
|
78
|
+
* (raw-RGBA, GPU texture, preview bitmap) all carry their dimensions, so this
|
|
79
|
+
* returns them without touching pixels — in particular it never triggers a GPU
|
|
80
|
+
* readback for a texture ref. A ref that already carries positive `width`/
|
|
81
|
+
* `height` fields is trusted directly. Otherwise it loads the encoded bytes and
|
|
82
|
+
* reads only the header (sharp metadata on Node, `createImageBitmap` in the
|
|
83
|
+
* browser), decoding the full image only as a last resort.
|
|
84
|
+
*/
|
|
85
|
+
export declare function imageDimensions(image: unknown, context?: ProcessingContext): Promise<{
|
|
86
|
+
width: number;
|
|
87
|
+
height: number;
|
|
88
|
+
}>;
|
|
89
|
+
/** Encode straight-alpha RGBA8 pixels to PNG bytes, environment-aware. */
|
|
90
|
+
export declare function encodeRgbaToPng(data: Uint8Array, width: number, height: number): Promise<Uint8Array>;
|
|
91
|
+
/**
|
|
92
|
+
* Encode a raw-RGBA `ImageRef` (the format {@link rawRgbaImageRef} produces)
|
|
93
|
+
* to PNG bytes. Returns its `data` unchanged when it's already encoded bytes,
|
|
94
|
+
* or an empty buffer when there's nothing to encode.
|
|
95
|
+
*/
|
|
96
|
+
export declare function encodePngFromRef(ref: unknown): Promise<Uint8Array>;
|
|
97
|
+
/**
|
|
98
|
+
* Resolve any in-flight GPU-texture `ImageRef`s in `value` to a CPU backing
|
|
99
|
+
* (raw-RGBA), recursively. Run at every boundary that serializes or leaves the
|
|
100
|
+
* GPU device — a `GPUTexture` can't cross `postMessage`, persist, or reach the
|
|
101
|
+
* server. The texture itself is left intact (the run-scoped registry frees it),
|
|
102
|
+
* so a sibling edge still chains on the GPU; only the transported copy is read
|
|
103
|
+
* back. Raw-RGBA (a `Uint8Array`) is serializable, so the result survives the
|
|
104
|
+
* generation cache / property re-injection that single-node runs rely on — an
|
|
105
|
+
* `ImageBitmap` would not. Non-texture values pass through unchanged.
|
|
106
|
+
*/
|
|
107
|
+
export declare function resolveImageRefForTransport(value: unknown): Promise<unknown>;
|
|
108
|
+
/**
|
|
109
|
+
* Wrap freshly-encoded PNG bytes into a base64 `ImageRef`.
|
|
110
|
+
*
|
|
111
|
+
* The result is new content, so the input's source identifiers — `uri`,
|
|
112
|
+
* `asset_id`, the previous `data`, and any raw-RGBA markers — are dropped.
|
|
113
|
+
* Carrying them over is a bug: a stale `uri`/`asset_id` points at the *input*
|
|
114
|
+
* asset and shadows the new `data` everywhere that prefers a uri (e.g. the
|
|
115
|
+
* output preview would render the input image, not the processed output).
|
|
116
|
+
* `base` is only mined for benign carry-over fields (e.g. type).
|
|
117
|
+
*/
|
|
118
|
+
export declare function toBase64Ref(png: Uint8Array, base?: unknown): {
|
|
119
|
+
type: string;
|
|
120
|
+
data: string;
|
|
121
|
+
};
|
|
122
|
+
//# sourceMappingURL=image-io.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-io.d.ts","sourceRoot":"","sources":["../../src/nodes/image-io.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAKL,KAAK,QAAQ,EACd,MAAM,uBAAuB,CAAC;AAM/B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAG9D,6EAA6E;AAC7E,UAAU,OAAO;IACf,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,UAAU,EAChB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GACb,QAAQ,CAEV;AAID,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAMxE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;AAWxC,KAAK,aAAa,GAAG,cAAc,OAAO,CAAC,CAAC;AAC5C,KAA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,EACf,IAAI,CAAC,EAAE,OAAO;;;EAWf"}
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
/**
|
|
3
|
+
* Environment-aware, sharp-free image I/O for the GPU shader nodes.
|
|
4
|
+
*
|
|
5
|
+
* The GPU image nodes run on both Node (Dawn device + `sharp` codec) and the
|
|
6
|
+
* browser (`navigator.gpu` device + Canvas codec). This module is the codec
|
|
7
|
+
* seam: it decodes encoded image bytes to straight-alpha RGBA and re-encodes
|
|
8
|
+
* RGBA to PNG, picking the Canvas path in the browser and lazily loading
|
|
9
|
+
* `sharp` on Node. Keeping it free of any *static* `sharp` import is what lets
|
|
10
|
+
* the GPU node files bundle for the browser (`sharp` is a native addon that the
|
|
11
|
+
* web bundle must never resolve).
|
|
12
|
+
*
|
|
13
|
+
* It deliberately does not live in the big `image.ts` (which stays Node-only
|
|
14
|
+
* and keeps its static `sharp` import for the legacy sharp nodes). The GPU
|
|
15
|
+
* nodes import their codec from here instead.
|
|
16
|
+
*/
|
|
17
|
+
import { isRawRgbaImage, isGpuTextureImage, isBitmapImage, RAW_RGBA_MIME } from "@nodetool-ai/protocol";
|
|
18
|
+
import { IS_NODE, importHidden } from "@nodetool-ai/config";
|
|
19
|
+
import { loadMediaRefBytes } from "@nodetool-ai/runtime/media-ref-bytes";
|
|
20
|
+
import { readbackTextureRef } from "./gpu-device.js";
|
|
21
|
+
/**
|
|
22
|
+
* Build a raw-RGBA `ImageRef`: `data` carries straight-alpha RGBA8 pixels and
|
|
23
|
+
* `mimeType` marks it as the in-flight raw format. GPU ops emit this so an
|
|
24
|
+
* adjacent GPU op reuses the pixels via {@link decodeRgba} instead of decoding
|
|
25
|
+
* an encoded image; the bytes are lazily encoded to PNG at any boundary that
|
|
26
|
+
* needs a portable image.
|
|
27
|
+
*/
|
|
28
|
+
export function rawRgbaImageRef(rgba, width, height) {
|
|
29
|
+
return { type: "image", data: rgba, mimeType: RAW_RGBA_MIME, width, height };
|
|
30
|
+
}
|
|
31
|
+
/* -------------------------- base64 (Buffer-free) -------------------------- */
|
|
32
|
+
import { base64ToBytes, bytesToBase64 } from "@nodetool-ai/nodes-utils";
|
|
33
|
+
import { isNonEmptyString, isNumber, isObjectLike } from "@nodetool-ai/node-sdk";
|
|
34
|
+
export { base64ToBytes, bytesToBase64 };
|
|
35
|
+
/** Strip a `data:...;base64,` prefix if present, returning the raw base64. */
|
|
36
|
+
function stripDataUrlPrefix(data) {
|
|
37
|
+
if (!data.startsWith("data:"))
|
|
38
|
+
return data;
|
|
39
|
+
const comma = data.indexOf(",");
|
|
40
|
+
return comma >= 0 ? data.slice(comma + 1) : data;
|
|
41
|
+
}
|
|
42
|
+
let _sharpPromise = null;
|
|
43
|
+
/**
|
|
44
|
+
* Actionable error for a missing/broken `sharp` native addon. Used by the
|
|
45
|
+
* Node-only codec entry points when {@link loadSharp} resolves null on Node
|
|
46
|
+
* (the addon failed to load) and no Canvas fallback applies.
|
|
47
|
+
*/
|
|
48
|
+
export const SHARP_UNAVAILABLE_MESSAGE = "The 'sharp' image codec is unavailable. It is a native addon that must be " +
|
|
49
|
+
"installed for this runtime (run `npm install sharp` in the server install, " +
|
|
50
|
+
"or reinstall it for your platform/arch — e.g. musl or a serverless target). " +
|
|
51
|
+
"In the browser/edge this node has no native codec.";
|
|
52
|
+
/**
|
|
53
|
+
* Lazily load `sharp` via a bundler-hidden import. Resolves `null` — never
|
|
54
|
+
* throws an opaque module-load error — when sharp is unavailable: off Node
|
|
55
|
+
* (browser/edge), or on Node when the native addon can't load (musl, unbundled
|
|
56
|
+
* serverless, ABI mismatch, partial install). A rejected attempt is never
|
|
57
|
+
* cached, so a fixed install is picked up on the next call; a `null` result is
|
|
58
|
+
* cached because the addon won't appear later in the same process. Callers must
|
|
59
|
+
* handle `null` with a working fallback or a clear, actionable error.
|
|
60
|
+
*/
|
|
61
|
+
export async function loadSharp() {
|
|
62
|
+
if (!_sharpPromise) {
|
|
63
|
+
// Let a thrown import (broken addon: musl, ABI mismatch, partial install)
|
|
64
|
+
// reject the attempt so the `.catch` below drops it from the cache and a
|
|
65
|
+
// later, fixed install is picked up. A legitimate off-Node `null` resolves
|
|
66
|
+
// and is cached — the addon won't appear later in the same process.
|
|
67
|
+
const attempt = (async () => {
|
|
68
|
+
const mod = await importHidden("sharp");
|
|
69
|
+
if (!mod)
|
|
70
|
+
return null;
|
|
71
|
+
if ("default" in mod && mod.default)
|
|
72
|
+
return mod.default;
|
|
73
|
+
// SAFETY: with no `default` export this is sharp's CJS build, where the
|
|
74
|
+
// module object is the factory itself.
|
|
75
|
+
return mod;
|
|
76
|
+
})();
|
|
77
|
+
_sharpPromise = attempt;
|
|
78
|
+
attempt.catch(() => {
|
|
79
|
+
if (_sharpPromise === attempt)
|
|
80
|
+
_sharpPromise = null;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
// Never surface an opaque module-load error to callers; report a broken addon
|
|
84
|
+
// as `null`. The cache reset above already ran on the rejected attempt.
|
|
85
|
+
return _sharpPromise.catch(() => null);
|
|
86
|
+
}
|
|
87
|
+
/* ------------------------------ byte loading ------------------------------ */
|
|
88
|
+
/**
|
|
89
|
+
* Resolve an image ref to encoded bytes, environment-aware and `Buffer`-free.
|
|
90
|
+
*
|
|
91
|
+
* Inline data and raw-RGBA are handled here; everything else delegates to the
|
|
92
|
+
* shared {@link loadMediaRefBytes}. In the browser that loader returns `null`
|
|
93
|
+
* for a relative `/api/...` URI (it only fetches absolute http(s)), so we fall
|
|
94
|
+
* back to a direct `fetch`, which the browser resolves against the page origin.
|
|
95
|
+
*/
|
|
96
|
+
export async function loadImageBytes(ref, context) {
|
|
97
|
+
if (!isObjectLike(ref))
|
|
98
|
+
return new Uint8Array();
|
|
99
|
+
const r = ref;
|
|
100
|
+
// Upstream GPU op left raw pixels — encode to PNG with the env-aware encoder
|
|
101
|
+
// (never the sharp-only path in `loadMediaRefBytes`, which throws in browser).
|
|
102
|
+
if (isRawRgbaImage(r)) {
|
|
103
|
+
return encodeRgbaToPng(r.data, r.width, r.height);
|
|
104
|
+
}
|
|
105
|
+
// A preview-bitmap ref (the worker's transport format) — read the pixels
|
|
106
|
+
// back off the bitmap, then encode.
|
|
107
|
+
if (isBitmapImage(r)) {
|
|
108
|
+
const { rgba, width, height } = await bitmapToRgba(r.bitmap);
|
|
109
|
+
return encodeRgbaToPng(rgba, width, height);
|
|
110
|
+
}
|
|
111
|
+
if (r.data instanceof Uint8Array && r.data.length > 0)
|
|
112
|
+
return r.data;
|
|
113
|
+
if (isNonEmptyString(r.data)) {
|
|
114
|
+
return base64ToBytes(stripDataUrlPrefix(r.data));
|
|
115
|
+
}
|
|
116
|
+
const viaLoader = await loadMediaRefBytes(r, context);
|
|
117
|
+
if (viaLoader && viaLoader.length > 0)
|
|
118
|
+
return viaLoader;
|
|
119
|
+
// Browser: fetch a relative/origin URI (or one derived from asset_id).
|
|
120
|
+
if (!IS_NODE) {
|
|
121
|
+
const url = r.uri && r.uri.length > 0
|
|
122
|
+
? r.uri
|
|
123
|
+
: r.asset_id
|
|
124
|
+
? `/api/storage/${r.asset_id}.png`
|
|
125
|
+
: null;
|
|
126
|
+
if (url) {
|
|
127
|
+
try {
|
|
128
|
+
const res = await fetch(url);
|
|
129
|
+
if (res.ok)
|
|
130
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// fall through to empty
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return new Uint8Array();
|
|
138
|
+
}
|
|
139
|
+
/* --------------------------------- decode --------------------------------- */
|
|
140
|
+
/** Copy bytes into a fresh `ArrayBuffer` (a valid `BlobPart`, never shared). */
|
|
141
|
+
export function toArrayBuffer(bytes) {
|
|
142
|
+
const buffer = new ArrayBuffer(bytes.byteLength);
|
|
143
|
+
new Uint8Array(buffer).set(bytes);
|
|
144
|
+
return buffer;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Read the pixels of a preview `ImageBitmap` back to straight-alpha RGBA via
|
|
148
|
+
* an OffscreenCanvas (browser only — bitmap refs never exist on Node). The
|
|
149
|
+
* bitmap is left open: the UI may still be painting the same instance.
|
|
150
|
+
*/
|
|
151
|
+
export async function bitmapToRgba(bitmap) {
|
|
152
|
+
const { width, height } = bitmap;
|
|
153
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
154
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
155
|
+
if (!ctx)
|
|
156
|
+
throw new Error("OffscreenCanvas 2D context unavailable");
|
|
157
|
+
ctx.drawImage(bitmap, 0, 0);
|
|
158
|
+
const { data } = ctx.getImageData(0, 0, width, height);
|
|
159
|
+
return { rgba: new Uint8Array(data.buffer.slice(0)), width, height };
|
|
160
|
+
}
|
|
161
|
+
/** Decode encoded image bytes to straight-alpha RGBA via Canvas (browser). */
|
|
162
|
+
async function decodeBytesBrowser(bytes) {
|
|
163
|
+
const bitmap = await createImageBitmap(new Blob([toArrayBuffer(bytes)]));
|
|
164
|
+
const { width, height } = bitmap;
|
|
165
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
166
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
167
|
+
if (!ctx)
|
|
168
|
+
throw new Error("OffscreenCanvas 2D context unavailable");
|
|
169
|
+
ctx.drawImage(bitmap, 0, 0);
|
|
170
|
+
bitmap.close();
|
|
171
|
+
const { data } = ctx.getImageData(0, 0, width, height);
|
|
172
|
+
return { rgba: new Uint8Array(data.buffer.slice(0)), width, height };
|
|
173
|
+
}
|
|
174
|
+
/** Decode encoded image bytes to straight-alpha RGBA via sharp (Node). */
|
|
175
|
+
async function decodeBytesNode(bytes) {
|
|
176
|
+
const sharp = await loadSharp();
|
|
177
|
+
if (!sharp) {
|
|
178
|
+
// sharp missing/broken on this Node target — fall back to Canvas when the
|
|
179
|
+
// runtime has one (e.g. a Node build with OffscreenCanvas), else fail loud.
|
|
180
|
+
if (typeof OffscreenCanvas !== "undefined" &&
|
|
181
|
+
typeof createImageBitmap !== "undefined") {
|
|
182
|
+
return decodeBytesBrowser(bytes);
|
|
183
|
+
}
|
|
184
|
+
throw new Error(SHARP_UNAVAILABLE_MESSAGE);
|
|
185
|
+
}
|
|
186
|
+
const { data, info } = await sharp(bytes, { failOn: "none" })
|
|
187
|
+
.ensureAlpha()
|
|
188
|
+
.raw()
|
|
189
|
+
.toBuffer({ resolveWithObject: true });
|
|
190
|
+
return {
|
|
191
|
+
rgba: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
192
|
+
width: info.width,
|
|
193
|
+
height: info.height
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Decode an image input to straight-alpha RGBA. Reuses the pixels directly when
|
|
198
|
+
* the input is already raw (an upstream GPU op left them, no codec work);
|
|
199
|
+
* otherwise loads and decodes the encoded bytes. Returns an empty buffer for
|
|
200
|
+
* missing/empty input.
|
|
201
|
+
*/
|
|
202
|
+
export async function decodeRgba(image, context) {
|
|
203
|
+
if (isRawRgbaImage(image)) {
|
|
204
|
+
return { rgba: image.data, width: image.width, height: image.height };
|
|
205
|
+
}
|
|
206
|
+
// An in-flight GPU-texture ref — read its pixels back off the device.
|
|
207
|
+
if (isGpuTextureImage(image)) {
|
|
208
|
+
return readbackTextureRef(image);
|
|
209
|
+
}
|
|
210
|
+
// A preview-bitmap ref (e.g. a cached result re-injected into a single-node
|
|
211
|
+
// run) — read the pixels off the bitmap, no codec work.
|
|
212
|
+
if (isBitmapImage(image)) {
|
|
213
|
+
return bitmapToRgba(image.bitmap);
|
|
214
|
+
}
|
|
215
|
+
const bytes = await loadImageBytes(image, context);
|
|
216
|
+
if (bytes.length === 0)
|
|
217
|
+
return { rgba: new Uint8Array(), width: 0, height: 0 };
|
|
218
|
+
return IS_NODE ? decodeBytesNode(bytes) : decodeBytesBrowser(bytes);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Read just the pixel dimensions of an image input, cheaply. In-flight refs
|
|
222
|
+
* (raw-RGBA, GPU texture, preview bitmap) all carry their dimensions, so this
|
|
223
|
+
* returns them without touching pixels — in particular it never triggers a GPU
|
|
224
|
+
* readback for a texture ref. A ref that already carries positive `width`/
|
|
225
|
+
* `height` fields is trusted directly. Otherwise it loads the encoded bytes and
|
|
226
|
+
* reads only the header (sharp metadata on Node, `createImageBitmap` in the
|
|
227
|
+
* browser), decoding the full image only as a last resort.
|
|
228
|
+
*/
|
|
229
|
+
export async function imageDimensions(image, context) {
|
|
230
|
+
if (isRawRgbaImage(image) ||
|
|
231
|
+
isGpuTextureImage(image) ||
|
|
232
|
+
isBitmapImage(image)) {
|
|
233
|
+
return { width: image.width, height: image.height };
|
|
234
|
+
}
|
|
235
|
+
if (isObjectLike(image)) {
|
|
236
|
+
const { width, height } = image;
|
|
237
|
+
if (isNumber(width) && isNumber(height) && width > 0 && height > 0) {
|
|
238
|
+
return { width, height };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const bytes = await loadImageBytes(image, context);
|
|
242
|
+
if (bytes.length === 0)
|
|
243
|
+
return { width: 0, height: 0 };
|
|
244
|
+
if (IS_NODE) {
|
|
245
|
+
const sharp = await loadSharp();
|
|
246
|
+
if (sharp) {
|
|
247
|
+
const meta = await sharp(bytes, { failOn: "none" }).metadata();
|
|
248
|
+
if (meta.width && meta.height) {
|
|
249
|
+
return { width: meta.width, height: meta.height };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
else if (typeof createImageBitmap !== "undefined") {
|
|
254
|
+
const bitmap = await createImageBitmap(new Blob([toArrayBuffer(bytes)]));
|
|
255
|
+
const { width, height } = bitmap;
|
|
256
|
+
bitmap.close();
|
|
257
|
+
return { width, height };
|
|
258
|
+
}
|
|
259
|
+
// Last resort — full decode (also covers Node without sharp).
|
|
260
|
+
const decoded = IS_NODE ? await decodeBytesNode(bytes) : await decodeBytesBrowser(bytes);
|
|
261
|
+
return { width: decoded.width, height: decoded.height };
|
|
262
|
+
}
|
|
263
|
+
/* --------------------------------- encode --------------------------------- */
|
|
264
|
+
/** Encode straight-alpha RGBA to PNG via Canvas (browser). Always 4-channel. */
|
|
265
|
+
async function encodeRgbaBrowser(data, width, height) {
|
|
266
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
267
|
+
const ctx = canvas.getContext("2d");
|
|
268
|
+
if (!ctx)
|
|
269
|
+
throw new Error("OffscreenCanvas 2D context unavailable");
|
|
270
|
+
ctx.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);
|
|
271
|
+
const blob = await canvas.convertToBlob({ type: "image/png" });
|
|
272
|
+
return new Uint8Array(await blob.arrayBuffer());
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Encode straight-alpha RGBA to PNG via sharp (Node). Drops a uniformly opaque
|
|
276
|
+
* alpha plane so the PNG is 3-channel — matching the channel count the legacy
|
|
277
|
+
* sharp pipelines produced (tests that index raw bytes with `* 3` depend on it).
|
|
278
|
+
*/
|
|
279
|
+
async function encodeRgbaNode(data, width, height) {
|
|
280
|
+
const sharp = await loadSharp();
|
|
281
|
+
if (!sharp) {
|
|
282
|
+
// sharp missing/broken on this Node target — fall back to Canvas when the
|
|
283
|
+
// runtime has one, else fail loud. (Canvas always emits 4-channel PNG; the
|
|
284
|
+
// 3-channel removeAlpha optimization is sharp-only and not load-bearing.)
|
|
285
|
+
if (typeof OffscreenCanvas !== "undefined") {
|
|
286
|
+
return encodeRgbaBrowser(data, width, height);
|
|
287
|
+
}
|
|
288
|
+
throw new Error(SHARP_UNAVAILABLE_MESSAGE);
|
|
289
|
+
}
|
|
290
|
+
let allOpaque = true;
|
|
291
|
+
for (let i = 3; i < data.length; i += 4) {
|
|
292
|
+
if (data[i] !== 255) {
|
|
293
|
+
allOpaque = false;
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
let pipeline = sharp(Buffer.from(data.buffer, data.byteOffset, data.byteLength), {
|
|
298
|
+
raw: { width, height, channels: 4 }
|
|
299
|
+
});
|
|
300
|
+
if (allOpaque)
|
|
301
|
+
pipeline = pipeline.removeAlpha();
|
|
302
|
+
const png = await pipeline.png().toBuffer();
|
|
303
|
+
return new Uint8Array(png.buffer, png.byteOffset, png.byteLength);
|
|
304
|
+
}
|
|
305
|
+
/** Encode straight-alpha RGBA8 pixels to PNG bytes, environment-aware. */
|
|
306
|
+
export async function encodeRgbaToPng(data, width, height) {
|
|
307
|
+
if (data.length === 0 || width === 0 || height === 0)
|
|
308
|
+
return new Uint8Array();
|
|
309
|
+
return IS_NODE
|
|
310
|
+
? encodeRgbaNode(data, width, height)
|
|
311
|
+
: encodeRgbaBrowser(data, width, height);
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Encode a raw-RGBA `ImageRef` (the format {@link rawRgbaImageRef} produces)
|
|
315
|
+
* to PNG bytes. Returns its `data` unchanged when it's already encoded bytes,
|
|
316
|
+
* or an empty buffer when there's nothing to encode.
|
|
317
|
+
*/
|
|
318
|
+
export async function encodePngFromRef(ref) {
|
|
319
|
+
// In-flight GPU texture — read its pixels back, then encode.
|
|
320
|
+
if (isGpuTextureImage(ref)) {
|
|
321
|
+
const { rgba, width, height } = await readbackTextureRef(ref);
|
|
322
|
+
return encodeRgbaToPng(rgba, width, height);
|
|
323
|
+
}
|
|
324
|
+
// Preview-bitmap ref — read the pixels off the bitmap, then encode.
|
|
325
|
+
if (isBitmapImage(ref)) {
|
|
326
|
+
const { rgba, width, height } = await bitmapToRgba(ref.bitmap);
|
|
327
|
+
return encodeRgbaToPng(rgba, width, height);
|
|
328
|
+
}
|
|
329
|
+
const data = ref.data;
|
|
330
|
+
const width = ref.width ?? 0;
|
|
331
|
+
const height = ref.height ?? 0;
|
|
332
|
+
if (!(data instanceof Uint8Array) || width === 0 || height === 0) {
|
|
333
|
+
return data instanceof Uint8Array ? data : new Uint8Array();
|
|
334
|
+
}
|
|
335
|
+
return encodeRgbaToPng(data, width, height);
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Resolve any in-flight GPU-texture `ImageRef`s in `value` to a CPU backing
|
|
339
|
+
* (raw-RGBA), recursively. Run at every boundary that serializes or leaves the
|
|
340
|
+
* GPU device — a `GPUTexture` can't cross `postMessage`, persist, or reach the
|
|
341
|
+
* server. The texture itself is left intact (the run-scoped registry frees it),
|
|
342
|
+
* so a sibling edge still chains on the GPU; only the transported copy is read
|
|
343
|
+
* back. Raw-RGBA (a `Uint8Array`) is serializable, so the result survives the
|
|
344
|
+
* generation cache / property re-injection that single-node runs rely on — an
|
|
345
|
+
* `ImageBitmap` would not. Non-texture values pass through unchanged.
|
|
346
|
+
*/
|
|
347
|
+
export async function resolveImageRefForTransport(value) {
|
|
348
|
+
if (isGpuTextureImage(value)) {
|
|
349
|
+
const { rgba, width, height } = await readbackTextureRef(value);
|
|
350
|
+
return rawRgbaImageRef(rgba, width, height);
|
|
351
|
+
}
|
|
352
|
+
if (Array.isArray(value)) {
|
|
353
|
+
return Promise.all(value.map((v) => resolveImageRefForTransport(v)));
|
|
354
|
+
}
|
|
355
|
+
if (isObjectLike(value) && !ArrayBuffer.isView(value)) {
|
|
356
|
+
const entries = await Promise.all(Object.entries(value).map(async ([k, v]) => [k, await resolveImageRefForTransport(v)]));
|
|
357
|
+
return Object.fromEntries(entries);
|
|
358
|
+
}
|
|
359
|
+
return value;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Wrap freshly-encoded PNG bytes into a base64 `ImageRef`.
|
|
363
|
+
*
|
|
364
|
+
* The result is new content, so the input's source identifiers — `uri`,
|
|
365
|
+
* `asset_id`, the previous `data`, and any raw-RGBA markers — are dropped.
|
|
366
|
+
* Carrying them over is a bug: a stale `uri`/`asset_id` points at the *input*
|
|
367
|
+
* asset and shadows the new `data` everywhere that prefers a uri (e.g. the
|
|
368
|
+
* output preview would render the input image, not the processed output).
|
|
369
|
+
* `base` is only mined for benign carry-over fields (e.g. type).
|
|
370
|
+
*/
|
|
371
|
+
export function toBase64Ref(png, base) {
|
|
372
|
+
const seed = isObjectLike(base) ? { ...base } : {};
|
|
373
|
+
delete seed.mimeType;
|
|
374
|
+
delete seed.width;
|
|
375
|
+
delete seed.height;
|
|
376
|
+
delete seed.uri;
|
|
377
|
+
delete seed.asset_id;
|
|
378
|
+
delete seed.data;
|
|
379
|
+
return { type: "image", ...seed, data: bytesToBase64(png) };
|
|
380
|
+
}
|
|
381
|
+
//# sourceMappingURL=image-io.js.map
|