@webex/ladon-ts 5.9.1 → 5.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/CHANGELOG.md +14 -0
- package/build/module/_virtual/_commonjsHelpers.js +7 -0
- package/build/module/_virtual/_commonjsHelpers.js.map +1 -0
- package/build/module/_virtual/logger.js +8 -0
- package/build/module/_virtual/logger.js.map +1 -0
- package/build/module/_virtual/logger2.js +5 -0
- package/build/module/_virtual/logger2.js.map +1 -0
- package/build/module/index.d.ts +1 -0
- package/build/module/index.js +38 -34
- package/build/module/index.js.map +1 -1
- package/build/module/lib/config-builder.js +56 -81
- package/build/module/lib/config-builder.js.map +1 -1
- package/build/module/lib/config.js +10 -9
- package/build/module/lib/config.js.map +1 -1
- package/build/module/lib/logger.d.ts +6 -0
- package/build/module/lib/logger.js +22 -0
- package/build/module/lib/logger.js.map +1 -0
- package/build/module/lib/pipeline.js +35 -37
- package/build/module/lib/pipeline.js.map +1 -1
- package/build/module/lib/renderer/blur-renderer.js +20 -30
- package/build/module/lib/renderer/blur-renderer.js.map +1 -1
- package/build/module/lib/renderer/replacement-renderer.js +7 -8
- package/build/module/lib/renderer/replacement-renderer.js.map +1 -1
- package/build/module/lib/renderer/webgl-renderer.js +14 -27
- package/build/module/lib/renderer/webgl-renderer.js.map +1 -1
- package/build/module/lib/resource-loader.js +8 -11
- package/build/module/lib/resource-loader.js.map +1 -1
- package/build/module/lib/util.js +40 -43
- package/build/module/lib/util.js.map +1 -1
- package/build/module/lib/version.d.ts +1 -1
- package/build/module/lib/version.js +1 -1
- package/build/module/lib/version.js.map +1 -1
- package/build/module/lib/worker-generator.js +7 -6
- package/build/module/lib/worker-generator.js.map +1 -1
- package/build/module/lib/worker-manager.js +17 -22
- package/build/module/lib/worker-manager.js.map +1 -1
- package/build/module/node_modules/js-logger/src/logger.js +108 -0
- package/build/module/node_modules/js-logger/src/logger.js.map +1 -0
- package/build/worker/segmentation.js +829 -825
- package/build/worker/segmentation.js.map +1 -1
- package/package.json +4 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { logger as l } from "./logger.js";
|
|
2
|
+
import { isResolvedUri as s, toAbsoluteURI as t } from "./util.js";
|
|
3
|
+
class d {
|
|
3
4
|
constructor() {
|
|
4
5
|
this.resolvedUriCache = /* @__PURE__ */ new Map();
|
|
5
6
|
}
|
|
@@ -15,19 +16,15 @@ class t {
|
|
|
15
16
|
* @returns The resolved full URL.
|
|
16
17
|
*/
|
|
17
18
|
async resolveUri(o, e) {
|
|
18
|
-
if (
|
|
19
|
-
throw new Error("Asset URI is undefined.");
|
|
20
|
-
if (this.resolvedUriCache.has(e))
|
|
19
|
+
if (e || l.errorAndThrow("Asset URI is undefined."), this.resolvedUriCache.has(e))
|
|
21
20
|
return this.resolvedUriCache.get(e);
|
|
22
21
|
let r;
|
|
23
|
-
|
|
24
|
-
throw new Error(`Failed to resolve asset URI: ${e}`);
|
|
25
|
-
return this.resolvedUriCache.set(e, r), r;
|
|
22
|
+
return s(e) ? r = e : e.match(/\.[a-z0-9]+$/i) ? typeof o.assetUrlResolver == "function" && (r = await o.assetUrlResolver(e, o)) : r = t(e, o.baseUrl), r || l.errorAndThrow(`Failed to resolve asset URI: ${e}`), this.resolvedUriCache.set(e, r), r;
|
|
26
23
|
}
|
|
27
24
|
}
|
|
28
|
-
const
|
|
25
|
+
const c = new d();
|
|
29
26
|
export {
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
d as ResourceLoader,
|
|
28
|
+
c as resourceLoader
|
|
32
29
|
};
|
|
33
30
|
//# sourceMappingURL=resource-loader.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-loader.js","sources":["../../../src/lib/resource-loader.ts"],"sourcesContent":["import { PreloadConfig } from './config-types';\nimport { isResolvedUri, toAbsoluteURI } from './util';\n\nexport class ResourceLoader {\n /**\n * In-memory cache for resolved URLs. This is used to avoid redundant network requests for\n * the same asset URI. The cache is a Map where the key is the asset URI and the value is\n * the resolved URL.\n */\n private resolvedUriCache: Map<string, string> = new Map();\n\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n public async resolveUri(config: PreloadConfig, assetUri?: string): Promise<string> {\n if (!assetUri) {\n
|
|
1
|
+
{"version":3,"file":"resource-loader.js","sources":["../../../src/lib/resource-loader.ts"],"sourcesContent":["import { PreloadConfig } from './config-types';\nimport { logger } from './logger';\nimport { isResolvedUri, toAbsoluteURI } from './util';\n\nexport class ResourceLoader {\n /**\n * In-memory cache for resolved URLs. This is used to avoid redundant network requests for\n * the same asset URI. The cache is a Map where the key is the asset URI and the value is\n * the resolved URL.\n */\n private resolvedUriCache: Map<string, string> = new Map();\n\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n public async resolveUri(config: PreloadConfig, assetUri?: string): Promise<string> {\n if (!assetUri) {\n logger.errorAndThrow('Asset URI is undefined.');\n }\n\n // Check if the URL is already cached\n if (this.resolvedUriCache.has(assetUri)) {\n return this.resolvedUriCache.get(assetUri) as string;\n }\n\n let resolvedUrl: string | undefined;\n\n if (isResolvedUri(assetUri)) {\n // If the assetUri is fully qualified or a blob URL, return it directly.\n // (Assets uris are resolved before being sent to the worker.)\n resolvedUrl = assetUri;\n } else if (!assetUri.match(/\\.[a-z0-9]+$/i)) {\n // Resolve as an absolute path to a non-file endpoint (e.g., wasmPaths).\n resolvedUrl = toAbsoluteURI(assetUri, config.baseUrl);\n } else if (typeof config.assetUrlResolver === 'function') {\n // Resolve via assetUrlResolver. This delegates the resolution logic to the caller.\n resolvedUrl = await config.assetUrlResolver(assetUri, config);\n }\n\n if (!resolvedUrl) {\n logger.errorAndThrow(`Failed to resolve asset URI: ${assetUri}`);\n }\n\n // Cache the resolved URL\n this.resolvedUriCache.set(assetUri, resolvedUrl);\n\n return resolvedUrl;\n }\n}\n\n// The resource loader is a singleton that can be used to load resources\nexport const resourceLoader = new ResourceLoader();\n"],"names":["ResourceLoader","config","assetUri","logger","resolvedUrl","isResolvedUri","toAbsoluteURI","resourceLoader"],"mappings":";;AAIO,MAAMA,EAAe;AAAA,EAArB,cAAA;AAMK,SAAA,uCAA4C,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaxD,MAAa,WAAWC,GAAuBC,GAAoC;AAM/E,QALKA,KACDC,EAAO,cAAc,yBAAyB,GAI9C,KAAK,iBAAiB,IAAID,CAAQ;AAC3B,aAAA,KAAK,iBAAiB,IAAIA,CAAQ;AAGzC,QAAAE;AAEA,WAAAC,EAAcH,CAAQ,IAGRE,IAAAF,IACNA,EAAS,MAAM,eAAe,IAG/B,OAAOD,EAAO,oBAAqB,eAE1CG,IAAc,MAAMH,EAAO,iBAAiBC,GAAUD,CAAM,KAH9CG,IAAAE,EAAcJ,GAAUD,EAAO,OAAO,GAMnDG,KACMD,EAAA,cAAc,gCAAgCD,CAAQ,EAAE,GAI9D,KAAA,iBAAiB,IAAIA,GAAUE,CAAW,GAExCA;AAAA,EAAA;AAEf;AAGa,MAAAG,IAAiB,IAAIP,EAAe;"}
|
package/build/module/lib/util.js
CHANGED
|
@@ -1,75 +1,72 @@
|
|
|
1
|
+
import { logger as P } from "./logger.js";
|
|
1
2
|
var I = /* @__PURE__ */ ((o) => (o.Nearest = "nearest", o))(I || {});
|
|
2
|
-
const
|
|
3
|
-
const l = new Uint8ClampedArray(r * e * 4),
|
|
4
|
-
let
|
|
3
|
+
const d = (o, n, u, r, e) => {
|
|
4
|
+
const l = new Uint8ClampedArray(r * e * 4), y = n / r, S = u / e, s = n * 4;
|
|
5
|
+
let c = 0;
|
|
5
6
|
for (let t = 0; t < e; t++) {
|
|
6
|
-
const f = Math.floor(t *
|
|
7
|
-
for (let
|
|
8
|
-
const m = f + Math.floor(
|
|
9
|
-
l[
|
|
7
|
+
const f = Math.floor(t * S) * s;
|
|
8
|
+
for (let a = 0; a < r; a++) {
|
|
9
|
+
const m = f + Math.floor(a * y) * 4;
|
|
10
|
+
l[c++] = o[m], l[c++] = o[m + 1], l[c++] = o[m + 2], l[c++] = o[m + 3];
|
|
10
11
|
}
|
|
11
12
|
}
|
|
12
13
|
return l;
|
|
13
14
|
};
|
|
14
|
-
function
|
|
15
|
+
function L(o, n, u, r, e) {
|
|
15
16
|
const l = new Uint8ClampedArray(r * e);
|
|
16
17
|
if (n === r && u === e) {
|
|
17
18
|
for (let s = 0; s < o.length; s++)
|
|
18
19
|
l[s] = Math.min(Math.max(o[s], 0), 255);
|
|
19
20
|
return l;
|
|
20
21
|
}
|
|
21
|
-
const
|
|
22
|
+
const y = (n - 1) / (r - 1), S = (u - 1) / (e - 1);
|
|
22
23
|
for (let s = 0; s < e; s++)
|
|
23
|
-
for (let
|
|
24
|
-
const t =
|
|
25
|
-
l[s * r +
|
|
24
|
+
for (let c = 0; c < r; c++) {
|
|
25
|
+
const t = y * c, f = S * s, a = Math.floor(t), m = Math.floor(f), w = Math.min(Math.ceil(t), n - 1), x = Math.min(Math.ceil(f), u - 1), p = t - a, i = f - m, M = o[m * n + a], h = o[m * n + w], T = o[x * n + a], A = o[x * n + w], k = M * (1 - p) * (1 - i) + h * p * (1 - i) + T * (1 - p) * i + A * p * i;
|
|
26
|
+
l[s * r + c] = Math.min(Math.max(k, 0), 255);
|
|
26
27
|
}
|
|
27
28
|
return l;
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
-
const l = new Uint8ClampedArray(r * e),
|
|
30
|
+
function R(o, n, u, r, e) {
|
|
31
|
+
const l = new Uint8ClampedArray(r * e), y = n / r, S = u / e, s = (t, f) => {
|
|
31
32
|
if (t === 0) return 1;
|
|
32
33
|
if (t < 0 && (t = -t), t < f) {
|
|
33
|
-
const
|
|
34
|
-
return f * Math.sin(
|
|
34
|
+
const a = Math.PI * t;
|
|
35
|
+
return f * Math.sin(a) * Math.sin(a / f) / (a * a);
|
|
35
36
|
}
|
|
36
37
|
return 0;
|
|
37
|
-
},
|
|
38
|
+
}, c = 3;
|
|
38
39
|
for (let t = 0; t < e; t++)
|
|
39
40
|
for (let f = 0; f < r; f++) {
|
|
40
|
-
const
|
|
41
|
-
let
|
|
42
|
-
for (let M = x -
|
|
43
|
-
for (let h =
|
|
41
|
+
const a = f * y, m = t * S, w = Math.floor(a), x = Math.floor(m);
|
|
42
|
+
let p = 0, i = 0;
|
|
43
|
+
for (let M = x - c + 1; M <= x + c; M++)
|
|
44
|
+
for (let h = w - c + 1; h <= w + c; h++)
|
|
44
45
|
if (h >= 0 && h < n && M >= 0 && M < u) {
|
|
45
|
-
const
|
|
46
|
-
|
|
46
|
+
const T = o[M * n + h], A = s(a - h, c) * s(m - M, c);
|
|
47
|
+
p += T * A, i += A;
|
|
47
48
|
}
|
|
48
|
-
l[t * r + f] = i !== 0 ? Math.round(
|
|
49
|
+
l[t * r + f] = i !== 0 ? Math.round(p / i) : 0;
|
|
49
50
|
}
|
|
50
51
|
return l;
|
|
51
52
|
}
|
|
52
|
-
function
|
|
53
|
+
function C(o, n, u) {
|
|
53
54
|
const r = o.createShader(n);
|
|
54
|
-
if (!r)
|
|
55
|
-
throw new Error("[ladon-ts] Error creating shader");
|
|
56
|
-
if (o.shaderSource(r, u), o.compileShader(r), !o.getShaderParameter(r, o.COMPILE_STATUS)) {
|
|
55
|
+
if (r || P.errorAndThrow("Error creating shader"), o.shaderSource(r, u), o.compileShader(r), !o.getShaderParameter(r, o.COMPILE_STATUS)) {
|
|
57
56
|
const e = o.getShaderInfoLog(r) ?? "unknown error compiling shader.";
|
|
58
|
-
|
|
57
|
+
P.errorAndThrow(e);
|
|
59
58
|
}
|
|
60
59
|
return r;
|
|
61
60
|
}
|
|
62
|
-
function
|
|
61
|
+
function b(o, n, u) {
|
|
63
62
|
const r = o.createProgram();
|
|
64
|
-
if (!r)
|
|
65
|
-
throw new Error("[ladon-ts] Error creating GPU program");
|
|
66
|
-
if (o.attachShader(r, n), o.attachShader(r, u), o.linkProgram(r), !o.getProgramParameter(r, o.LINK_STATUS)) {
|
|
63
|
+
if (r || P.errorAndThrow("Error creating GPU program"), o.attachShader(r, n), o.attachShader(r, u), o.linkProgram(r), !o.getProgramParameter(r, o.LINK_STATUS)) {
|
|
67
64
|
const e = o.getProgramInfoLog(r) ?? "unknown error linking program.";
|
|
68
|
-
|
|
65
|
+
P.errorAndThrow(e);
|
|
69
66
|
}
|
|
70
67
|
return r;
|
|
71
68
|
}
|
|
72
|
-
function
|
|
69
|
+
function z(o) {
|
|
73
70
|
if (o.startsWith("blob:"))
|
|
74
71
|
return !0;
|
|
75
72
|
try {
|
|
@@ -78,15 +75,15 @@ function C(o) {
|
|
|
78
75
|
return !1;
|
|
79
76
|
}
|
|
80
77
|
}
|
|
81
|
-
const
|
|
78
|
+
const E = (o, n) => !n || o.startsWith("http") ? new URL(o).href : o ? n.replace(/\/+$/, "") + "/" + o.replace(/^\/+/, "") : n;
|
|
82
79
|
export {
|
|
83
80
|
I as InterpolationMethod,
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
81
|
+
L as bilinearUpsample,
|
|
82
|
+
C as compileShader,
|
|
83
|
+
z as isResolvedUri,
|
|
84
|
+
R as lanczos3Upsample,
|
|
85
|
+
b as linkProgram,
|
|
86
|
+
d as resizeImage,
|
|
87
|
+
E as toAbsoluteURI
|
|
91
88
|
};
|
|
92
89
|
//# sourceMappingURL=util.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","sources":["../../../src/lib/util.ts"],"sourcesContent":["export enum InterpolationMethod {\n Nearest = 'nearest',\n}\n\n/**\n * Resizes an image from the source dimensions to target dimensions.\n *\n * @param {Uint8ClampedArray} imageData The source image data in Uint8ClampedArray format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The target image data in Uint8ClampedArray format.\n *\n * @example\n * const targetData = resizeImage(sourceData, 800, 600, 400, 300);\n *\n * @note The function uses a \"nearest neighbor\" algorithm for resizing,\n * which is fast but might not provide the best quality for all images.\n */\nexport const resizeImage = (\n imageData: Uint8ClampedArray,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n): Uint8ClampedArray => {\n const targetData = new Uint8ClampedArray(targetWidth * targetHeight * 4);\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n const scaledSrcWidth = srcWidth * 4;\n let offset = 0;\n\n for (let y = 0; y < targetHeight; y++) {\n const srcY = Math.floor(y * yRatio) * scaledSrcWidth;\n for (let x = 0; x < targetWidth; x++) {\n const srcOffset = srcY + Math.floor(x * xRatio) * 4;\n\n targetData[offset++] = imageData[srcOffset];\n targetData[offset++] = imageData[srcOffset + 1];\n targetData[offset++] = imageData[srcOffset + 2];\n targetData[offset++] = imageData[srcOffset + 3];\n }\n }\n\n return targetData;\n};\n\n/**\n * Upsamples an image using the bilinear interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n *\n */\nexport function bilinearUpsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n // If the source and target dimensions are the same, just copy the input to the output.\n // The output is expected to be in the [0, 255] range\n if (srcWidth === targetWidth && srcHeight === targetHeight) {\n for (let i = 0; i < input.length; i++) {\n output[i] = Math.min(Math.max(input[i], 0), 255);\n }\n return output;\n }\n\n const xRatio = (srcWidth - 1) / (targetWidth - 1);\n const yRatio = (srcHeight - 1) / (targetHeight - 1);\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = xRatio * j;\n const y = yRatio * i;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n const xH = Math.min(Math.ceil(x), srcWidth - 1);\n const yH = Math.min(Math.ceil(y), srcHeight - 1);\n\n const xWeight = x - xL;\n const yWeight = y - yL;\n\n const a = input[yL * srcWidth + xL];\n const b = input[yL * srcWidth + xH];\n const c = input[yH * srcWidth + xL];\n const d = input[yH * srcWidth + xH];\n\n const value =\n a * (1 - xWeight) * (1 - yWeight) +\n b * xWeight * (1 - yWeight) +\n c * (1 - xWeight) * yWeight +\n d * xWeight * yWeight;\n\n output[i * targetWidth + j] = Math.min(Math.max(value, 0), 255);\n }\n }\n\n return output;\n}\n\n/**\n * Upsamples an image using the Lanczos3 interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n */\nexport function lanczos3Upsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n\n const lanczos = (x: number, a: number) => {\n if (x === 0) return 1;\n if (x < 0) x = -x;\n if (x < a) {\n const piX = Math.PI * x;\n return (a * Math.sin(piX) * Math.sin(piX / a)) / (piX * piX);\n }\n return 0;\n };\n\n const a = 3; // Lanczos parameter\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = j * xRatio;\n const y = i * yRatio;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n\n let value = 0;\n let weightSum = 0;\n\n for (let ky = yL - a + 1; ky <= yL + a; ky++) {\n for (let kx = xL - a + 1; kx <= xL + a; kx++) {\n if (kx >= 0 && kx < srcWidth && ky >= 0 && ky < srcHeight) {\n const pixel = input[ky * srcWidth + kx];\n const weight = lanczos(x - kx, a) * lanczos(y - ky, a);\n value += pixel * weight;\n weightSum += weight;\n }\n }\n }\n\n output[i * targetWidth + j] = weightSum !== 0 ? Math.round(value / weightSum) : 0;\n }\n }\n\n return output;\n}\n\nexport function compileShader(\n gl: WebGL2RenderingContext,\n shader_type: number,\n source: string\n): WebGLShader {\n const shader = gl.createShader(shader_type);\n\n if (!shader) {\n throw new Error('[ladon-ts] Error creating shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const error = gl.getShaderInfoLog(shader) ?? 'unknown error compiling shader.';\n throw new Error('[ladon-ts] ' + error);\n }\n\n return shader;\n}\n\nexport function linkProgram(\n gl: WebGL2RenderingContext,\n vertex_shader: WebGLShader,\n fragment_shader: WebGLShader\n): WebGLProgram {\n const program = gl.createProgram();\n\n if (!program) {\n throw new Error('[ladon-ts] Error creating GPU program');\n }\n\n gl.attachShader(program, vertex_shader);\n gl.attachShader(program, fragment_shader);\n\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const error = gl.getProgramInfoLog(program) ?? 'unknown error linking program.';\n throw new Error('[ladon-ts] ' + error);\n }\n\n return program;\n}\n\n/**\n * Determines if a URI is already resolved.\n * A resolved URI is either:\n * - A blob URL (starts with 'blob:')\n * - A fully qualified URL (e.g., http:// or https://)\n *\n * @param uri - The URI to check.\n * @returns Whether the URI is already resolved.\n */\nexport function isResolvedUri(uri: string): boolean {\n if (uri.startsWith('blob:')) {\n // Blob URIs are resolved\n return true;\n }\n\n try {\n // Throws if the URI is not a valid full URL\n new URL(uri);\n return true;\n } catch {\n // Not a fully qualified URL\n return false;\n }\n}\n\nexport const toAbsoluteURI = (relativeURL: string, baseURL?: string) => {\n // adapted from - https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js\n\n if (!baseURL || relativeURL.startsWith('http')) {\n return new URL(relativeURL).href;\n }\n\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n"],"names":["InterpolationMethod","resizeImage","imageData","srcWidth","srcHeight","targetWidth","targetHeight","targetData","xRatio","yRatio","scaledSrcWidth","offset","y","srcY","x","srcOffset","bilinearUpsample","input","output","i","j","xL","yL","xH","yH","xWeight","yWeight","a","b","c","d","value","lanczos3Upsample","lanczos","piX","weightSum","ky","kx","pixel","weight","compileShader","gl","shader_type","source","shader","error","linkProgram","vertex_shader","fragment_shader","program","isResolvedUri","uri","toAbsoluteURI","relativeURL","baseURL"],"mappings":"AAAY,IAAAA,sBAAAA,OACRA,EAAA,UAAU,WADFA,IAAAA,KAAA,CAAA,CAAA;AAqBL,MAAMC,IAAc,CACvBC,GACAC,GACAC,GACAC,GACAC,MACoB;AACpB,QAAMC,IAAa,IAAI,kBAAkBF,IAAcC,IAAe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AO;AAEf,WAAA;AAGP,MAAA;AAEA,eAAI,IAAIA,CAAG,GACJ;AAAA,EAAA,QACH;AAEG,WAAA;AAAA,EAAA;AAEf;AAEa,MAAAC,IAAgB,CAACC,GAAqBC,MAG3C,CAACA,KAAWD,EAAY,WAAW,MAAM,IAClC,IAAI,IAAIA,CAAW,EAAE,OAGzBA,IACDC,EAAQ,QAAQ,QAAQ,EAAE,IAAI,MAAMD,EAAY,QAAQ,QAAQ,EAAE,IAClEC;"}
|
|
1
|
+
{"version":3,"file":"util.js","sources":["../../../src/lib/util.ts"],"sourcesContent":["import { logger } from './logger';\n\nexport enum InterpolationMethod {\n Nearest = 'nearest',\n}\n\n/**\n * Resizes an image from the source dimensions to target dimensions.\n *\n * @param {Uint8ClampedArray} imageData The source image data in Uint8ClampedArray format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The target image data in Uint8ClampedArray format.\n *\n * @example\n * const targetData = resizeImage(sourceData, 800, 600, 400, 300);\n *\n * @note The function uses a \"nearest neighbor\" algorithm for resizing,\n * which is fast but might not provide the best quality for all images.\n */\nexport const resizeImage = (\n imageData: Uint8ClampedArray,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n): Uint8ClampedArray => {\n const targetData = new Uint8ClampedArray(targetWidth * targetHeight * 4);\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n const scaledSrcWidth = srcWidth * 4;\n let offset = 0;\n\n for (let y = 0; y < targetHeight; y++) {\n const srcY = Math.floor(y * yRatio) * scaledSrcWidth;\n for (let x = 0; x < targetWidth; x++) {\n const srcOffset = srcY + Math.floor(x * xRatio) * 4;\n\n targetData[offset++] = imageData[srcOffset];\n targetData[offset++] = imageData[srcOffset + 1];\n targetData[offset++] = imageData[srcOffset + 2];\n targetData[offset++] = imageData[srcOffset + 3];\n }\n }\n\n return targetData;\n};\n\n/**\n * Upsamples an image using the bilinear interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n *\n */\nexport function bilinearUpsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n // If the source and target dimensions are the same, just copy the input to the output.\n // The output is expected to be in the [0, 255] range\n if (srcWidth === targetWidth && srcHeight === targetHeight) {\n for (let i = 0; i < input.length; i++) {\n output[i] = Math.min(Math.max(input[i], 0), 255);\n }\n return output;\n }\n\n const xRatio = (srcWidth - 1) / (targetWidth - 1);\n const yRatio = (srcHeight - 1) / (targetHeight - 1);\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = xRatio * j;\n const y = yRatio * i;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n const xH = Math.min(Math.ceil(x), srcWidth - 1);\n const yH = Math.min(Math.ceil(y), srcHeight - 1);\n\n const xWeight = x - xL;\n const yWeight = y - yL;\n\n const a = input[yL * srcWidth + xL];\n const b = input[yL * srcWidth + xH];\n const c = input[yH * srcWidth + xL];\n const d = input[yH * srcWidth + xH];\n\n const value =\n a * (1 - xWeight) * (1 - yWeight) +\n b * xWeight * (1 - yWeight) +\n c * (1 - xWeight) * yWeight +\n d * xWeight * yWeight;\n\n output[i * targetWidth + j] = Math.min(Math.max(value, 0), 255);\n }\n }\n\n return output;\n}\n\n/**\n * Upsamples an image using the Lanczos3 interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n */\nexport function lanczos3Upsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n\n const lanczos = (x: number, a: number) => {\n if (x === 0) return 1;\n if (x < 0) x = -x;\n if (x < a) {\n const piX = Math.PI * x;\n return (a * Math.sin(piX) * Math.sin(piX / a)) / (piX * piX);\n }\n return 0;\n };\n\n const a = 3; // Lanczos parameter\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = j * xRatio;\n const y = i * yRatio;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n\n let value = 0;\n let weightSum = 0;\n\n for (let ky = yL - a + 1; ky <= yL + a; ky++) {\n for (let kx = xL - a + 1; kx <= xL + a; kx++) {\n if (kx >= 0 && kx < srcWidth && ky >= 0 && ky < srcHeight) {\n const pixel = input[ky * srcWidth + kx];\n const weight = lanczos(x - kx, a) * lanczos(y - ky, a);\n value += pixel * weight;\n weightSum += weight;\n }\n }\n }\n\n output[i * targetWidth + j] = weightSum !== 0 ? Math.round(value / weightSum) : 0;\n }\n }\n\n return output;\n}\n\nexport function compileShader(\n gl: WebGL2RenderingContext,\n shader_type: number,\n source: string\n): WebGLShader {\n const shader = gl.createShader(shader_type);\n\n if (!shader) {\n logger.errorAndThrow('Error creating shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const error = gl.getShaderInfoLog(shader) ?? 'unknown error compiling shader.';\n logger.errorAndThrow(error);\n }\n\n return shader;\n}\n\nexport function linkProgram(\n gl: WebGL2RenderingContext,\n vertex_shader: WebGLShader,\n fragment_shader: WebGLShader\n): WebGLProgram {\n const program = gl.createProgram();\n\n if (!program) {\n logger.errorAndThrow('Error creating GPU program');\n }\n\n gl.attachShader(program, vertex_shader);\n gl.attachShader(program, fragment_shader);\n\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const error = gl.getProgramInfoLog(program) ?? 'unknown error linking program.';\n logger.errorAndThrow(error);\n }\n\n return program;\n}\n\n/**\n * Determines if a URI is already resolved.\n * A resolved URI is either:\n * - A blob URL (starts with 'blob:')\n * - A fully qualified URL (e.g., http:// or https://)\n *\n * @param uri - The URI to check.\n * @returns Whether the URI is already resolved.\n */\nexport function isResolvedUri(uri: string): boolean {\n if (uri.startsWith('blob:')) {\n // Blob URIs are resolved\n return true;\n }\n\n try {\n // Throws if the URI is not a valid full URL\n new URL(uri);\n return true;\n } catch {\n // Not a fully qualified URL\n return false;\n }\n}\n\nexport const toAbsoluteURI = (relativeURL: string, baseURL?: string) => {\n // adapted from - https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js\n\n if (!baseURL || relativeURL.startsWith('http')) {\n return new URL(relativeURL).href;\n }\n\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n"],"names":["InterpolationMethod","resizeImage","imageData","srcWidth","srcHeight","targetWidth","targetHeight","targetData","xRatio","yRatio","scaledSrcWidth","offset","y","srcY","x","srcOffset","bilinearUpsample","input","output","i","j","xL","yL","xH","yH","xWeight","yWeight","a","b","c","d","value","lanczos3Upsample","lanczos","piX","weightSum","ky","kx","pixel","weight","compileShader","gl","shader_type","source","shader","logger","error","linkProgram","vertex_shader","fragment_shader","program","isResolvedUri","uri","toAbsoluteURI","relativeURL","baseURL"],"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,CAAO,KAAK;AAC/C,IAAAL,EAAO,cAAcC,CAAK;AAAA,EAAA;AAGvB,SAAAI;AACX;AAWO,SAASC,EAAcC,GAAsB;AAC5C,MAAAA,EAAI,WAAW,OAAO;AAEf,WAAA;AAGP,MAAA;AAEA,eAAI,IAAIA,CAAG,GACJ;AAAA,EAAA,QACH;AAEG,WAAA;AAAA,EAAA;AAEf;AAEa,MAAAC,IAAgB,CAACC,GAAqBC,MAG3C,CAACA,KAAWD,EAAY,WAAW,MAAM,IAClC,IAAI,IAAIA,CAAW,EAAE,OAGzBA,IACDC,EAAQ,QAAQ,QAAQ,EAAE,IAAI,MAAMD,EAAY,QAAQ,QAAQ,EAAE,IAClEC;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const LIB_VERSION = "5.
|
|
1
|
+
export declare const LIB_VERSION = "5.10.0";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sources":["../../../src/lib/version.ts"],"sourcesContent":["export const LIB_VERSION = '5.
|
|
1
|
+
{"version":3,"file":"version.js","sources":["../../../src/lib/version.ts"],"sourcesContent":["export const LIB_VERSION = '5.10.0';\n"],"names":["LIB_VERSION"],"mappings":"AAAO,MAAMA,IAAc;"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { logger as i } from "./logger.js";
|
|
1
2
|
import { workerManager as s } from "./worker-manager.js";
|
|
2
|
-
class
|
|
3
|
+
class d {
|
|
3
4
|
constructor(e) {
|
|
4
5
|
this.config = e, this.pending = /* @__PURE__ */ new Map(), this.newMask = !0, this.lastResult = {
|
|
5
6
|
data: new Float32Array(
|
|
@@ -67,16 +68,16 @@ class m {
|
|
|
67
68
|
const r = this.pending.get(t);
|
|
68
69
|
r && (r(this.lastResult), this.pending.delete(t));
|
|
69
70
|
}), s.onLog((t, r) => {
|
|
70
|
-
const a = `
|
|
71
|
+
const a = `Message received from worker: ${t}`;
|
|
71
72
|
switch (r) {
|
|
72
73
|
case "warn":
|
|
73
|
-
|
|
74
|
+
i.warn(a);
|
|
74
75
|
break;
|
|
75
76
|
case "error":
|
|
76
|
-
|
|
77
|
+
i.error(a);
|
|
77
78
|
break;
|
|
78
79
|
default:
|
|
79
|
-
|
|
80
|
+
i.log(a);
|
|
80
81
|
}
|
|
81
82
|
}), (async () => (await (s.getWorker() ?? s.initializeWorker(e)), s.sendInit({
|
|
82
83
|
baseUrl: e.baseUrl,
|
|
@@ -111,6 +112,6 @@ class m {
|
|
|
111
112
|
}
|
|
112
113
|
}
|
|
113
114
|
export {
|
|
114
|
-
|
|
115
|
+
d as WorkerGenerator
|
|
115
116
|
};
|
|
116
117
|
//# sourceMappingURL=worker-generator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-generator.js","sources":["../../../src/lib/worker-generator.ts"],"sourcesContent":["import { PipelineConfig } from './config-types';\nimport { LadonOutput, MaskGenerator, WorkerGeneratedResult } from './generator-types';\nimport { workerManager } from './worker-manager';\n\nexport class WorkerGenerator implements MaskGenerator {\n private pending: Map<number, (result: LadonOutput) => void> = new Map();\n private lastResult: LadonOutput;\n private newMask = true;\n\n constructor(public readonly config: PipelineConfig) {\n this.lastResult = {\n data: new Float32Array(\n this.config.mask.outputSize.height * this.config.mask.outputSize.width\n ),\n facesAndLandmarks: { data: new Float32Array(0), dims: [] },\n gesture: new Float32Array(0),\n motion: 0,\n timestamp: 0,\n warm: false,\n };\n }\n\n public isLoaded(): boolean {\n return !!workerManager.getWorker();\n }\n\n public async getLadonOutput(): Promise<LadonOutput> {\n const toReturn = {\n data: this.lastResult.data,\n facesAndLandmarks: this.lastResult.facesAndLandmarks,\n gesture: this.lastResult.gesture,\n motion: this.lastResult.motion,\n timestamp: this.lastResult.timestamp,\n warm: this.newMask,\n };\n\n this.newMask = false;\n\n return toReturn;\n }\n\n /**\n * Returns a promise that resolves when the worker returns the mask for the given timestamp.\n * This is useful for synchronizing the processing of frames with their corresponding masks.\n * The promise will be resolved with the mask data when it is available.\n *\n * @param timestamp - The timestamp of the frame for which the mask is requested.\n * @returns A promise that resolves with the mask data when available.\n */\n public async getLadonOutputForTimestamp(timestamp: number): Promise<LadonOutput> {\n return new Promise<LadonOutput>((resolve) => {\n this.pending.set(timestamp, resolve);\n });\n }\n\n /**\n * Loads the worker and initializes it with the provided configuration.\n * The worker is responsible for processing the input image and generating the mask.\n * Prepares the worker configuration by resolving the final URLs and paths to send to the worker.\n *\n * @returns A promise that resolves when the worker is loaded and initialized.\n */\n public async load(): Promise<void> {\n const config = await workerManager.prepareWorkerConfig(this.config);\n\n // Listen for worker events\n return new Promise<void>((resolve) => {\n workerManager.onInitialized(() => {\n resolve();\n });\n workerManager.onGenerated((data: WorkerGeneratedResult) => {\n const result: LadonOutput = {\n data: data.mask,\n facesAndLandmarks: data.facesAndLandmarks,\n gesture: data.gesture,\n motion: data.motion,\n timestamp: data.timestamp,\n warm: true,\n };\n this.lastResult = result;\n this.newMask = true;\n\n // Resolve the pending promise for this timestamp, if any\n const cb = this.pending.get(data.timestamp);\n if (cb) {\n cb(result);\n this.pending.delete(data.timestamp);\n }\n });\n workerManager.onDropped((timestamp: number) => {\n // Resolve the pending promise for this timestamp with the last result\n const cb = this.pending.get(timestamp);\n if (cb) {\n cb(this.lastResult);\n this.pending.delete(timestamp);\n }\n });\n workerManager.onLog((message, severity) => {\n const msg = `
|
|
1
|
+
{"version":3,"file":"worker-generator.js","sources":["../../../src/lib/worker-generator.ts"],"sourcesContent":["import { PipelineConfig } from './config-types';\nimport { LadonOutput, MaskGenerator, WorkerGeneratedResult } from './generator-types';\nimport { logger } from './logger';\nimport { workerManager } from './worker-manager';\n\nexport class WorkerGenerator implements MaskGenerator {\n private pending: Map<number, (result: LadonOutput) => void> = new Map();\n private lastResult: LadonOutput;\n private newMask = true;\n\n constructor(public readonly config: PipelineConfig) {\n this.lastResult = {\n data: new Float32Array(\n this.config.mask.outputSize.height * this.config.mask.outputSize.width\n ),\n facesAndLandmarks: { data: new Float32Array(0), dims: [] },\n gesture: new Float32Array(0),\n motion: 0,\n timestamp: 0,\n warm: false,\n };\n }\n\n public isLoaded(): boolean {\n return !!workerManager.getWorker();\n }\n\n public async getLadonOutput(): Promise<LadonOutput> {\n const toReturn = {\n data: this.lastResult.data,\n facesAndLandmarks: this.lastResult.facesAndLandmarks,\n gesture: this.lastResult.gesture,\n motion: this.lastResult.motion,\n timestamp: this.lastResult.timestamp,\n warm: this.newMask,\n };\n\n this.newMask = false;\n\n return toReturn;\n }\n\n /**\n * Returns a promise that resolves when the worker returns the mask for the given timestamp.\n * This is useful for synchronizing the processing of frames with their corresponding masks.\n * The promise will be resolved with the mask data when it is available.\n *\n * @param timestamp - The timestamp of the frame for which the mask is requested.\n * @returns A promise that resolves with the mask data when available.\n */\n public async getLadonOutputForTimestamp(timestamp: number): Promise<LadonOutput> {\n return new Promise<LadonOutput>((resolve) => {\n this.pending.set(timestamp, resolve);\n });\n }\n\n /**\n * Loads the worker and initializes it with the provided configuration.\n * The worker is responsible for processing the input image and generating the mask.\n * Prepares the worker configuration by resolving the final URLs and paths to send to the worker.\n *\n * @returns A promise that resolves when the worker is loaded and initialized.\n */\n public async load(): Promise<void> {\n const config = await workerManager.prepareWorkerConfig(this.config);\n\n // Listen for worker events\n return new Promise<void>((resolve) => {\n workerManager.onInitialized(() => {\n resolve();\n });\n workerManager.onGenerated((data: WorkerGeneratedResult) => {\n const result: LadonOutput = {\n data: data.mask,\n facesAndLandmarks: data.facesAndLandmarks,\n gesture: data.gesture,\n motion: data.motion,\n timestamp: data.timestamp,\n warm: true,\n };\n this.lastResult = result;\n this.newMask = true;\n\n // Resolve the pending promise for this timestamp, if any\n const cb = this.pending.get(data.timestamp);\n if (cb) {\n cb(result);\n this.pending.delete(data.timestamp);\n }\n });\n workerManager.onDropped((timestamp: number) => {\n // Resolve the pending promise for this timestamp with the last result\n const cb = this.pending.get(timestamp);\n if (cb) {\n cb(this.lastResult);\n this.pending.delete(timestamp);\n }\n });\n workerManager.onLog((message, severity) => {\n const msg = `Message received from worker: ${message}`;\n switch (severity) {\n case 'warn':\n logger.warn(msg);\n break;\n case 'error':\n logger.error(msg);\n break;\n default:\n logger.log(msg);\n }\n });\n\n // Initialize the worker if not already done, then always send init\n (async () => {\n await (workerManager.getWorker() ?? workerManager.initializeWorker(config));\n workerManager.sendInit({\n baseUrl: config.baseUrl,\n input: config.input,\n mask: config.mask,\n wasmUri: config.wasmUri,\n render: { type: 'passthrough' },\n });\n })();\n });\n }\n\n /**\n * Sends the input image to the worker for processing.\n * The input image is expected to be a Uint8ClampedArray.\n * Claims ownership of the input tensor's buffer and forwards it to the worker.\n *\n * @param input - The input image as a Uint8ClampedArray.\n * @param timestamp - The timestamp of the input image.\n */\n public async process(input: Uint8ClampedArray, timestamp: number): Promise<void> {\n workerManager.sendGenerate(input, timestamp);\n }\n\n /**\n * Destroys the worker and cleans up resources.\n * First it sends a message to the worker to destroy itself,\n * then it waits for the worker to respond with a 'destroyed' message.\n * After that, it terminates the worker and revokes the URL if it exists.\n *\n * @returns A promise that resolves when the worker is destroyed.\n */\n public destroy(): Promise<void> {\n return workerManager.destroyWorker();\n }\n}\n"],"names":["WorkerGenerator","config","workerManager","toReturn","timestamp","resolve","data","result","cb","message","severity","msg","logger","input"],"mappings":";;AAKO,MAAMA,EAAyC;AAAA,EAKlD,YAA4BC,GAAwB;AAAxB,SAAA,SAAAA,GAJpB,KAAA,8BAA0D,IAAI,GAEtE,KAAQ,UAAU,IAGd,KAAK,aAAa;AAAA,MACd,MAAM,IAAI;AAAA,QACN,KAAK,OAAO,KAAK,WAAW,SAAS,KAAK,OAAO,KAAK,WAAW;AAAA,MACrE;AAAA,MACA,mBAAmB,EAAE,MAAM,IAAI,aAAa,CAAC,GAAG,MAAM,GAAG;AAAA,MACzD,SAAS,IAAI,aAAa,CAAC;AAAA,MAC3B,QAAQ;AAAA,MACR,WAAW;AAAA,MACX,MAAM;AAAA,IACV;AAAA,EAAA;AAAA,EAGG,WAAoB;AAChB,WAAA,CAAC,C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,OAAOJ,CAAS;AAAA,MACjC,CACH,GACaF,EAAA,MAAM,CAACO,GAASC,MAAa;AACjC,cAAAC,IAAM,iCAAiCF,CAAO;AACpD,gBAAQC,GAAU;AAAA,UACd,KAAK;AACD,YAAAE,EAAO,KAAKD,CAAG;AACf;AAAA,UACJ,KAAK;AACD,YAAAC,EAAO,MAAMD,CAAG;AAChB;AAAA,UACJ;AACI,YAAAC,EAAO,IAAID,CAAG;AAAA,QAAA;AAAA,MACtB,CACH,IAGA,aACG,OAAOT,EAAc,UAAe,KAAAA,EAAc,iBAAiBD,CAAM,IACzEC,EAAc,SAAS;AAAA,QACnB,SAASD,EAAO;AAAA,QAChB,OAAOA,EAAO;AAAA,QACd,MAAMA,EAAO;AAAA,QACb,SAASA,EAAO;AAAA,QAChB,QAAQ,EAAE,MAAM,cAAc;AAAA,MAAA,CACjC;AAAA,IACF,CACN;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWL,MAAa,QAAQY,GAA0BT,GAAkC;AAC/D,IAAAF,EAAA,aAAaW,GAAOT,CAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,UAAyB;AAC5B,WAAOF,EAAc,cAAc;AAAA,EAAA;AAE3C;"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { logger as a } from "./logger.js";
|
|
2
|
+
import { resourceLoader as n } from "./resource-loader.js";
|
|
3
|
+
class l {
|
|
3
4
|
constructor() {
|
|
4
5
|
this.destroyPromise = null, this.onInitializedCallbacks = [], this.onGeneratedCallbacks = [], this.onDroppedCallbacks = [], this.onLogCallbacks = [];
|
|
5
6
|
}
|
|
@@ -18,14 +19,12 @@ class d {
|
|
|
18
19
|
* @returns A promise that resolves when the worker is initialized.
|
|
19
20
|
*/
|
|
20
21
|
async initializeWorker(e) {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
this.destroyPromise && (await this.destroyPromise, this.destroyPromise = null), this.worker && (this.destroyPromise = this.destroyWorker(), await this.destroyPromise, this.destroyPromise = null);
|
|
24
|
-
const r = await a.resolveUri(e, e.mask.workerUri), o = await (await fetch(r, { cache: "force-cache" })).text();
|
|
22
|
+
typeof Worker > "u" && a.errorAndThrow("Web workers are not supported in this environment"), this.worker && await this.destroyWorker();
|
|
23
|
+
const r = await n.resolveUri(e, e.mask.workerUri), o = await (await fetch(r, { cache: "force-cache" })).text();
|
|
25
24
|
return this.workerUrl = URL.createObjectURL(new Blob([o], { type: "text/javascript" })), this.worker = new Worker(this.workerUrl, { type: "module" }), this.worker.addEventListener("message", (t) => {
|
|
26
25
|
if (t.data.type === "log") {
|
|
27
|
-
const { message: s, severity:
|
|
28
|
-
this.onLogCallbacks.forEach((
|
|
26
|
+
const { message: s, severity: k } = t.data;
|
|
27
|
+
this.onLogCallbacks.forEach((d) => d(s, k));
|
|
29
28
|
} else t.data.status === "generated" ? this.onGeneratedCallbacks.forEach((s) => s(t.data)) : t.data.status === "dropped" ? this.onDroppedCallbacks.forEach((s) => s(t.data.timestamp)) : t.data.status === "initialized" && this.onInitializedCallbacks.forEach((s) => s());
|
|
30
29
|
}), this.worker;
|
|
31
30
|
}
|
|
@@ -36,17 +35,17 @@ class d {
|
|
|
36
35
|
* If no worker is available, it resolves immediately.
|
|
37
36
|
*/
|
|
38
37
|
destroyWorker() {
|
|
39
|
-
return new Promise((e) => {
|
|
38
|
+
return this.destroyPromise || (this.destroyPromise = new Promise((e) => {
|
|
40
39
|
const r = (i) => {
|
|
41
40
|
var o;
|
|
42
|
-
i.data.status === "destroyed" && ((o = this.worker) == null || o.removeEventListener("message", r), this.terminateWorker(), e());
|
|
41
|
+
i.data.status === "destroyed" && ((o = this.worker) == null || o.removeEventListener("message", r), this.terminateWorker(), this.destroyPromise = null, e());
|
|
43
42
|
};
|
|
44
43
|
if (!this.worker) {
|
|
45
|
-
|
|
44
|
+
a.warn("No worker to destroy"), e();
|
|
46
45
|
return;
|
|
47
46
|
}
|
|
48
47
|
this.worker.addEventListener("message", r), this.worker.postMessage({ type: "destroy" });
|
|
49
|
-
});
|
|
48
|
+
})), this.destroyPromise;
|
|
50
49
|
}
|
|
51
50
|
/**
|
|
52
51
|
* Terminate the worker.
|
|
@@ -73,7 +72,7 @@ class d {
|
|
|
73
72
|
* @returns The worker configuration.
|
|
74
73
|
*/
|
|
75
74
|
async prepareWorkerConfig(e) {
|
|
76
|
-
const r = await
|
|
75
|
+
const r = await n.resolveUri(e, e.mask.modelUri), i = await n.resolveUri(e, e.mask.workerUri), o = await n.resolveUri(e, e.wasmUri), s = { ...{
|
|
77
76
|
...e,
|
|
78
77
|
mask: { ...e.mask, modelUri: r, workerUri: i },
|
|
79
78
|
wasmUri: o
|
|
@@ -130,9 +129,7 @@ class d {
|
|
|
130
129
|
* @param config.assetUrlResolver - The function to resolve asset URLs.
|
|
131
130
|
*/
|
|
132
131
|
sendInit(e) {
|
|
133
|
-
|
|
134
|
-
throw new Error("[ladon-ts] Worker is not initialized, cannot send init");
|
|
135
|
-
this.worker.postMessage({ type: "init", config: e });
|
|
132
|
+
this.worker || a.errorAndThrow("Worker is not initialized, cannot send init"), this.worker.postMessage({ type: "init", config: e });
|
|
136
133
|
}
|
|
137
134
|
/**
|
|
138
135
|
* Send a generate message to the worker.
|
|
@@ -141,9 +138,7 @@ class d {
|
|
|
141
138
|
* @param timestamp - The timestamp of the input image.
|
|
142
139
|
*/
|
|
143
140
|
sendGenerate(e, r) {
|
|
144
|
-
|
|
145
|
-
throw new Error("[ladon-ts] Worker is not initialized, cannot send generate");
|
|
146
|
-
this.worker.postMessage(
|
|
141
|
+
this.worker || a.errorAndThrow("Worker is not initialized, cannot send generate"), this.worker.postMessage(
|
|
147
142
|
{
|
|
148
143
|
type: "generate",
|
|
149
144
|
image: e,
|
|
@@ -153,9 +148,9 @@ class d {
|
|
|
153
148
|
);
|
|
154
149
|
}
|
|
155
150
|
}
|
|
156
|
-
const
|
|
151
|
+
const p = new l();
|
|
157
152
|
export {
|
|
158
|
-
|
|
159
|
-
|
|
153
|
+
l as WorkerManager,
|
|
154
|
+
p as workerManager
|
|
160
155
|
};
|
|
161
156
|
//# sourceMappingURL=worker-manager.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-manager.js","sources":["../../../src/lib/worker-manager.ts"],"sourcesContent":["import { PipelineConfig, PreloadConfig, WorkerConfig } from './config-types';\nimport { WorkerGeneratedResult } from './generator-types';\nimport { resourceLoader } from './resource-loader';\n\n/**\n * Worker manager class to handle the initialization and termination of the segmenation\n * web worker. This class is responsible for loading the worker script, resolving the\n * configuration, and managing the worker lifecycle. It also provides methods to\n * preload the worker and terminate it when no longer needed.\n */\nexport class WorkerManager {\n private worker?: Worker;\n private workerUrl?: string;\n private destroyPromise: Promise<void> | null = null;\n\n // Event callback registries\n private onInitializedCallbacks: Array<() => void> = [];\n private onGeneratedCallbacks: Array<(data: WorkerGeneratedResult) => void> = [];\n private onDroppedCallbacks: Array<(timestamp: number) => void> = [];\n private onLogCallbacks: Array<(message: string, severity: string) => void> = [];\n\n /**\n * Get the current worker instance.\n *\n * @returns The current worker instance or undefined if not initialized.\n */\n public getWorker() {\n return this.worker;\n }\n\n /**\n * Initialize the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is initialized.\n */\n public async initializeWorker(config: WorkerConfig): Promise<Worker> {\n if (typeof Worker === 'undefined') {\n throw new Error('[ladon-ts] web workers are not supported in this environment');\n }\n\n // Wait for any ongoing destroy operation to finish\n if (this.destroyPromise) {\n await this.destroyPromise;\n this.destroyPromise = null;\n }\n\n if (this.worker) {\n this.destroyPromise = this.destroyWorker();\n await this.destroyPromise;\n this.destroyPromise = null;\n }\n\n const scriptUri = await resourceLoader.resolveUri(config, config.mask.workerUri);\n const response = await fetch(scriptUri, { cache: 'force-cache' });\n const workerSource = await response.text();\n\n this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));\n this.worker = new Worker(this.workerUrl, { type: 'module' });\n\n // Attach a single message handler for all events\n this.worker.addEventListener('message', (event: MessageEvent) => {\n if (event.data.type === 'log') {\n const { message, severity } = event.data;\n this.onLogCallbacks.forEach((cb) => cb(message, severity));\n } else if (event.data.status === 'generated') {\n this.onGeneratedCallbacks.forEach((cb) => cb(event.data));\n } else if (event.data.status === 'dropped') {\n this.onDroppedCallbacks.forEach((cb) => cb(event.data.timestamp));\n } else if (event.data.status === 'initialized') {\n this.onInitializedCallbacks.forEach((cb) => cb());\n }\n // 'destroyed' is handled in destroyWorker\n });\n\n return this.worker;\n }\n\n /**\n * Destroys the worker gracefully by sending a destroy message and waiting for confirmation.\n *\n * @returns A promise that resolves when the worker is destroyed.\n * If no worker is available, it resolves immediately.\n */\n public destroyWorker(): Promise<void> {\n return new Promise<void>((resolve) => {\n const handleMessage = (event: MessageEvent) => {\n if (event.data.status === 'destroyed') {\n this.worker?.removeEventListener('message', handleMessage);\n this.terminateWorker();\n resolve();\n }\n };\n\n if (!this.worker) {\n console.warn('[ladon-ts] No worker to destroy');\n resolve();\n return;\n }\n\n this.worker.addEventListener('message', handleMessage);\n this.worker.postMessage({ type: 'destroy' });\n });\n }\n\n /**\n * Terminate the worker.\n */\n public terminateWorker() {\n if (this.worker) {\n this.worker.terminate();\n this.worker = undefined;\n }\n if (this.workerUrl) {\n URL.revokeObjectURL(this.workerUrl);\n this.workerUrl = undefined;\n }\n }\n\n /**\n * Preload the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is preloaded.\n */\n public async preloadWorker(config: PreloadConfig) {\n const workerConfig = await this.prepareWorkerConfig(config);\n this.worker = await this.initializeWorker(workerConfig);\n this.worker.postMessage({ type: 'preload', config: workerConfig });\n }\n\n /**\n * Prepare the worker configuration by resolving the final URLs and paths to send to the\n * worker. This is necessary because we can't send functions to the worker. We also need to\n * remove the assetUrlResolver function from the configuration.\n *\n * @param config - The preload configuration.\n * @returns The worker configuration.\n */\n public async prepareWorkerConfig(config: PreloadConfig) {\n // Resolve and cache the URIs before sending the config to the worker.\n // Future calls to the resolveUri method will use the cache.\n const modelUri = await resourceLoader.resolveUri(config, config.mask.modelUri);\n const workerUri = await resourceLoader.resolveUri(config, config.mask.workerUri);\n const wasmUri = await resourceLoader.resolveUri(config, config.wasmUri);\n const resolvedConfig: PreloadConfig = {\n ...config,\n mask: { ...config.mask, modelUri, workerUri },\n wasmUri,\n };\n\n // We can't send the assetUrlResolver function to the worker so we remove it from the config.\n const workerConfig = { ...resolvedConfig, assetUrlResolver: undefined };\n\n // This is a workaround to ensure the worker configuration can be sent to the worker.\n return JSON.parse(JSON.stringify(workerConfig));\n }\n\n /**\n * Register a callback for when the worker is initialized.\n */\n public onInitialized(callback: () => void) {\n this.onInitializedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for when the worker generates output.\n *\n * @param callback - The callback function to be called with the generated data.\n * @param data - The generated data from the worker.\n * @param data.mask - The generated mask.\n * @param data.facesAndLandmarks - The detected faces and landmarks.\n * @param data.gesture - The detected gesture.\n * @param data.motion - The detected motion.\n */\n public onGenerated(callback: (data: WorkerGeneratedResult) => void) {\n this.onGeneratedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for when the worker drops a frame.\n * This is useful for handling cases where the worker cannot keep up with the input frame rate.\n * The callback will be called with the timestamp of the dropped frame.\n *\n * @param callback - The callback function to be called with the timestamp of the dropped frame.\n */\n public onDropped(callback: (timestamp: number) => void) {\n this.onDroppedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for log messages from the worker.\n *\n * @param callback - The callback function to be called with the log message and severity.\n * @param severity - The severity of the log message (e.g., 'info', 'warn', 'error').\n */\n public onLog(callback: (message: string, severity: string) => void) {\n this.onLogCallbacks.push(callback);\n }\n\n /**\n * Send an init message to the worker.\n *\n * @param config - The configuration object to initialize the worker.\n * @param config.baseUrl - The base URL for loading assets.\n * @param config.input - The input configuration for the worker.\n * @param config.mask - The mask configuration for the worker.\n * @param config.wasmUri - The URI for the WebAssembly module.\n * @param config.workerUri - The URI for the worker script.\n * @param config.assetUrlResolver - The function to resolve asset URLs.\n */\n public sendInit(config: PipelineConfig) {\n if (!this.worker) {\n throw new Error('[ladon-ts] Worker is not initialized, cannot send init');\n }\n this.worker.postMessage({ type: 'init', config });\n }\n\n /**\n * Send a generate message to the worker.\n *\n * @param input - The input image data as a Uint8ClampedArray.\n * @param timestamp - The timestamp of the input image.\n */\n public sendGenerate(input: Uint8ClampedArray, timestamp: number) {\n if (!this.worker) {\n throw new Error('[ladon-ts] Worker is not initialized, cannot send generate');\n }\n this.worker.postMessage(\n {\n type: 'generate',\n image: input,\n timestamp,\n },\n [input.buffer]\n );\n }\n}\n\n// Global instance of the shared resource manager.\nexport const workerManager = new WorkerManager();\n"],"names":["WorkerManager","config","scriptUri","resourceLoader","workerSource","event","message","severity","cb","resolve","handleMessage","_a","workerConfig","modelUri","workerUri","wasmUri","callback","input","timestamp","workerManager"],"mappings":";AAUO,MAAMA,EAAc;AAAA,EAApB,cAAA;AAGH,SAAQ,iBAAuC,MAG/C,KAAQ,yBAA4C,CAAC,GACrD,KAAQ,uBAAqE,CAAC,GAC9E,KAAQ,qBAAyD,CAAC,GAClE,KAAQ,iBAAqE,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOvE,YAAY;AACf,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShB,MAAa,iBAAiBC,GAAuC;AAC7D,QAAA,OAAO,SAAW;AACZ,YAAA,IAAI,MAAM,8DAA8D;AAIlF,IAAI,KAAK,mBACL,MAAM,KAAK,gBACX,KAAK,iBAAiB,OAGtB,KAAK,WACA,KAAA,iBAAiB,KAAK,cAAc,GACzC,MAAM,KAAK,gBACX,KAAK,iBAAiB;AAG1B,UAAMC,IAAY,MAAMC,EAAe,WAAWF,GAAQA,EAAO,KAAK,SAAS,GAE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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASlC,MAAMA,GAAuD;AAC3D,SAAA,eAAe,KAAKA,CAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc9B,SAASf,GAAwB;AAChC,QAAA,CAAC,KAAK;AACA,YAAA,IAAI,MAAM,wDAAwD;AAE5E,SAAK,OAAO,YAAY,EAAE,MAAM,QAAQ,QAAAA,GAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS7C,aAAagB,GAA0BC,GAAmB;AACzD,QAAA,CAAC,KAAK;AACA,YAAA,IAAI,MAAM,4DAA4D;AAEhF,SAAK,OAAO;AAAA,MACR;AAAA,QACI,MAAM;AAAA,QACN,OAAOD;AAAA,QACP,WAAAC;AAAA,MACJ;AAAA,MACA,CAACD,EAAM,MAAM;AAAA,IACjB;AAAA,EAAA;AAER;AAGa,MAAAE,IAAgB,IAAInB,EAAc;"}
|
|
1
|
+
{"version":3,"file":"worker-manager.js","sources":["../../../src/lib/worker-manager.ts"],"sourcesContent":["import { PipelineConfig, PreloadConfig, WorkerConfig } from './config-types';\nimport { WorkerGeneratedResult } from './generator-types';\nimport { logger } from './logger';\nimport { resourceLoader } from './resource-loader';\n\n/**\n * Worker manager class to handle the initialization and termination of the segmenation\n * web worker. This class is responsible for loading the worker script, resolving the\n * configuration, and managing the worker lifecycle. It also provides methods to\n * preload the worker and terminate it when no longer needed.\n */\nexport class WorkerManager {\n private worker?: Worker;\n private workerUrl?: string;\n private destroyPromise: Promise<void> | null = null;\n\n // Event callback registries\n private onInitializedCallbacks: Array<() => void> = [];\n private onGeneratedCallbacks: Array<(data: WorkerGeneratedResult) => void> = [];\n private onDroppedCallbacks: Array<(timestamp: number) => void> = [];\n private onLogCallbacks: Array<(message: string, severity: string) => void> = [];\n\n /**\n * Get the current worker instance.\n *\n * @returns The current worker instance or undefined if not initialized.\n */\n public getWorker() {\n return this.worker;\n }\n\n /**\n * Initialize the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is initialized.\n */\n public async initializeWorker(config: WorkerConfig): Promise<Worker> {\n if (typeof Worker === 'undefined') {\n logger.errorAndThrow('Web workers are not supported in this environment');\n }\n\n if (this.worker) {\n await this.destroyWorker();\n }\n\n const scriptUri = await resourceLoader.resolveUri(config, config.mask.workerUri);\n const response = await fetch(scriptUri, { cache: 'force-cache' });\n const workerSource = await response.text();\n\n this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));\n this.worker = new Worker(this.workerUrl, { type: 'module' });\n\n // Attach a single message handler for all events\n this.worker.addEventListener('message', (event: MessageEvent) => {\n if (event.data.type === 'log') {\n const { message, severity } = event.data;\n this.onLogCallbacks.forEach((cb) => cb(message, severity));\n } else if (event.data.status === 'generated') {\n this.onGeneratedCallbacks.forEach((cb) => cb(event.data));\n } else if (event.data.status === 'dropped') {\n this.onDroppedCallbacks.forEach((cb) => cb(event.data.timestamp));\n } else if (event.data.status === 'initialized') {\n this.onInitializedCallbacks.forEach((cb) => cb());\n }\n // 'destroyed' is handled in destroyWorker\n });\n\n return this.worker;\n }\n\n /**\n * Destroys the worker gracefully by sending a destroy message and waiting for confirmation.\n *\n * @returns A promise that resolves when the worker is destroyed.\n * If no worker is available, it resolves immediately.\n */\n public destroyWorker(): Promise<void> {\n // Wait for any ongoing destroy operation to finish\n if (!this.destroyPromise) {\n this.destroyPromise = new Promise<void>((resolve) => {\n const handleMessage = (event: MessageEvent) => {\n if (event.data.status === 'destroyed') {\n this.worker?.removeEventListener('message', handleMessage);\n this.terminateWorker();\n this.destroyPromise = null;\n resolve();\n }\n };\n\n if (!this.worker) {\n logger.warn('No worker to destroy');\n resolve();\n return;\n }\n\n this.worker.addEventListener('message', handleMessage);\n this.worker.postMessage({ type: 'destroy' });\n });\n }\n\n return this.destroyPromise;\n }\n\n /**\n * Terminate the worker.\n */\n public terminateWorker() {\n if (this.worker) {\n this.worker.terminate();\n this.worker = undefined;\n }\n if (this.workerUrl) {\n URL.revokeObjectURL(this.workerUrl);\n this.workerUrl = undefined;\n }\n }\n\n /**\n * Preload the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is preloaded.\n */\n public async preloadWorker(config: PreloadConfig) {\n const workerConfig = await this.prepareWorkerConfig(config);\n this.worker = await this.initializeWorker(workerConfig);\n this.worker.postMessage({ type: 'preload', config: workerConfig });\n }\n\n /**\n * Prepare the worker configuration by resolving the final URLs and paths to send to the\n * worker. This is necessary because we can't send functions to the worker. We also need to\n * remove the assetUrlResolver function from the configuration.\n *\n * @param config - The preload configuration.\n * @returns The worker configuration.\n */\n public async prepareWorkerConfig(config: PreloadConfig) {\n // Resolve and cache the URIs before sending the config to the worker.\n // Future calls to the resolveUri method will use the cache.\n const modelUri = await resourceLoader.resolveUri(config, config.mask.modelUri);\n const workerUri = await resourceLoader.resolveUri(config, config.mask.workerUri);\n const wasmUri = await resourceLoader.resolveUri(config, config.wasmUri);\n const resolvedConfig: PreloadConfig = {\n ...config,\n mask: { ...config.mask, modelUri, workerUri },\n wasmUri,\n };\n\n // We can't send the assetUrlResolver function to the worker so we remove it from the config.\n const workerConfig = { ...resolvedConfig, assetUrlResolver: undefined };\n\n // This is a workaround to ensure the worker configuration can be sent to the worker.\n return JSON.parse(JSON.stringify(workerConfig));\n }\n\n /**\n * Register a callback for when the worker is initialized.\n */\n public onInitialized(callback: () => void) {\n this.onInitializedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for when the worker generates output.\n *\n * @param callback - The callback function to be called with the generated data.\n * @param data - The generated data from the worker.\n * @param data.mask - The generated mask.\n * @param data.facesAndLandmarks - The detected faces and landmarks.\n * @param data.gesture - The detected gesture.\n * @param data.motion - The detected motion.\n */\n public onGenerated(callback: (data: WorkerGeneratedResult) => void) {\n this.onGeneratedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for when the worker drops a frame.\n * This is useful for handling cases where the worker cannot keep up with the input frame rate.\n * The callback will be called with the timestamp of the dropped frame.\n *\n * @param callback - The callback function to be called with the timestamp of the dropped frame.\n */\n public onDropped(callback: (timestamp: number) => void) {\n this.onDroppedCallbacks.push(callback);\n }\n\n /**\n * Register a callback for log messages from the worker.\n *\n * @param callback - The callback function to be called with the log message and severity.\n * @param severity - The severity of the log message (e.g., 'info', 'warn', 'error').\n */\n public onLog(callback: (message: string, severity: string) => void) {\n this.onLogCallbacks.push(callback);\n }\n\n /**\n * Send an init message to the worker.\n *\n * @param config - The configuration object to initialize the worker.\n * @param config.baseUrl - The base URL for loading assets.\n * @param config.input - The input configuration for the worker.\n * @param config.mask - The mask configuration for the worker.\n * @param config.wasmUri - The URI for the WebAssembly module.\n * @param config.workerUri - The URI for the worker script.\n * @param config.assetUrlResolver - The function to resolve asset URLs.\n */\n public sendInit(config: PipelineConfig) {\n if (!this.worker) {\n logger.errorAndThrow('Worker is not initialized, cannot send init');\n }\n this.worker.postMessage({ type: 'init', config });\n }\n\n /**\n * Send a generate message to the worker.\n *\n * @param input - The input image data as a Uint8ClampedArray.\n * @param timestamp - The timestamp of the input image.\n */\n public sendGenerate(input: Uint8ClampedArray, timestamp: number) {\n if (!this.worker) {\n logger.errorAndThrow('Worker is not initialized, cannot send generate');\n }\n this.worker.postMessage(\n {\n type: 'generate',\n image: input,\n timestamp,\n },\n [input.buffer]\n );\n }\n}\n\n// Global instance of the shared resource manager.\nexport const workerManager = new WorkerManager();\n"],"names":["WorkerManager","config","logger","scriptUri","resourceLoader","workerSource","event","message","severity","cb","resolve","handleMessage","_a","workerConfig","modelUri","workerUri","wasmUri","callback","input","timestamp","workerManager"],"mappings":";;AAWO,MAAMA,EAAc;AAAA,EAApB,cAAA;AAGH,SAAQ,iBAAuC,MAG/C,KAAQ,yBAA4C,CAAC,GACrD,KAAQ,uBAAqE,CAAC,GAC9E,KAAQ,qBAAyD,CAAC,GAClE,KAAQ,iBAAqE,CAAC;AA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,MAAM,KAAK,UAAUH,CAAY,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3C,cAAcI,GAAsB;AAClC,SAAA,uBAAuB,KAAKA,CAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAatC,YAAYA,GAAiD;AAC3D,SAAA,qBAAqB,KAAKA,CAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUpC,UAAUA,GAAuC;AAC/C,SAAA,mBAAmB,KAAKA,CAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASlC,MAAMA,GAAuD;AAC3D,SAAA,eAAe,KAAKA,CAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc9B,SAAShB,GAAwB;AAChC,IAAC,KAAK,UACNC,EAAO,cAAc,6CAA6C,GAEtE,KAAK,OAAO,YAAY,EAAE,MAAM,QAAQ,QAAAD,GAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAS7C,aAAaiB,GAA0BC,GAAmB;AACzD,IAAC,KAAK,UACNjB,EAAO,cAAc,iDAAiD,GAE1E,KAAK,OAAO;AAAA,MACR;AAAA,QACI,MAAM;AAAA,QACN,OAAOgB;AAAA,QACP,WAAAC;AAAA,MACJ;AAAA,MACA,CAACD,EAAM,MAAM;AAAA,IACjB;AAAA,EAAA;AAER;AAGa,MAAAE,IAAgB,IAAIpB,EAAc;"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { __module as v } from "../../../_virtual/logger2.js";
|
|
2
|
+
/*!
|
|
3
|
+
* js-logger - http://github.com/jonnyreeves/js-logger
|
|
4
|
+
* Jonny Reeves, http://jonnyreeves.co.uk/
|
|
5
|
+
* js-logger may be freely distributed under the MIT license.
|
|
6
|
+
*/
|
|
7
|
+
var R = v.exports, E;
|
|
8
|
+
function F() {
|
|
9
|
+
return E ? v.exports : (E = 1, function(d) {
|
|
10
|
+
(function(g) {
|
|
11
|
+
var n = {};
|
|
12
|
+
n.VERSION = "1.6.1";
|
|
13
|
+
var m, c = {}, f = function(e, t) {
|
|
14
|
+
return function() {
|
|
15
|
+
return t.apply(e, arguments);
|
|
16
|
+
};
|
|
17
|
+
}, h = function() {
|
|
18
|
+
var e = arguments, t = e[0], a, o;
|
|
19
|
+
for (o = 1; o < e.length; o++)
|
|
20
|
+
for (a in e[o])
|
|
21
|
+
!(a in t) && e[o].hasOwnProperty(a) && (t[a] = e[o][a]);
|
|
22
|
+
return t;
|
|
23
|
+
}, u = function(e, t) {
|
|
24
|
+
return { value: e, name: t };
|
|
25
|
+
};
|
|
26
|
+
n.TRACE = u(1, "TRACE"), n.DEBUG = u(2, "DEBUG"), n.INFO = u(3, "INFO"), n.TIME = u(4, "TIME"), n.WARN = u(5, "WARN"), n.ERROR = u(8, "ERROR"), n.OFF = u(99, "OFF");
|
|
27
|
+
var L = function(e) {
|
|
28
|
+
this.context = e, this.setLevel(e.filterLevel), this.log = this.info;
|
|
29
|
+
};
|
|
30
|
+
L.prototype = {
|
|
31
|
+
// Changes the current logging level for the logging instance.
|
|
32
|
+
setLevel: function(e) {
|
|
33
|
+
e && "value" in e && (this.context.filterLevel = e);
|
|
34
|
+
},
|
|
35
|
+
// Gets the current logging level for the logging instance
|
|
36
|
+
getLevel: function() {
|
|
37
|
+
return this.context.filterLevel;
|
|
38
|
+
},
|
|
39
|
+
// Is the logger configured to output messages at the supplied level?
|
|
40
|
+
enabledFor: function(e) {
|
|
41
|
+
var t = this.context.filterLevel;
|
|
42
|
+
return e.value >= t.value;
|
|
43
|
+
},
|
|
44
|
+
trace: function() {
|
|
45
|
+
this.invoke(n.TRACE, arguments);
|
|
46
|
+
},
|
|
47
|
+
debug: function() {
|
|
48
|
+
this.invoke(n.DEBUG, arguments);
|
|
49
|
+
},
|
|
50
|
+
info: function() {
|
|
51
|
+
this.invoke(n.INFO, arguments);
|
|
52
|
+
},
|
|
53
|
+
warn: function() {
|
|
54
|
+
this.invoke(n.WARN, arguments);
|
|
55
|
+
},
|
|
56
|
+
error: function() {
|
|
57
|
+
this.invoke(n.ERROR, arguments);
|
|
58
|
+
},
|
|
59
|
+
time: function(e) {
|
|
60
|
+
typeof e == "string" && e.length > 0 && this.invoke(n.TIME, [e, "start"]);
|
|
61
|
+
},
|
|
62
|
+
timeEnd: function(e) {
|
|
63
|
+
typeof e == "string" && e.length > 0 && this.invoke(n.TIME, [e, "end"]);
|
|
64
|
+
},
|
|
65
|
+
// Invokes the logger callback if it's not being filtered.
|
|
66
|
+
invoke: function(e, t) {
|
|
67
|
+
m && this.enabledFor(e) && m(t, h({ level: e }, this.context));
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
var r = new L({ filterLevel: n.OFF });
|
|
71
|
+
(function() {
|
|
72
|
+
var e = n;
|
|
73
|
+
e.enabledFor = f(r, r.enabledFor), e.trace = f(r, r.trace), e.debug = f(r, r.debug), e.time = f(r, r.time), e.timeEnd = f(r, r.timeEnd), e.info = f(r, r.info), e.warn = f(r, r.warn), e.error = f(r, r.error), e.log = e.info;
|
|
74
|
+
})(), n.setHandler = function(e) {
|
|
75
|
+
m = e;
|
|
76
|
+
}, n.setLevel = function(e) {
|
|
77
|
+
r.setLevel(e);
|
|
78
|
+
for (var t in c)
|
|
79
|
+
c.hasOwnProperty(t) && c[t].setLevel(e);
|
|
80
|
+
}, n.getLevel = function() {
|
|
81
|
+
return r.getLevel();
|
|
82
|
+
}, n.get = function(e) {
|
|
83
|
+
return c[e] || (c[e] = new L(h({ name: e }, r.context)));
|
|
84
|
+
}, n.createDefaultHandler = function(e) {
|
|
85
|
+
e = e || {}, e.formatter = e.formatter || function(i, l) {
|
|
86
|
+
l.name && i.unshift("[" + l.name + "]");
|
|
87
|
+
};
|
|
88
|
+
var t = {}, a = function(o, i) {
|
|
89
|
+
Function.prototype.apply.call(o, console, i);
|
|
90
|
+
};
|
|
91
|
+
return typeof console > "u" ? function() {
|
|
92
|
+
} : function(o, i) {
|
|
93
|
+
o = Array.prototype.slice.call(o);
|
|
94
|
+
var l = console.log, s;
|
|
95
|
+
i.level === n.TIME ? (s = (i.name ? "[" + i.name + "] " : "") + o[0], o[1] === "start" ? console.time ? console.time(s) : t[s] = (/* @__PURE__ */ new Date()).getTime() : console.timeEnd ? console.timeEnd(s) : a(l, [s + ": " + ((/* @__PURE__ */ new Date()).getTime() - t[s]) + "ms"])) : (i.level === n.WARN && console.warn ? l = console.warn : i.level === n.ERROR && console.error ? l = console.error : i.level === n.INFO && console.info ? l = console.info : i.level === n.DEBUG && console.debug ? l = console.debug : i.level === n.TRACE && console.trace && (l = console.trace), e.formatter(o, i), a(l, o));
|
|
96
|
+
};
|
|
97
|
+
}, n.useDefaults = function(e) {
|
|
98
|
+
n.setLevel(e && e.defaultLevel || n.DEBUG), n.setHandler(n.createDefaultHandler(e));
|
|
99
|
+
}, n.setDefaults = n.useDefaults, d.exports ? d.exports = n : (n._prevLogger = g.Logger, n.noConflict = function() {
|
|
100
|
+
return g.Logger = n._prevLogger, n;
|
|
101
|
+
}, g.Logger = n);
|
|
102
|
+
})(R);
|
|
103
|
+
}(v), v.exports);
|
|
104
|
+
}
|
|
105
|
+
export {
|
|
106
|
+
F as __require
|
|
107
|
+
};
|
|
108
|
+
//# sourceMappingURL=logger.js.map
|