img-auto-parallax 0.1.2 → 0.2.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 +12 -2
- package/dist/define.mjs +1 -1
- package/dist/{element-C2AqZorC.d.mts → element-DDl79CEt.d.mts} +4 -56
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +3 -1
- package/dist/internal.d.mts +34 -0
- package/dist/internal.mjs +1 -0
- package/dist/models-BeWE4rVt.d.mts +56 -0
- package/dist/{node-DOo42478.mjs → models-BmGGoJKs.mjs} +123 -206
- package/dist/{src-BiTfnOJ8.mjs → src-C092I6Rx.mjs} +49 -234
- package/dist/types.d.mts +2 -1
- package/package.json +6 -34
- package/dist/cli.d.mts +0 -1
- package/dist/cli.mjs +0 -64
- package/dist/node-BCog5g3V.d.mts +0 -108
- package/dist/node.d.mts +0 -6
- package/dist/node.mjs +0 -1
- package/dist/vite.d.mts +0 -11
- package/dist/vite.mjs +0 -29
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# img-auto-parallax
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An `<img>` drop-in WebComponent that brings any photo to life with depth and parallax effects, right on the device.
|
|
4
4
|
|
|
5
5
|
[](https://img-auto-parallax.vercel.app)
|
|
6
6
|
|
|
@@ -33,6 +33,16 @@ pnpm dev # docs + playground, using the library source
|
|
|
33
33
|
pnpm run ci # lint, typecheck, knip, build, test
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
## Sponsors
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
|
|
40
|
+
<img src="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg" alt="Sponsors"/>
|
|
41
|
+
</a>
|
|
42
|
+
</p>
|
|
43
|
+
|
|
36
44
|
## License
|
|
37
45
|
|
|
38
|
-
[MIT](./LICENSE.md).
|
|
46
|
+
[MIT](./LICENSE.md).
|
|
47
|
+
|
|
48
|
+
The bundled model is Apache-2.0, see [`models/NOTICE.md`](https://github.com/antfu/img-auto-parallax/blob/main/packages/img-auto-parallax/models/NOTICE.md).
|
package/dist/define.mjs
CHANGED
|
@@ -1,57 +1,5 @@
|
|
|
1
|
+
import { n as DepthModelOption, r as DepthModelPreset } from "./models-BeWE4rVt.mjs";
|
|
1
2
|
import "vgpu";
|
|
2
|
-
/** Describes an ONNX depth model the runtime can drive. */
|
|
3
|
-
interface DepthModelSpec {
|
|
4
|
-
/** Location of the `.onnx` file. */
|
|
5
|
-
url: string | URL;
|
|
6
|
-
/** Graph input name (NCHW float32). */
|
|
7
|
-
inputName: string;
|
|
8
|
-
/** Graph output name (float32, `[1, H, W]` or `[1, 1, H, W]`). */
|
|
9
|
-
outputName: string;
|
|
10
|
-
/**
|
|
11
|
-
* Input sizes are rounded to a multiple of this (the ViT patch size for
|
|
12
|
-
* Depth Anything). Ignored when `fixedSize` is set.
|
|
13
|
-
*/
|
|
14
|
-
multiple?: number;
|
|
15
|
-
/** Fixed `[width, height]` input. When omitted, the input follows each image's aspect ratio. */
|
|
16
|
-
fixedSize?: readonly [number, number];
|
|
17
|
-
/** How RGB is normalised before inference: ImageNet mean/std, or plain 0–1. */
|
|
18
|
-
normalization: 'imagenet' | 'unit';
|
|
19
|
-
/**
|
|
20
|
-
* How to read the output. `relative`: larger values are nearer (inverse
|
|
21
|
-
* depth, auto-ranged per image). `metric`: metres, mapped with a log scale.
|
|
22
|
-
*/
|
|
23
|
-
output: {
|
|
24
|
-
kind: 'relative';
|
|
25
|
-
} | {
|
|
26
|
-
kind: 'metric';
|
|
27
|
-
near: number;
|
|
28
|
-
far: number;
|
|
29
|
-
};
|
|
30
|
-
/** Needs the WebGPU `shader-f16` feature (fp16 weights). */
|
|
31
|
-
requiresF16?: boolean;
|
|
32
|
-
/** Used instead when `requiresF16` is set and the GPU lacks `shader-f16`. */
|
|
33
|
-
fallback?: DepthModelSpec;
|
|
34
|
-
/** Human-readable name, for pickers and logs. */
|
|
35
|
-
label?: string;
|
|
36
|
-
/** Download size in bytes, when known. */
|
|
37
|
-
bytes?: number;
|
|
38
|
-
}
|
|
39
|
-
type DepthModelPreset = 'depth-anything' | 'midas' | 'fastdepth';
|
|
40
|
-
/**
|
|
41
|
-
* The built-in models. Bundlers that understand `new URL(…, import.meta.url)`
|
|
42
|
-
* (Vite, webpack 5, Rollup) emit the bundled files as assets automatically.
|
|
43
|
-
*/
|
|
44
|
-
declare const MODEL_PRESETS: Record<DepthModelPreset, DepthModelSpec>;
|
|
45
|
-
declare const DEFAULT_MODEL: DepthModelPreset;
|
|
46
|
-
/**
|
|
47
|
-
* Register a custom model under a name, so elements can pick it with
|
|
48
|
-
* `model="name"`. Re-registering a name replaces it for future estimates.
|
|
49
|
-
*/
|
|
50
|
-
declare function registerModel(name: string, spec: DepthModelSpec): void;
|
|
51
|
-
/** Names usable in the `model` attribute: the presets and registered models. */
|
|
52
|
-
declare function listModels(): string[];
|
|
53
|
-
/** A preset or registered name, or a full spec. */
|
|
54
|
-
type DepthModelOption = DepthModelPreset | (string & {}) | DepthModelSpec;
|
|
55
3
|
/** True on devices without a hovering pointer that expose orientation events. */
|
|
56
4
|
declare function prefersGyro(): boolean;
|
|
57
5
|
/** Called when `getGyroPermission()` changes, e.g. after a grant or once readings arrive. */
|
|
@@ -143,7 +91,7 @@ interface ParallaxOptions {
|
|
|
143
91
|
disabled?: boolean;
|
|
144
92
|
/**
|
|
145
93
|
* A precompiled depth map (grayscale, near = bright, any size), e.g. from
|
|
146
|
-
* `img-auto-parallax precompute`. When set, no model or ONNX Runtime is loaded.
|
|
94
|
+
* `img-auto-parallax-build precompute`. When set, no model or ONNX Runtime is loaded.
|
|
147
95
|
*/
|
|
148
96
|
srcDepth?: string | null;
|
|
149
97
|
/** Model for this element: a preset or a `registerModel()` name. Defaults to `configure({ model })`. */
|
|
@@ -226,7 +174,7 @@ declare class ImgAutoParallaxElement extends HTMLElement implements Required<Par
|
|
|
226
174
|
/** Model for this element: `auto`, a preset (`q4f16`, `q4`, `fp16`, `fp32`) or a registered name. Defaults to `configure({ model })`. */
|
|
227
175
|
/**
|
|
228
176
|
* A precompiled depth map (grayscale, near = bright, any size), e.g. from
|
|
229
|
-
* `img-auto-parallax precompute`. When set, no model or ONNX Runtime is loaded.
|
|
177
|
+
* `img-auto-parallax-build precompute`. When set, no model or ONNX Runtime is loaded.
|
|
230
178
|
*/
|
|
231
179
|
get srcDepth(): string | null;
|
|
232
180
|
set srcDepth(value: string | null | undefined);
|
|
@@ -289,4 +237,4 @@ declare class ImgAutoParallaxElement extends HTMLElement implements Required<Par
|
|
|
289
237
|
disconnectedCallback(): void;
|
|
290
238
|
attributeChangedCallback(name: string, old: string | null, value: string | null): void;
|
|
291
239
|
}
|
|
292
|
-
export {
|
|
240
|
+
export { GyroPermission as _, ParallaxIdle as a, prefersGyro as b, ParallaxState as c, ImgAutoParallaxConfig as d, ModelProgress as f, preload as g, isSupported as h, ParallaxErrorDetail as i, ParallaxTrigger as l, hasWebGpu as m, ImgAutoParallaxElement as n, ParallaxLayer as o, configure as p, ImgAutoParallaxEventMap as r, ParallaxOptions as s, DEFAULTS as t, ParallaxView as u, getGyroPermission as v, requestGyroPermission as x, onGyroPermissionChange as y };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as GyroPermission, a as ParallaxIdle, b as prefersGyro, c as ParallaxState, d as ImgAutoParallaxConfig, f as ModelProgress, g as preload, h as isSupported, i as ParallaxErrorDetail, l as ParallaxTrigger, m as hasWebGpu, n as ImgAutoParallaxElement, o as ParallaxLayer, p as configure, r as ImgAutoParallaxEventMap, s as ParallaxOptions, t as DEFAULTS, u as ParallaxView, v as getGyroPermission, x as requestGyroPermission, y as onGyroPermissionChange } from "./element-DDl79CEt.mjs";
|
|
2
|
+
import { a as MODEL_PRESETS, i as DepthModelSpec, n as DepthModelOption, o as listModels, r as DepthModelPreset, s as registerModel, t as DEFAULT_MODEL } from "./models-BeWE4rVt.mjs";
|
|
2
3
|
export declare const DEFAULT_TAG = "img-auto-parallax";
|
|
3
4
|
/**
|
|
4
5
|
* Register the custom element (idempotent). Pass a different tag to avoid
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import { a as configure, c as preload, d as prefersGyro, f as requestGyroPermission, i as ImgAutoParallaxElement, l as getGyroPermission, n as defineImgAutoParallax, o as hasWebGpu, r as DEFAULTS, s as isSupported, t as DEFAULT_TAG, u as onGyroPermissionChange } from "./src-C092I6Rx.mjs";
|
|
2
|
+
import { i as registerModel, n as MODEL_PRESETS, r as listModels, t as DEFAULT_MODEL } from "./models-BmGGoJKs.mjs";
|
|
3
|
+
export { DEFAULTS, DEFAULT_MODEL, DEFAULT_TAG, ImgAutoParallaxElement, MODEL_PRESETS, configure, defineImgAutoParallax, getGyroPermission, hasWebGpu, isSupported, listModels, onGyroPermissionChange, prefersGyro, preload, registerModel, requestGyroPermission };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { c as resolveModel, i as DepthModelSpec, n as DepthModelOption, t as DEFAULT_MODEL } from "./models-BeWE4rVt.mjs";
|
|
2
|
+
/** Longest side of the colour image kept on the GPU for display. */
|
|
3
|
+
export declare const MAX_COLOUR_SIDE = 2048;
|
|
4
|
+
/**
|
|
5
|
+
* Model input size for a source image. Follows the image's aspect ratio with
|
|
6
|
+
* the long side near `resolution`, rounded to the model's `multiple`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function inferenceSize(model: Pick<DepthModelSpec, 'fixedSize' | 'multiple'>, sourceWidth: number, sourceHeight: number, resolution: number): [number, number];
|
|
9
|
+
/** Interleaved RGBA bytes to planar float32 RGB (NCHW without the batch axis). */
|
|
10
|
+
export declare function rgbaToNchw(rgba: ArrayLike<number>, width: number, height: number, normalization: DepthModelSpec['normalization']): Float32Array;
|
|
11
|
+
/** Fit `width`×`height` inside `maxSide`, never upscaling. */
|
|
12
|
+
export declare function fitWithin(width: number, height: number, maxSide: number): [number, number];
|
|
13
|
+
/**
|
|
14
|
+
* Raw model output to 0..1 nearness (1 = nearest), matching the GPU path
|
|
15
|
+
* (reduce-range.wgsl + normalize-depth.wgsl), so precompiled maps look the same.
|
|
16
|
+
*/
|
|
17
|
+
export declare function normalizeDepth(raw: ArrayLike<number>, output: DepthModelSpec['output']): Float32Array;
|
|
18
|
+
/** Box-filtered (area) RGBA resize, for decoding images outside the browser. */
|
|
19
|
+
export declare function resizeRgba(src: ArrayLike<number>, sw: number, sh: number, dw: number, dh: number): Uint8ClampedArray;
|
|
20
|
+
/**
|
|
21
|
+
* Nearness (0..1) to grayscale RGBA bytes: the precompiled depth map format.
|
|
22
|
+
* `levels` (2–256, default 256) rounds to that many evenly spaced grays, which
|
|
23
|
+
* PNG compresses far better.
|
|
24
|
+
*/
|
|
25
|
+
export declare function nearnessToRgba(nearness: ArrayLike<number>, levels?: number): Uint8ClampedArray;
|
|
26
|
+
/** Conventional depth map path for an image: `photo.jpg` → `photo.depth.png`. */
|
|
27
|
+
export declare function depthMapPath(image: string, suffix?: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* Joint bilateral upsampling of nearness to the colour image's size, guided by
|
|
30
|
+
* its colours, so depth edges follow the photo's edges. The CPU twin of
|
|
31
|
+
* shaders/upsample-depth.wgsl (precompiled maps match what the GPU computes).
|
|
32
|
+
*/
|
|
33
|
+
export declare function jointBilateralUpsample(low: ArrayLike<number>, lw: number, lh: number, rgba: ArrayLike<number>, hw: number, hh: number): Float32Array;
|
|
34
|
+
export { DEFAULT_MODEL, type DepthModelOption, type DepthModelSpec, resolveModel };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as DEFAULT_MODEL, o as MAX_COLOUR_SIDE, f as depthMapPath, c as fitWithin, l as inferenceSize, p as jointBilateralUpsample, m as nearnessToRgba, h as normalizeDepth, g as resizeRgba, a as resolveModel, d as rgbaToNchw } from "./models-BmGGoJKs.mjs";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Describes an ONNX depth model the runtime can drive. */
|
|
2
|
+
interface DepthModelSpec {
|
|
3
|
+
/** Location of the `.onnx` file. */
|
|
4
|
+
url: string | URL;
|
|
5
|
+
/** Graph input name (NCHW float32). */
|
|
6
|
+
inputName: string;
|
|
7
|
+
/** Graph output name (float32, `[1, H, W]` or `[1, 1, H, W]`). */
|
|
8
|
+
outputName: string;
|
|
9
|
+
/**
|
|
10
|
+
* Input sizes are rounded to a multiple of this (the ViT patch size for
|
|
11
|
+
* Depth Anything). Ignored when `fixedSize` is set.
|
|
12
|
+
*/
|
|
13
|
+
multiple?: number;
|
|
14
|
+
/** Fixed `[width, height]` input. When omitted, the input follows each image's aspect ratio. */
|
|
15
|
+
fixedSize?: readonly [number, number];
|
|
16
|
+
/** How RGB is normalised before inference: ImageNet mean/std, or plain 0–1. */
|
|
17
|
+
normalization: 'imagenet' | 'unit';
|
|
18
|
+
/**
|
|
19
|
+
* How to read the output. `relative`: larger values are nearer (inverse
|
|
20
|
+
* depth, auto-ranged per image). `metric`: metres, mapped with a log scale.
|
|
21
|
+
*/
|
|
22
|
+
output: {
|
|
23
|
+
kind: 'relative';
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'metric';
|
|
26
|
+
near: number;
|
|
27
|
+
far: number;
|
|
28
|
+
};
|
|
29
|
+
/** Needs the WebGPU `shader-f16` feature (fp16 weights). */
|
|
30
|
+
requiresF16?: boolean;
|
|
31
|
+
/** Used instead when `requiresF16` is set and the GPU lacks `shader-f16`. */
|
|
32
|
+
fallback?: DepthModelSpec;
|
|
33
|
+
/** Human-readable name, for pickers and logs. */
|
|
34
|
+
label?: string;
|
|
35
|
+
/** Download size in bytes, when known. */
|
|
36
|
+
bytes?: number;
|
|
37
|
+
}
|
|
38
|
+
type DepthModelPreset = 'depth-anything' | 'midas' | 'fastdepth';
|
|
39
|
+
/**
|
|
40
|
+
* The built-in models. Bundlers that understand `new URL(…, import.meta.url)`
|
|
41
|
+
* (Vite, webpack 5, Rollup) emit the bundled files as assets automatically.
|
|
42
|
+
*/
|
|
43
|
+
declare const MODEL_PRESETS: Record<DepthModelPreset, DepthModelSpec>;
|
|
44
|
+
declare const DEFAULT_MODEL: DepthModelPreset;
|
|
45
|
+
/**
|
|
46
|
+
* Register a custom model under a name, so elements can pick it with
|
|
47
|
+
* `model="name"`. Re-registering a name replaces it for future estimates.
|
|
48
|
+
*/
|
|
49
|
+
declare function registerModel(name: string, spec: DepthModelSpec): void;
|
|
50
|
+
/** Names usable in the `model` attribute: the presets and registered models. */
|
|
51
|
+
declare function listModels(): string[];
|
|
52
|
+
/** A preset or registered name, or a full spec. */
|
|
53
|
+
type DepthModelOption = DepthModelPreset | (string & {}) | DepthModelSpec;
|
|
54
|
+
/** Resolve a model option to the spec that runs on this GPU. */
|
|
55
|
+
declare function resolveModel(option: DepthModelOption, supportsF16: boolean): DepthModelSpec;
|
|
56
|
+
export { MODEL_PRESETS as a, resolveModel as c, DepthModelSpec as i, DepthModelOption as n, listModels as o, DepthModelPreset as r, registerModel as s, DEFAULT_MODEL as t };
|
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
import { Buffer } from "node:buffer";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
import { glob, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
-
import { availableParallelism } from "node:os";
|
|
5
|
-
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
-
import process from "node:process";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
-
import jpeg from "jpeg-js";
|
|
9
|
-
import { PNG } from "pngjs";
|
|
10
1
|
// src/depth-map.ts
|
|
11
2
|
/**
|
|
12
3
|
* Raw model output to 0..1 nearness (1 = nearest), matching the GPU path
|
|
@@ -90,6 +81,12 @@ function nearnessToRgba(nearness, levels = 256) {
|
|
|
90
81
|
}
|
|
91
82
|
return rgba;
|
|
92
83
|
}
|
|
84
|
+
/** Grayscale RGBA bytes (red channel) back to nearness. */
|
|
85
|
+
function rgbaToNearness(rgba, pixels) {
|
|
86
|
+
const out = new Float32Array(pixels);
|
|
87
|
+
for (let i = 0; i < pixels; i++) out[i] = rgba[i * 4] / 255;
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
93
90
|
/** Conventional depth map path for an image: `photo.jpg` → `photo.depth.png`. */
|
|
94
91
|
function depthMapPath(image, suffix = ".depth.png") {
|
|
95
92
|
return image.replace(/\.[^./\\]+$/, "") + suffix;
|
|
@@ -150,6 +147,114 @@ function jointBilateralUpsample(low, lw, lh, rgba, hw, hh) {
|
|
|
150
147
|
}
|
|
151
148
|
return high;
|
|
152
149
|
}
|
|
150
|
+
// src/preprocess.ts
|
|
151
|
+
const IMAGENET_MEAN = [
|
|
152
|
+
.485,
|
|
153
|
+
.456,
|
|
154
|
+
.406
|
|
155
|
+
];
|
|
156
|
+
const IMAGENET_STD = [
|
|
157
|
+
.229,
|
|
158
|
+
.224,
|
|
159
|
+
.225
|
|
160
|
+
];
|
|
161
|
+
/** Longest side of the colour image kept on the GPU for display. */
|
|
162
|
+
const MAX_COLOUR_SIDE = 2048;
|
|
163
|
+
/**
|
|
164
|
+
* Model input size for a source image. Follows the image's aspect ratio with
|
|
165
|
+
* the long side near `resolution`, rounded to the model's `multiple`.
|
|
166
|
+
*/
|
|
167
|
+
function inferenceSize(model, sourceWidth, sourceHeight, resolution) {
|
|
168
|
+
if (model.fixedSize) return [model.fixedSize[0], model.fixedSize[1]];
|
|
169
|
+
if (!(sourceWidth > 0) || !(sourceHeight > 0)) throw new Error(`Invalid source size ${sourceWidth}x${sourceHeight}.`);
|
|
170
|
+
const multiple = Math.max(1, Math.round(model.multiple ?? 1));
|
|
171
|
+
const scale = resolution / Math.max(sourceWidth, sourceHeight);
|
|
172
|
+
const snap = (value) => Math.max(multiple, Math.round(value * scale / multiple) * multiple);
|
|
173
|
+
return [snap(sourceWidth), snap(sourceHeight)];
|
|
174
|
+
}
|
|
175
|
+
/** Interleaved RGBA bytes to planar float32 RGB (NCHW without the batch axis). */
|
|
176
|
+
function rgbaToNchw(rgba, width, height, normalization) {
|
|
177
|
+
const pixels = width * height;
|
|
178
|
+
if (rgba.length < pixels * 4) throw new Error(`Expected ${pixels * 4} RGBA bytes for ${width}x${height}, got ${rgba.length}.`);
|
|
179
|
+
const output = new Float32Array(pixels * 3);
|
|
180
|
+
for (let channel = 0; channel < 3; channel += 1) {
|
|
181
|
+
const mean = normalization === "imagenet" ? IMAGENET_MEAN[channel] : 0;
|
|
182
|
+
const std = normalization === "imagenet" ? IMAGENET_STD[channel] : 1;
|
|
183
|
+
const plane = channel * pixels;
|
|
184
|
+
for (let pixel = 0; pixel < pixels; pixel += 1) output[plane + pixel] = (rgba[pixel * 4 + channel] / 255 - mean) / std;
|
|
185
|
+
}
|
|
186
|
+
return output;
|
|
187
|
+
}
|
|
188
|
+
/** Fit `width`×`height` inside `maxSide`, never upscaling. */
|
|
189
|
+
function fitWithin(width, height, maxSide) {
|
|
190
|
+
const scale = Math.min(1, maxSide / Math.max(width, height));
|
|
191
|
+
return [Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale))];
|
|
192
|
+
}
|
|
193
|
+
function createScratch() {
|
|
194
|
+
const canvas = typeof OffscreenCanvas === "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1);
|
|
195
|
+
const context = canvas.getContext("2d", { willReadFrequently: true });
|
|
196
|
+
if (!context) throw new Error("[img-auto-parallax] 2D canvas context is unavailable.");
|
|
197
|
+
return {
|
|
198
|
+
canvas,
|
|
199
|
+
context
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function drawScaled(scratch, source, width, height) {
|
|
203
|
+
const { canvas, context } = scratch;
|
|
204
|
+
if (canvas.width !== width || canvas.height !== height) {
|
|
205
|
+
canvas.width = width;
|
|
206
|
+
canvas.height = height;
|
|
207
|
+
}
|
|
208
|
+
context.imageSmoothingEnabled = true;
|
|
209
|
+
context.imageSmoothingQuality = "high";
|
|
210
|
+
context.clearRect(0, 0, width, height);
|
|
211
|
+
context.drawImage(source, 0, 0, width, height);
|
|
212
|
+
return context.getImageData(0, 0, width, height).data;
|
|
213
|
+
}
|
|
214
|
+
function sourceSize(source) {
|
|
215
|
+
if (typeof HTMLImageElement !== "undefined" && source instanceof HTMLImageElement) return [source.naturalWidth, source.naturalHeight];
|
|
216
|
+
if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
|
|
217
|
+
const sized = source;
|
|
218
|
+
return [Number(sized.width ?? 0), Number(sized.height ?? 0)];
|
|
219
|
+
}
|
|
220
|
+
/** Reusable canvases for preprocessing. Not safe for concurrent use. */
|
|
221
|
+
function createPreprocessor() {
|
|
222
|
+
const modelScratch = createScratch();
|
|
223
|
+
const displayScratch = createScratch();
|
|
224
|
+
return (source, model, resolution) => {
|
|
225
|
+
const [width, height] = sourceSize(source);
|
|
226
|
+
const depthSize = inferenceSize(model, width, height, resolution);
|
|
227
|
+
const modelRgba = drawScaled(modelScratch, source, depthSize[0], depthSize[1]);
|
|
228
|
+
const colourSize = fitWithin(width, height, MAX_COLOUR_SIDE);
|
|
229
|
+
const rgba = drawScaled(displayScratch, source, colourSize[0], colourSize[1]);
|
|
230
|
+
return {
|
|
231
|
+
nchw: rgbaToNchw(modelRgba, depthSize[0], depthSize[1], model.normalization),
|
|
232
|
+
depthSize,
|
|
233
|
+
rgba,
|
|
234
|
+
colourSize
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
let precompiledScratch;
|
|
239
|
+
/** Colour at display size plus a decoded depth map (red channel, near = bright). */
|
|
240
|
+
function readPrecompiled(source, depthMap) {
|
|
241
|
+
precompiledScratch ??= {
|
|
242
|
+
display: createScratch(),
|
|
243
|
+
depth: createScratch()
|
|
244
|
+
};
|
|
245
|
+
const [width, height] = sourceSize(source);
|
|
246
|
+
if (!width || !height) throw new Error("[img-auto-parallax] source has no intrinsic size.");
|
|
247
|
+
const colourSize = fitWithin(width, height, MAX_COLOUR_SIDE);
|
|
248
|
+
const rgba = drawScaled(precompiledScratch.display, source, colourSize[0], colourSize[1]);
|
|
249
|
+
const [dw, dh] = sourceSize(depthMap);
|
|
250
|
+
if (!dw || !dh) throw new Error("[img-auto-parallax] depth map has no intrinsic size.");
|
|
251
|
+
return {
|
|
252
|
+
nearness: rgbaToNearness(drawScaled(precompiledScratch.depth, depthMap, dw, dh), dw * dh),
|
|
253
|
+
depthSize: [dw, dh],
|
|
254
|
+
rgba,
|
|
255
|
+
colourSize
|
|
256
|
+
};
|
|
257
|
+
}
|
|
153
258
|
/**
|
|
154
259
|
* The built-in models. Bundlers that understand `new URL(…, import.meta.url)`
|
|
155
260
|
* (Vite, webpack 5, Rollup) emit the bundled files as assets automatically.
|
|
@@ -201,7 +306,15 @@ const MODEL_PRESETS = {
|
|
|
201
306
|
}
|
|
202
307
|
}
|
|
203
308
|
};
|
|
309
|
+
const DEFAULT_MODEL = "depth-anything";
|
|
204
310
|
const registry = new Map(Object.entries(MODEL_PRESETS));
|
|
311
|
+
/**
|
|
312
|
+
* Register a custom model under a name, so elements can pick it with
|
|
313
|
+
* `model="name"`. Re-registering a name replaces it for future estimates.
|
|
314
|
+
*/
|
|
315
|
+
function registerModel(name, spec) {
|
|
316
|
+
registry.set(name, spec);
|
|
317
|
+
}
|
|
205
318
|
/** Names usable in the `model` attribute: the presets and registered models. */
|
|
206
319
|
function listModels() {
|
|
207
320
|
return [...registry.keys()];
|
|
@@ -213,200 +326,4 @@ function resolveModel(option, supportsF16) {
|
|
|
213
326
|
if (spec.requiresF16 && !supportsF16 && spec.fallback) return spec.fallback;
|
|
214
327
|
return spec;
|
|
215
328
|
}
|
|
216
|
-
|
|
217
|
-
const IMAGENET_MEAN = [
|
|
218
|
-
.485,
|
|
219
|
-
.456,
|
|
220
|
-
.406
|
|
221
|
-
];
|
|
222
|
-
const IMAGENET_STD = [
|
|
223
|
-
.229,
|
|
224
|
-
.224,
|
|
225
|
-
.225
|
|
226
|
-
];
|
|
227
|
-
/** Longest side of the colour image kept on the GPU for display. */
|
|
228
|
-
const MAX_COLOUR_SIDE = 2048;
|
|
229
|
-
/**
|
|
230
|
-
* Model input size for a source image. Follows the image's aspect ratio with
|
|
231
|
-
* the long side near `resolution`, rounded to the model's `multiple`.
|
|
232
|
-
*/
|
|
233
|
-
function inferenceSize(model, sourceWidth, sourceHeight, resolution) {
|
|
234
|
-
if (model.fixedSize) return [model.fixedSize[0], model.fixedSize[1]];
|
|
235
|
-
if (!(sourceWidth > 0) || !(sourceHeight > 0)) throw new Error(`Invalid source size ${sourceWidth}x${sourceHeight}.`);
|
|
236
|
-
const multiple = Math.max(1, Math.round(model.multiple ?? 1));
|
|
237
|
-
const scale = resolution / Math.max(sourceWidth, sourceHeight);
|
|
238
|
-
const snap = (value) => Math.max(multiple, Math.round(value * scale / multiple) * multiple);
|
|
239
|
-
return [snap(sourceWidth), snap(sourceHeight)];
|
|
240
|
-
}
|
|
241
|
-
/** Interleaved RGBA bytes to planar float32 RGB (NCHW without the batch axis). */
|
|
242
|
-
function rgbaToNchw(rgba, width, height, normalization) {
|
|
243
|
-
const pixels = width * height;
|
|
244
|
-
if (rgba.length < pixels * 4) throw new Error(`Expected ${pixels * 4} RGBA bytes for ${width}x${height}, got ${rgba.length}.`);
|
|
245
|
-
const output = new Float32Array(pixels * 3);
|
|
246
|
-
for (let channel = 0; channel < 3; channel += 1) {
|
|
247
|
-
const mean = normalization === "imagenet" ? IMAGENET_MEAN[channel] : 0;
|
|
248
|
-
const std = normalization === "imagenet" ? IMAGENET_STD[channel] : 1;
|
|
249
|
-
const plane = channel * pixels;
|
|
250
|
-
for (let pixel = 0; pixel < pixels; pixel += 1) output[plane + pixel] = (rgba[pixel * 4 + channel] / 255 - mean) / std;
|
|
251
|
-
}
|
|
252
|
-
return output;
|
|
253
|
-
}
|
|
254
|
-
/** Fit `width`×`height` inside `maxSide`, never upscaling. */
|
|
255
|
-
function fitWithin(width, height, maxSide) {
|
|
256
|
-
const scale = Math.min(1, maxSide / Math.max(width, height));
|
|
257
|
-
return [Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale))];
|
|
258
|
-
}
|
|
259
|
-
// src/node.ts
|
|
260
|
-
let ort;
|
|
261
|
-
const sessions = /* @__PURE__ */ new Map();
|
|
262
|
-
/** Decode a JPEG or PNG to RGBA. */
|
|
263
|
-
function decodeImage(bytes) {
|
|
264
|
-
if (bytes[0] === 255 && bytes[1] === 216) {
|
|
265
|
-
const image = jpeg.decode(bytes, {
|
|
266
|
-
useTArray: true,
|
|
267
|
-
formatAsRGBA: true,
|
|
268
|
-
maxMemoryUsageInMB: 1024
|
|
269
|
-
});
|
|
270
|
-
return {
|
|
271
|
-
width: image.width,
|
|
272
|
-
height: image.height,
|
|
273
|
-
data: image.data
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
if (bytes[0] === 137 && bytes[1] === 80) {
|
|
277
|
-
const image = PNG.sync.read(Buffer.from(bytes));
|
|
278
|
-
return {
|
|
279
|
-
width: image.width,
|
|
280
|
-
height: image.height,
|
|
281
|
-
data: image.data
|
|
282
|
-
};
|
|
283
|
-
}
|
|
284
|
-
throw new Error("[img-auto-parallax] only JPEG and PNG images can be precompiled.");
|
|
285
|
-
}
|
|
286
|
-
function encodePng(rgba, width, height) {
|
|
287
|
-
const png = new PNG({
|
|
288
|
-
width,
|
|
289
|
-
height,
|
|
290
|
-
colorType: 0,
|
|
291
|
-
inputColorType: 6
|
|
292
|
-
});
|
|
293
|
-
png.data = Buffer.from(rgba.buffer, rgba.byteOffset, rgba.byteLength);
|
|
294
|
-
return new Uint8Array(PNG.sync.write(png, {
|
|
295
|
-
colorType: 0,
|
|
296
|
-
inputColorType: 6,
|
|
297
|
-
deflateLevel: 9
|
|
298
|
-
}));
|
|
299
|
-
}
|
|
300
|
-
async function loadModelBytes(model) {
|
|
301
|
-
const url = typeof model.url === "string" ? new URL(model.url) : model.url;
|
|
302
|
-
if (url.protocol === "file:") return new Uint8Array(await readFile(fileURLToPath(url)));
|
|
303
|
-
const response = await fetch(url);
|
|
304
|
-
if (!response.ok) throw new Error(`[img-auto-parallax] could not download ${url} (HTTP ${response.status}).`);
|
|
305
|
-
return new Uint8Array(await response.arrayBuffer());
|
|
306
|
-
}
|
|
307
|
-
function getSession(model) {
|
|
308
|
-
const key = String(model.url);
|
|
309
|
-
let session = sessions.get(key);
|
|
310
|
-
if (!session) {
|
|
311
|
-
session = (async () => {
|
|
312
|
-
ort ??= import("onnxruntime-web").then((mod) => {
|
|
313
|
-
mod.env.wasm.numThreads = Math.min(4, availableParallelism());
|
|
314
|
-
return mod;
|
|
315
|
-
});
|
|
316
|
-
return (await ort).InferenceSession.create(await loadModelBytes(model), { executionProviders: ["wasm"] });
|
|
317
|
-
})();
|
|
318
|
-
sessions.set(key, session);
|
|
319
|
-
session.catch(() => sessions.delete(key));
|
|
320
|
-
}
|
|
321
|
-
return session;
|
|
322
|
-
}
|
|
323
|
-
/** Run the depth model on an image (JPEG/PNG bytes) on the CPU, and encode the depth map. */
|
|
324
|
-
async function generateDepthMap(image, options = {}) {
|
|
325
|
-
const model = resolveModel(options.model ?? "depth-anything", true);
|
|
326
|
-
const decoded = decodeImage(image);
|
|
327
|
-
const resolution = options.resolution === "full" ? Math.max(...fitWithin(decoded.width, decoded.height, MAX_COLOUR_SIDE)) : options.resolution ?? 518;
|
|
328
|
-
const [width, height] = inferenceSize(model, decoded.width, decoded.height, resolution);
|
|
329
|
-
const rgba = resizeRgba(decoded.data, decoded.width, decoded.height, width, height);
|
|
330
|
-
const session = await getSession(model);
|
|
331
|
-
const input = new (await ort).Tensor("float32", rgbaToNchw(rgba, width, height, model.normalization), [
|
|
332
|
-
1,
|
|
333
|
-
3,
|
|
334
|
-
height,
|
|
335
|
-
width
|
|
336
|
-
]);
|
|
337
|
-
const output = (await session.run({ [model.inputName]: input }))[model.outputName];
|
|
338
|
-
if (!output || output.type !== "float32") throw new Error(`[img-auto-parallax] model output "${model.outputName}" is missing or not float32.`);
|
|
339
|
-
const dims = output.dims;
|
|
340
|
-
const outW = dims.at(-1);
|
|
341
|
-
const outH = dims.at(-2);
|
|
342
|
-
const nearness = normalizeDepth(output.data, model.output);
|
|
343
|
-
const levels = options.levels ?? 128;
|
|
344
|
-
if (options.mapSize !== "full") return {
|
|
345
|
-
width: outW,
|
|
346
|
-
height: outH,
|
|
347
|
-
png: encodePng(nearnessToRgba(nearness, levels), outW, outH)
|
|
348
|
-
};
|
|
349
|
-
const [width1, height1] = fitWithin(decoded.width, decoded.height, MAX_COLOUR_SIDE);
|
|
350
|
-
return {
|
|
351
|
-
width: width1,
|
|
352
|
-
height: height1,
|
|
353
|
-
png: encodePng(nearnessToRgba(jointBilateralUpsample(nearness, outW, outH, width1 === decoded.width && height1 === decoded.height ? decoded.data : resizeRgba(decoded.data, decoded.width, decoded.height, width1, height1), width1, height1), levels), width1, height1)
|
|
354
|
-
};
|
|
355
|
-
}
|
|
356
|
-
/**
|
|
357
|
-
* Generate `photo.depth.png` next to every matching image. Unchanged images
|
|
358
|
-
* (same content, model and resolution) are skipped.
|
|
359
|
-
*/
|
|
360
|
-
async function precompute(patterns, options = {}) {
|
|
361
|
-
const cwd = resolve(options.cwd ?? process.cwd());
|
|
362
|
-
const suffix = options.suffix ?? ".depth.png";
|
|
363
|
-
const files = [];
|
|
364
|
-
for (const pattern of Array.isArray(patterns) ? patterns : [patterns]) for await (const file of glob(pattern, { cwd })) {
|
|
365
|
-
const absolute = isAbsolute(file) ? file : join(cwd, file);
|
|
366
|
-
if (!absolute.endsWith(suffix) && /\.(?:jpe?g|png)$/i.test(extname(absolute))) files.push(absolute);
|
|
367
|
-
}
|
|
368
|
-
files.sort();
|
|
369
|
-
const cacheFile = options.cacheFile ?? join(cwd, "node_modules/.cache/img-auto-parallax.json");
|
|
370
|
-
let cache = {};
|
|
371
|
-
try {
|
|
372
|
-
cache = JSON.parse(await readFile(cacheFile, "utf8"));
|
|
373
|
-
} catch {}
|
|
374
|
-
const settingsKey = `v2:${String(resolveModel(options.model ?? "depth-anything", true).url).split("/").pop()}:${options.resolution ?? 518}:${options.mapSize ?? "model"}:${options.levels ?? 128}`;
|
|
375
|
-
const result = {
|
|
376
|
-
generated: [],
|
|
377
|
-
cached: []
|
|
378
|
-
};
|
|
379
|
-
for (const [index, file] of files.entries()) {
|
|
380
|
-
const output = depthMapPath(file, suffix);
|
|
381
|
-
const bytes = new Uint8Array(await readFile(file));
|
|
382
|
-
const hash = `${settingsKey}:${createHash("sha256").update(bytes).digest("hex").slice(0, 16)}`;
|
|
383
|
-
const key = relative(cwd, file);
|
|
384
|
-
const exists = await stat(output).then(() => true, () => false);
|
|
385
|
-
if (!options.force && exists && cache[key] === hash) {
|
|
386
|
-
result.cached.push(output);
|
|
387
|
-
options.onProgress?.({
|
|
388
|
-
file,
|
|
389
|
-
output,
|
|
390
|
-
status: "cached",
|
|
391
|
-
index,
|
|
392
|
-
total: files.length
|
|
393
|
-
});
|
|
394
|
-
continue;
|
|
395
|
-
}
|
|
396
|
-
const map = await generateDepthMap(bytes, options);
|
|
397
|
-
await writeFile(output, map.png);
|
|
398
|
-
cache[key] = hash;
|
|
399
|
-
result.generated.push(output);
|
|
400
|
-
options.onProgress?.({
|
|
401
|
-
file,
|
|
402
|
-
output,
|
|
403
|
-
status: "generated",
|
|
404
|
-
index,
|
|
405
|
-
total: files.length
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
await mkdir(dirname(cacheFile), { recursive: true });
|
|
409
|
-
await writeFile(cacheFile, `${JSON.stringify(cache, null, 2)}\n`);
|
|
410
|
-
return result;
|
|
411
|
-
}
|
|
412
|
-
export { depthMapPath as i, generateDepthMap as n, precompute as r, decodeImage as t };
|
|
329
|
+
export { resolveModel as a, fitWithin as c, rgbaToNchw as d, depthMapPath as f, resizeRgba as g, normalizeDepth as h, registerModel as i, inferenceSize as l, nearnessToRgba as m, MODEL_PRESETS as n, MAX_COLOUR_SIDE as o, jointBilateralUpsample as p, listModels as r, createPreprocessor as s, DEFAULT_MODEL as t, readPrecompiled as u };
|