callable-lipsync 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/js/index.js +1 -1
- package/js/talkinghead.d.ts +2 -0
- package/js/talkinghead.js +11 -9
- package/js/web-inline.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -309,7 +309,7 @@ const lip = await LipSyncNode.create(ctx);
|
|
|
309
309
|
const release = driveTalkingHead(head, lip); // head.speakAudio(...) and its streams (and its TTS, with ttsEndpoint set) now animate through the model
|
|
310
310
|
```
|
|
311
311
|
|
|
312
|
-
Make the AudioContext at the sample rate of what you stream to TalkingHead (or resample it first): a shared context does not resample its streams. With the default 0.16 s of audio ahead the lips are complete but head turns are not timed to the words; `LipSyncNode.create(ctx, { ahead: 0.64 })` times them, for a longer delay.
|
|
312
|
+
Make the AudioContext at the sample rate of what you stream to TalkingHead (or resample it first): a shared context does not resample its streams. With the default 0.16 s of audio ahead the lips are complete but head turns are not timed to the words; `LipSyncNode.create(ctx, { ahead: 0.64 })` times them, for a longer delay. Rigs differ in how far a shape goes: `driveTalkingHead(head, lip, { shapes: { cheekPuff: 0.3 } })` scales one down (the avatar page does that for its avatar, whose cheekPuff is a full balloon).
|
|
313
313
|
|
|
314
314
|
**Any three.js avatar with ARKit blend shapes** (the 52 named shapes many web avatars carry):
|
|
315
315
|
|
package/js/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import { Engine } from './engine.js';
|
|
|
8
8
|
export { Engine };
|
|
9
9
|
export { Arkit } from './arkit.js';
|
|
10
10
|
|
|
11
|
-
export const VERSION = '0.3.
|
|
11
|
+
export const VERSION = '0.3.1'; // this package's version (kept equal to package.json's by the tests)
|
|
12
12
|
export const SAMPLE_RATE = 16000, FPS = 25, FRAME = 640;
|
|
13
13
|
// what the 118 numbers of a frame are: [first, one past the last]. Rotations are axis-angle, in radians.
|
|
14
14
|
export const LAYOUT = { expression: [0, 100], chest: [100, 103], jaw: [103, 106], neck: [106, 109], leftEye: [109, 112], rightEye: [112, 115], travel: [115, 118] };
|
package/js/talkinghead.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface DriveOptions {
|
|
|
8
8
|
eyes?: boolean;
|
|
9
9
|
/** How far the face and head move (default 1). */
|
|
10
10
|
gain?: number;
|
|
11
|
+
/** Each blend shape's own gain on top of `gain`, e.g. { cheekPuff: 0.3 } (rigs differ in how far a shape goes); not the blinks and gaze, which stay as the model has them. */
|
|
12
|
+
shapes?: Record<string, number>;
|
|
11
13
|
}
|
|
12
14
|
/** Drive a TalkingHead avatar (its ARKit blend shapes, head and body) from the node. Returns a function that gives it back. */
|
|
13
15
|
export declare function driveTalkingHead(head: unknown, lip: LipSyncNode, options?: DriveOptions): () => void;
|
package/js/talkinghead.js
CHANGED
|
@@ -26,9 +26,10 @@
|
|
|
26
26
|
|
|
27
27
|
// TalkingHead's head and body turns, from the frame's neck and chest rotations (radians; small, so axis-angle = Euler)
|
|
28
28
|
const HEAD = [['headRotateX', 106], ['headRotateY', 107], ['headRotateZ', 108]], BODY = [['bodyRotateX', 100], ['bodyRotateY', 101], ['bodyRotateZ', 102]];
|
|
29
|
-
// TalkingHead turns the spine by a share of bodyRotate (x: 1/2 + 1/8 + 1/24, y: 1/2 + 1/2 + 1/4, z: 1/12 + 1/12 + 1/24)
|
|
30
|
-
// head bone by headRotate + bodyRotate.
|
|
31
|
-
//
|
|
29
|
+
// TalkingHead turns the spine by a share of bodyRotate (x: 1/2 + 1/8 + 1/24, y: 1/2 + 1/2 + 1/4, z: 1/12 + 1/12 + 1/24), from
|
|
30
|
+
// the hips up, and the head bone by headRotate + bodyRotate. bodyRotate is the model's chest as it is (divided by the share,
|
|
31
|
+
// a sideways lean of the chest became a 5x larger one from the hips that slid the head out of the picture), and
|
|
32
|
+
// headRotate = chest + neck - (1 + share) * bodyRotate turns the head to chest + neck, as in the model.
|
|
32
33
|
const SHARE = [1 / 2 + 1 / 8 + 1 / 24, 1 / 2 + 1 / 2 + 1 / 4, 1 / 12 + 1 / 12 + 1 / 24];
|
|
33
34
|
// its own shapes that would add to ours: the mouth mixes and the visemes always, the eye mixes while the model has the eyes
|
|
34
35
|
const QUIET = ['mouthOpen', 'mouthSmile', 'viseme_sil', 'viseme_PP', 'viseme_FF', 'viseme_TH', 'viseme_DD', 'viseme_kk', 'viseme_CH', 'viseme_SS', 'viseme_nn', 'viseme_RR', 'viseme_aa', 'viseme_E', 'viseme_I', 'viseme_O', 'viseme_U'];
|
|
@@ -41,8 +42,9 @@ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
|
41
42
|
|
|
42
43
|
// options: audio (default true: route TalkingHead's speech and stream through the node), head (default true: the head and
|
|
43
44
|
// body turns), eyes (default true: blinks and gaze from the model, with tiny; false leaves them to TalkingHead), gain
|
|
44
|
-
// (default 1: how far the face and head move)
|
|
45
|
-
|
|
45
|
+
// (default 1: how far the face and head move), shapes (each blend shape's own gain on top, e.g. { cheekPuff: 0.3 }: rigs
|
|
46
|
+
// differ in how far a shape goes; gain and shapes leave the blinks and gaze as they are). Returns a function that gives the avatar back to TalkingHead.
|
|
47
|
+
export function driveTalkingHead(head, lip, { audio = true, head: turns = true, eyes = true, gain = 1, shapes = {} } = {}) {
|
|
46
48
|
if (!head || !head.opt) throw new Error('callable-lipsync: driveTalkingHead needs a TalkingHead'); // before showAvatar too: the avatar is picked up when it comes
|
|
47
49
|
if (audio && (head.audioCtx !== lip.ctx || head.opt.audioCtx !== lip.ctx)) throw new Error('callable-lipsync: make one AudioContext and give it to both: new TalkingHead(el, { audioCtx: ctx }) and LipSyncNode.create(ctx) (or pass { audio: false })');
|
|
48
50
|
let mt = null, set = null, names = null, eyesOn = null, active = false, outTo = null, warned = false, bare = false, released = false;
|
|
@@ -70,7 +72,7 @@ export function driveTalkingHead(head, lip, { audio = true, head: turns = true,
|
|
|
70
72
|
}
|
|
71
73
|
function build() { // what we set on the avatar now shown
|
|
72
74
|
const get = (list) => list.map((n) => mt[n]).filter(Boolean);
|
|
73
|
-
set = { shapes: (names || []).map((n, i) => [mt[n], i, isEye(n)]).filter(([m]) => m), quiet: get(QUIET), quietEyes: get(QUIET_EYES),
|
|
75
|
+
set = { shapes: (names || []).map((n, i) => [mt[n], i, isEye(n), gain * (shapes[n] ?? 1)]).filter(([m]) => m), quiet: get(QUIET), quietEyes: get(QUIET_EYES),
|
|
74
76
|
rot: turns ? [...HEAD, ...BODY].filter(([n]) => mt[n]).map(([n, k]) => [mt[n], k, BODY.some(([b]) => b === n)]) : [] };
|
|
75
77
|
}
|
|
76
78
|
function bind() { // (again) for the avatar now shown: its morph targets, and the shape names the node knows
|
|
@@ -113,14 +115,14 @@ export function driveTalkingHead(head, lip, { audio = true, head: turns = true,
|
|
|
113
115
|
if (!w || !f) return; // a new stream's first frames are on their way: the last pose holds
|
|
114
116
|
if (lip.names && !set.shapes.length && !bare) { bare = true; console.warn('callable-lipsync: this avatar has none of the ARKit blend shapes: only its head turns follow the model'); }
|
|
115
117
|
const nano = lip.model === 'nano'; eyesTo(eyes && !nano);
|
|
116
|
-
for (const [m, i, eye] of set.shapes) { if (eye && !eyesOn) continue; m.realtime = eye ? w[i] : Math.min(1,
|
|
118
|
+
for (const [m, i, eye, g] of set.shapes) { if (eye && !eyesOn) continue; m.realtime = eye ? w[i] : Math.min(1, g * w[i]); m.needsUpdate = true; }
|
|
117
119
|
for (const m of set.quiet) { m.realtime = 0; m.needsUpdate = true; }
|
|
118
120
|
if (eyesOn) for (const m of set.quietEyes) { m.realtime = 0; m.needsUpdate = true; }
|
|
119
121
|
const withBody = !nano && set.rot.some(([, , body]) => body), clamp = (x) => Math.max(-1, Math.min(1, x));
|
|
120
122
|
for (const [m, k, body] of set.rot) {
|
|
121
123
|
if (body && nano) { if (m.realtime !== null) { m.realtime = null; m.base = 0; m.needsUpdate = true; } continue; }
|
|
122
|
-
const torso = (i) => clamp(gain * f[100 + i]
|
|
123
|
-
m.realtime = body ? torso(k - 100) : withBody ? gain * f[k] - torso(k - 106) : gain * f[k]; m.needsUpdate = true;
|
|
124
|
+
const torso = (i) => clamp(gain * f[100 + i]); // bodyRotate for axis i
|
|
125
|
+
m.realtime = body ? torso(k - 100) : withBody ? gain * (f[100 + k - 106] + f[k]) - (1 + SHARE[k - 106]) * torso(k - 106) : gain * f[k]; m.needsUpdate = true;
|
|
124
126
|
}
|
|
125
127
|
active = true;
|
|
126
128
|
};
|
package/js/web-inline.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Generated by scripts/build_web.mjs from web-worker.js (with the modules it imports) and web-capture.js: do not edit.
|
|
2
|
-
export const WORKER = "// Generated by scripts/build_web.mjs from the files in js/: do not edit.\nconst __m = {};\n__m['engine'] = (() => {\n// callable-lipsync as a stream: 16 kHz audio in, FLAME 2023 Open frames out at 25 fps\n// (118 numbers: 100 expression, 3 chest rotation, 3 jaw, 3 neck, 6 eyes, 3 travel in m).\n// Runs the model's ONNX graphs with onnxruntime (web or node); works in a page, a worker or Node.\n//\n// Audio ahead of a frame: the lips use `wait` frames of it (4 = 0.16 s, the model's full view; fewer: silence stands\n// in for the rest), the head `known` frames more past that (12 = 0.64 s in all; 8, 4, 0; -4 with wait 0 = none).\n// `quiet` (default on): after 0.4 s without sound the mouth is eased to the model's closed pose (meta.closed), and released as sound returns.\n// `floor`: the level of a faint noise added to the audio (1e-4 = -80 dB; 0 = none), so that long digital silence reads as a quiet room.\n// Every block of the network keeps its past outputs, so a new 40 ms of audio costs one frame of each block.\nconst FRAME = 640, LOUD = 1e-5, HOLD = 10; // samples a frame; the mean square of a frame with sound in it (-50 dB); frames after the last sound before the mouth is eased shut\nfunction rng(seed) { let a = seed >>> 0; return () => { a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }\n\nclass Engine {\n static async create(ort, load, options = {}) {\n const e = new Engine(); e.ort = ort; e.meta = JSON.parse(new TextDecoder().decode(await load('meta.json'))); e.s = {}; e.bytes = 0;\n for (const n of e.meta.graphs) { const b = await load(n + '.onnx'); e.bytes += b.byteLength; e.s[n] = await ort.InferenceSession.create(new Uint8Array(b), options.session || {}); }\n e.nano = e.meta.kind === 'nano'; // the small model: face, jaw and the head's rotation straight from the audio; no draws, no chest, eyes or blinks; always 0.16 s of audio ahead\n if (!e.nano) { const tb = await load('tables.bin'), T = e.meta.tables; e.dig = new Float32Array(tb, T.dig.offset, T.dig.shape[0] * T.dig.shape[1]); e.template = new Float32Array(tb, T.template.offset, T.template.shape[0] * T.template.shape[1]); }\n e.layers = []; let src = 'e'; e.meta.trunk.forEach((b, i) => { e.layers.push({ name: 't' + i, src, ...b }); src = 't' + i; }); e.hName = src; e.meta.slow.forEach((b, i) => { e.layers.push({ name: 's' + i, src, ...b }); src = 's' + i; }); e.sName = src;\n e.zero = new Float32Array(e.meta.width); e.reset({}); return e;\n }\n reset({ known = 12, wait = 4, guide = 2, temp = 1, blinkTemp = 1, smooth = 0.75, seed = 1, hop = null, record = false, floor = 1e-4, quiet = true } = {}) {\n const m = this.meta; if (this.nano) { wait = m.future; known = 0; hop = 1; } Object.assign(this, { known, wait, guide, temp, blinkTemp, smooth, record, floor, quiet }); this.en = []; this.en0 = 0; this.enAcc = 0; this.enN = 0; this.lastLoud = -1e9; this.gate = 0; this.hiss = rng(0x5bd1e995); // the noise floor is the same on every run: the lips do not depend on the seed\n this.hop = hop || (wait === m.future && known >= m.stride ? m.stride : 1); this.rand = rng(seed); this.blinkRand = rng(seed ^ 0x9e3779b9); // blinks draw from their own sequence, so the motion does not depend on how the audio was cut into chunks\n this.audio = new Float32Array(1 << 16); this.a0 = 0; this.an = 0; // samples [a0, an) are held\n this.col = { e: [] }; this.n = { e: 0 }; for (const l of this.layers) { this.col[l.name] = []; this.n[l.name] = 0; } // each block's outputs per frame, final up to n\n this.naux = 0; this.aux = []; this.nface = 0; this.face = [];\n if (!this.nano) { this.ha = new Float32Array(2 * m.ahid); this.hb = new Float32Array(2 * m.ahid); this.hx = new Float32Array(4 * m.hid); } this.blinkLast = 0; this.blinkStart = -1;\n this.nb = 0; this.q = []; this.pose = []; this.y1 = null; this.y2 = null; this.out = 0;\n this.ms = { lips: 0, heads: 0, tokens: 0, frames: 0, calls: 0 }; this.log = { digits: [], probs: [], blinks: [], face: [] };\n }\n push(x) {\n if (this.an - this.a0 + x.length > this.audio.length) { const from = Math.max(this.a0, this.an - 16 * FRAME); let n = this.audio.length; while (n < this.an - from + x.length) n *= 2; const b = new Float32Array(n); b.set(this.audio.subarray(from - this.a0, this.an - this.a0)); this.audio = b; this.a0 = from; }\n const o = this.an - this.a0, a = this.audio, g = 2 * this.floor, r = this.hiss; this.an += x.length;\n for (let i = 0; i < x.length; i++) { this.enAcc += x[i] * x[i]; if (++this.enN === FRAME) { this.en.push(this.enAcc / FRAME > LOUD); this.enAcc = 0; this.enN = 0; } } // per frame: is there sound (over -50 dB); en[k - en0] is frame k's\n if (this.en.length > 4096) { const cut = Math.min(this.en.length - 1024, (this.nano ? this.out : this.nface) - HOLD - 1 - this.en0); if (cut > 0) { this.en.splice(0, cut); this.en0 += cut; } } // a long stream: drop what the silence gate no longer reads\n if (g) for (let i = 0; i < x.length; i++) a[o + i] = x[i] + g * (r() + r() + r() - 1.5); else a.set(x, o); // a noise floor (-80 dB): exact digital silence is something the model never heard, and after 2.5 s of it the lips drift open\n }\n t(data, dims) { return new this.ort.Tensor('float32', data, dims); }\n async run(name, feeds) { this.ms.calls++; return this.s[name].run(feeds); }\n window(f0, f1, end) { // audio of frames [f0, f1), zeros before the stream and from sample `end` on\n const x = new Float32Array((f1 - f0) * FRAME), a = Math.max(f0 * FRAME, this.a0, 0), b = Math.min(f1 * FRAME, end, this.an); if (b > a) x.set(this.audio.subarray(a - this.a0, b - this.a0), a - f0 * FRAME); return x;\n }\n async fe(f0, f1, end) { // the vectors into the trunk for frames [f0, f1) -> rows\n const w = this.meta.width, x = this.window(f0 - 2, f1, end), r = (await this.run('fe', { audio: this.t(x, [1, x.length]) })).e.data, o = []; for (let i = f0; i < f1; i++) o.push(r.slice((i - f0 + 2) * w, (i - f0 + 3) * w)); return o;\n }\n async blockCols(l, frames, get) { // block l at `frames` from its input's columns\n const w = this.meta.width, N = frames.length, x = new Float32Array(N * w * 3);\n for (let i = 0; i < N; i++) { const t = frames[i], taps = l.ahead ? [t - l.d, t, t + l.d] : [t - 2 * l.d, t - l.d, t]; for (let k = 0; k < 3; k++) { const c = await get(l.src, taps[k]); for (let j = 0; j < w; j++) x[(i * w + j) * 3 + k] = c[j]; } }\n const y = (await this.run(l.name, { x: this.t(x, [N, w, 3]) })).y.data, o = []; for (let i = 0; i < N; i++) o.push(y.slice(i * w, (i + 1) * w)); return o;\n }\n async final(nE) { // everything the audio up to frame nE (exclusive) settles for good\n if (nE > this.n.e) { (await this.fe(this.n.e, nE, nE * FRAME)).forEach((c, i) => { this.col.e[this.n.e + i] = c; }); this.n.e = nE; }\n const get = async (name, t) => (t < 0 ? this.zero : this.col[name][t]);\n for (const l of this.layers) { const lim = this.n[l.src] - (l.ahead ? l.d : 0); if (lim > this.n[l.name]) { const fr = []; for (let t = this.n[l.name]; t < lim; t++) fr.push(t); (await this.blockCols(l, fr, get)).forEach((c, i) => { this.col[l.name][fr[i]] = c; }); this.n[l.name] = lim; } }\n }\n async spec(f) { // frame f's features [h, s] from audio up to frame f + wait only, silence after it\n const nE = f + this.wait + 1, lim = { e: nE }, sc = { e: [] }; for (const l of this.layers) { lim[l.name] = lim[l.src] - (l.ahead ? l.d : 0); sc[l.name] = []; }\n (await this.fe(nE, f + this.meta.future + 1, nE * FRAME)).forEach((c, i) => { sc.e[nE + i] = c; });\n const get = async (name, t) => { if (t < 0) return this.zero; if (t < lim[name]) return this.col[name][t]; if (!sc[name][t]) sc[name][t] = (await this.blockCols(this.layers.find(l => l.name === name), [t], get))[0]; return sc[name][t]; };\n return [await get(this.hName, f), await get(this.sName, f)];\n }\n async faces(H) { // output frames [nface, nface + H): face, upper face, blinks\n const m = this.meta, w = m.width, hs = new Float32Array(H * w), fh = new Float32Array(2 * w * H);\n for (let i = 0; i < H; i++) { const t = this.nface + i, [h, s] = this.wait === m.future ? [this.col[this.hName][t], this.col[this.sName][t]] : await this.spec(t); hs.set(h, i * w); for (let c = 0; c < w; c++) { fh[c * H + i] = h[c]; fh[(w + c) * H + i] = s[c]; } }\n const fc = new Float32Array((await this.run('face', { h: this.t(hs, [H, w]) })).face.data), closed = this.meta.closed;\n for (let i = 0; i < H; i++) { // no sound for a while (as far as this frame may hear): the mouth eases to the model's own closed pose. Left alone it drifts half open in long silences\n const tt = this.nface + i, upto = Math.min(this.en0 + this.en.length - 1, tt + this.wait); for (let k = Math.max(this.en0, tt - HOLD); k <= upto; k++) if (this.en[k - this.en0]) this.lastLoud = Math.max(this.lastLoud, k);\n const silent = this.lastLoud < tt - HOLD; this.gate = silent ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; const gt = this.quiet && closed ? this.gate : 0;\n if (this.record) this.log.face.push(Array.from(fc.subarray(i * 101, i * 101 + 101)));\n if (gt > 1e-3) for (let c = 0; c < 101; c++) fc[i * 101 + c] += gt * (closed[c] - fc[i * 101 + c]);\n }\n const hd = await this.run('head', { f: this.t(fh, [1, 2 * w, H]) }), B = m.blink, Z = m.Z, z = new Float32Array(hd.z.data);\n for (let i = 0; i < H; i++) {\n const tt = this.nface + i, bucket = Math.min(Math.floor((tt - this.blinkLast) / 5), B.since - 1), p = 1 / (1 + Math.exp(-hd.blink.data[i * B.since + bucket] / this.blinkTemp));\n if ((tt - this.blinkLast >= B.gap || this.blinkStart < 0) && this.blinkRand() < p) { this.blinkStart = tt; this.blinkLast = tt + 1; if (this.record) this.log.blinks.push(tt); }\n if (this.blinkStart >= 0 && tt - this.blinkStart < B.len) for (let k = 0; k < Z; k++) z[i * Z + k] += this.template[(tt - this.blinkStart) * Z + k];\n }\n const o = await this.run('open', { face: this.t(fc, [H, 101]), z: this.t(z, [H, Z]) });\n for (let i = 0; i < H; i++) this.face[this.nface + i] = { expr: o.expr.data.slice(i * 100, i * 100 + 100), jaw: o.jaw.data.slice(i * 3, i * 3 + 3) };\n this.nface += H;\n }\n async sides() { // what the audio sides say for the frames whose features are final\n const m = this.meta, w = m.width, a = this.naux, b = this.n[this.sName], H = b - a, fw = new Float32Array(2 * w * (H + 4)); // their first convolution reads 4 frames back (zeros before the stream)\n for (let i = 0; i < H + 4; i++) { const t = a - 4 + i; if (t < 0) continue; const h = this.col[this.hName][t], s = this.col[this.sName][t]; for (let c = 0; c < w; c++) { fw[c * (H + 4) + i] = h[c]; fw[(w + c) * (H + 4) + i] = s[c]; } }\n const au = await this.run('aud', { f: this.t(fw, [1, 2 * w, H + 4]), ha: this.t(this.ha, [2, 1, m.ahid]), hb: this.t(this.hb, [2, 1, m.ahid]) }); this.ha = au.ha2.data; this.hb = au.hb2.data;\n for (let i = 0; i < H; i++) this.aux[a + i] = au.aux.data.slice(i * 34, i * 34 + 34); this.naux = b;\n }\n async block() { // the pose of frames [nb * stride, (nb + 1) * stride)\n const m = this.meta, S = m.stride, K = S + m.look, i0 = this.nb * S, v = new Float32Array(35 * K);\n for (let k = 0; k < K; k++) { if (k - S >= this.known) continue; v[34 * K + k] = 1; const a = this.aux[i0 - S + k]; if (a) for (let c = 0; c < 34; c++) v[c * K + k] = a[c]; }\n const bank = Math.min(Math.max(Math.floor((m.look - this.known + 3) / 4), 0), m.bank - 1), c = (await this.run('ctx', { v: this.t(v, [1, 35 * K]) })).c.data.slice(bank * m.hid, (bank + 1) * m.hid);\n const D = m.dim, n = this.q.length, q1 = n ? this.q[n - 1] : new Float32Array(D), q2 = n > 1 ? this.q[n - 2] : q1;\n const g = await this.run('gru', { c: this.t(c, [1, m.hid]), q1: this.t(q1, [1, D]), q2: this.t(q2, [1, D]), first: this.t(new Float32Array([n ? 0 : 1]), [1]), hx: this.t(this.hx, [2, 2, m.hid]) });\n this.hx = g.hx2.data; const h = new Float32Array(g.h.data), q = new Float32Array(D), dg = [], pr = [];\n for (let d = 0; d < D; d++) {\n const p = (await this.run('digit', { h: this.t(h, [2, m.hid]), d: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(d)]), []), guide: this.t(new Float32Array([this.guide]), []), temp: this.t(new Float32Array([this.temp]), []) })).p.data;\n let u = this.rand(), t = 0, acc = 0; for (; t < m.levels[d] - 1; t++) { acc += p[t]; if (u < acc) break; }\n const row = (d * m.Lm + t) * m.hid; for (let k = 0; k < m.hid; k++) { h[k] += this.dig[row + k]; h[m.hid + k] += this.dig[row + k]; }\n q[d] = (t - m.half[d]) / m.half[d]; if (this.record) { dg.push(t); pr.push(Array.from(p)); }\n }\n if (this.record) { this.log.digits.push(dg); this.log.probs.push(pr); }\n this.q.push(q); if (this.q.length > m.dec_blocks) this.q.shift(); const N = this.q.length, qw = new Float32Array(N * D); this.q.forEach((x, j) => qw.set(x, j * D));\n const pose = (await this.run('vqdec', { q: this.t(qw, [1, N, D]) })).pose.data, body = [0, 1, 2, 12, 13, 14];\n for (let j = 0; j < S; j++) {\n const p = pose.slice(j * 15, j * 15 + 15);\n if (this.smooth < 1) { if (!this.y1) { this.y1 = body.map(b => p[b]); this.y2 = this.y1.slice(); } body.forEach((b, k) => { this.y1[k] += this.smooth * (p[b] - this.y1[k]); this.y2[k] += this.smooth * (this.y1[k] - this.y2[k]); p[b] = this.y2[k]; }); }\n this.pose[i0 + j] = p;\n }\n this.nb++;\n }\n mute(tt) { // the silence gate's value for frame tt (frames in order)\n const upto = Math.min(this.en0 + this.en.length - 1, tt + this.wait); for (let k = Math.max(this.en0, tt - HOLD); k <= upto; k++) if (this.en[k - this.en0]) this.lastLoud = Math.max(this.lastLoud, k);\n this.gate = this.lastLoud < tt - HOLD ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; return this.quiet && this.meta.closed ? this.gate : 0;\n }\n async stepNano() {\n const m = this.meta, w = m.width, done = [], have = Math.floor(this.an / FRAME), t0 = performance.now(); if (have > this.n.e) await this.final(have);\n for (let lim = Math.min(this.n[this.hName], this.n[this.sName]); this.out < lim;) {\n const H = Math.min(8, lim - this.out), h = new Float32Array(H * w), s = new Float32Array(H * w); for (let i = 0; i < H; i++) { h.set(this.col[this.hName][this.out + i], i * w); s.set(this.col[this.sName][this.out + i], i * w); }\n const o = await this.run('out', { h: this.t(h, [H, w]), s: this.t(s, [H, w]) }), closed = m.closed;\n for (let i = 0; i < H; i++) {\n const d = new Float32Array(118), fc = new Float32Array(103); fc.set(o.expr.data.subarray(i * 100, i * 100 + 100)); fc.set(o.jaw.data.subarray(i * 3, i * 3 + 3), 100); if (this.record) this.log.face.push(Array.from(fc));\n const gt = this.mute(this.out); if (gt > 1e-3) for (let c = 0; c < 103; c++) fc[c] += gt * (closed[c] - fc[c]);\n d.set(fc.subarray(0, 100)); d.set(fc.subarray(100, 103), 103); d.set(o.rot.data.subarray(i * 3, i * 3 + 3), 106); // the head's rotation goes on the neck\n done.push({ index: this.out, data: d }); const old = this.out - 160; if (old >= 0) for (const k in this.col) delete this.col[k][old]; this.out++; this.ms.frames++;\n }\n }\n this.ms.lips += performance.now() - t0; return done;\n }\n // Runs whatever the audio pushed so far allows; returns the new frames [{index, data}] in order.\n async step() {\n if (this.nano) return this.stepNano();\n const m = this.meta, S = m.stride, done = [], have = Math.floor(this.an / FRAME); let t0 = performance.now();\n const nE = this.hop > 1 ? Math.floor((have - m.future) / this.hop) * this.hop + m.future : have;\n if (nE > this.n.e) await this.final(nE);\n const H = Math.min(nE - this.wait, this.wait === m.future ? this.n[this.sName] : 1e9) - this.nface; if (H > 0) for (let i = 0; i < H; i += 8) await this.faces(Math.min(8, H - i));\n this.ms.lips += performance.now() - t0; t0 = performance.now();\n if (this.n[this.sName] > this.naux) await this.sides();\n this.ms.heads += performance.now() - t0; t0 = performance.now();\n while (this.nb * S < this.nface && this.naux >= this.nb * S + this.known) await this.block();\n this.ms.tokens += performance.now() - t0;\n while (this.out < this.nface && this.out < this.nb * S) {\n const fr = this.face[this.out], p = this.pose[this.out], d = new Float32Array(118); d.set(fr.expr); d.set(p.subarray(0, 3), 100); d.set(fr.jaw, 103); d.set(p.subarray(3, 15), 106);\n done.push({ index: this.out, data: d }); delete this.face[this.out]; delete this.pose[this.out]; const old = this.out - 160; if (old >= 0) { delete this.aux[old]; for (const k in this.col) delete this.col[k][old]; } this.out++; this.ms.frames++;\n }\n return done;\n }\n}\n\nreturn { Engine };\n})();\n__m['arkit'] = (() => {\n// Frames as ARKit blendshape weights.\n//\n// import { LipSync, Arkit } from 'callable-lipsync';\n// const arkit = await Arkit.load({ model: 'tiny', base: '/models/arkit/' }); // in Node, leave `base` out\n// const weights = arkit.convert(frame); // Float32Array(51), each 0..1, in the order of arkit.names\n//\n// The 51 ARKit shapes are displacements of the FLAME head's vertices, so a frame's weights are the mix of them closest\n// to how far the frame's face is from the model's resting face. jawOpen comes straight from the jaw's rotation and the\n// eight eyeLook weights from the eyes'; the rest are solved from the face's shape (exactly: the problem has one answer,\n// so the Python package gives the same weights). The head, neck and chest rotations and the travel are not\n// blendshapes: apply those to your rig's bones from the frame itself.\nconst LOOK = ['eyeLookDownLeft', 'eyeLookDownRight', 'eyeLookInLeft', 'eyeLookInRight', 'eyeLookOutLeft', 'eyeLookOutRight', 'eyeLookUpLeft', 'eyeLookUpRight'];\n\nfunction rotation(x, y, z, R) { // axis-angle -> row-major 3x3\n const t = Math.hypot(x, y, z); if (t < 1e-9) { R[0] = 1; R[1] = -z; R[2] = y; R[3] = z; R[4] = 1; R[5] = -x; R[6] = -y; R[7] = x; R[8] = 1; return R; }\n const kx = x / t, ky = y / t, kz = z / t, c = Math.cos(t), s = Math.sin(t), v = 1 - c;\n R[0] = c + kx * kx * v; R[1] = kx * ky * v - kz * s; R[2] = kx * kz * v + ky * s; R[3] = ky * kx * v + kz * s; R[4] = c + ky * ky * v; R[5] = ky * kz * v - kx * s; R[6] = kz * kx * v - ky * s; R[7] = kz * ky * v + kx * s; R[8] = c + kz * kz * v; return R;\n}\n\nclass Arkit {\n // options: model 'tiny' or 'nano' (whose resting face the weights are measured from) or rest (your own frame of 118);\n // base: URL of the folder with arkit.json and arkit.bin (browser); load: your own (name) => ArrayBuffer;\n // jaw: the jaw rotation, in radians past rest, that counts as jawOpen = 1; lookRange: the same for the eyeLook weights\n static async load({ model = 'tiny', base = null, load = null, ...options } = {}) {\n if (!load) { const { loader } = await import('./index.js'); load = await loader('arkit', base); }\n const meta = JSON.parse(new TextDecoder().decode(await load('arkit.json'))); return new Arkit(meta, await load('arkit.bin'), { model, ...options });\n }\n constructor(meta, buf, { model = 'tiny', rest = null, jaw = 0.35, lookRange = 0.5, ridge = 0.01 } = {}) {\n const d = {}; for (const [k, a] of Object.entries(meta.arrays)) { const n = a.shape.reduce((x, y) => x * y, 1); d[k] = a.dtype === 'uint32' ? new Uint32Array(buf, a.offset, n) : Float64Array.from(new Float32Array(buf, a.offset, n)); }\n Object.assign(this, d); this.names = meta.names; this.index = Object.fromEntries(this.names.map((n, i) => [n, i])); this.U = meta.vertices; this.nS = meta.skin; this.P = meta.points; this.jaw = jaw; this.lookRange = lookRange;\n this.rest = Float64Array.from(rest || meta.rest[model]); const K = this.K = this.names.length, n = this.n = 3 * (this.nS + this.P), jo = this.index.jawOpen;\n this.v = new Float64Array(this.U * 3); this.R = new Float64Array(9); this.restPoints = this.points(this.rest, new Float64Array(n));\n const A = this.A = Float64Array.from(this.shapes), step = Float64Array.from(this.rest); step[103] += 0.05; const p = this.points(step, new Float64Array(n)); // jawOpen is the jaw's own rotation: the direction it starts in, from rest\n for (let k = 0; k < n; k++) A[jo * n + k] = (p[k] - this.restPoints[k]) * jaw / 0.05;\n const free = this.free = []; this.names.forEach((x, i) => { if (!LOOK.includes(x) && i !== jo) free.push(i); }); const m = this.m = free.length, H = this.H = new Float64Array(m * m); let tr = 0;\n for (let a = 0; a < K; a++) { let s = 0; for (let k = 0; k < n; k++) s += A[a * n + k] * A[a * n + k]; tr += s; }\n for (let a = 0; a < m; a++) for (let b = a; b < m; b++) { let s = 0; const X = free[a] * n, Y = free[b] * n; for (let k = 0; k < n; k++) s += A[X + k] * A[Y + k]; H[a * m + b] = H[b * m + a] = s; }\n const lam = ridge * tr / K; for (let a = 0; a < m; a++) H[a * m + a] += lam;\n this.d = new Float64Array(n); this.b = new Float64Array(m); this.w = new Float64Array(m); this.z = new Float64Array(m); this.lo = new Uint8Array(m).fill(1); this.hi = new Uint8Array(m); this.L = new Float64Array(m * m); this.rhs = new Float64Array(m); this.out = new Float32Array(K);\n }\n points(f, out) { // a frame -> the compared points in the head's frame: the skin vertices, then the control points (weighted)\n const U = this.U, v = this.v, E = this.expr, R = rotation(f[103], f[104], f[105], this.R), T = this.template, PD = this.jaw_dirs, JE = this.jaw_joint_expr, n3 = U * 3; v.set(T); let jx = this.jaw_joint[0], jy = this.jaw_joint[1], jz = this.jaw_joint[2];\n for (let i = 0; i < 100; i++) { const c = f[i]; if (c === 0) continue; const o = i * n3; for (let k = 0; k < n3; k++) v[k] += c * E[o + k]; jx += c * JE[3 * i]; jy += c * JE[3 * i + 1]; jz += c * JE[3 * i + 2]; }\n for (let p = 0; p < 9; p++) { const c = R[p] - (p % 4 === 0 ? 1 : 0); if (c === 0) continue; const o = p * n3; for (let k = 0; k < n3; k++) v[k] += c * PD[o + k]; }\n for (let u = 0; u < U; u++) { const w = this.jaw_weight[u]; if (w === 0) continue; const x = v[3 * u] - jx, y = v[3 * u + 1] - jy, z = v[3 * u + 2] - jz; v[3 * u] += w * (R[0] * x + R[1] * y + R[2] * z - x); v[3 * u + 1] += w * (R[3] * x + R[4] * y + R[5] * z - y); v[3 * u + 2] += w * (R[6] * x + R[7] * y + R[8] * z - z); }\n const nS = this.nS, S = this.skin, C = this.corners, B = this.bary, W = this.point_weight;\n for (let i = 0; i < nS; i++) for (let c = 0; c < 3; c++) out[3 * i + c] = v[3 * S[i] + c];\n for (let i = 0; i < this.P; i++) for (let c = 0; c < 3; c++) out[3 * (nS + i) + c] = W[i] * (B[3 * i] * v[3 * C[3 * i] + c] + B[3 * i + 1] * v[3 * C[3 * i + 1] + c] + B[3 * i + 2] * v[3 * C[3 * i + 2] + c]);\n return out;\n }\n box() { // the weights in 0..1 that minimise w.H.w / 2 - b.w, exactly (an active-set solve, started from where the last frame's ended; the answer does not depend on the start)\n const { H, b, w, z, lo, hi, m, L, rhs } = this, tol = 1e-9, ix = []; for (let i = 0; i < m; i++) w[i] = hi[i] ? 1 : lo[i] ? 0 : w[i];\n for (let it = 0; it < 20 * m; it++) {\n for (;;) { // the best weights with the bound ones held; walk towards them until none leaves 0..1\n ix.length = 0; for (let i = 0; i < m; i++) if (!lo[i] && !hi[i]) ix.push(i); const q = ix.length; if (!q) break;\n for (let a = 0; a < q; a++) { let s = b[ix[a]]; for (let j = 0; j < m; j++) if (lo[j] || hi[j]) s -= H[ix[a] * m + j] * w[j]; rhs[a] = s; }\n for (let a = 0; a < q; a++) for (let c = 0; c <= a; c++) { let s = H[ix[a] * m + ix[c]]; for (let k = 0; k < c; k++) s -= L[a * m + k] * L[c * m + k]; L[a * m + c] = a === c ? Math.sqrt(s) : s / L[c * m + c]; } // Cholesky\n for (let a = 0; a < q; a++) { let s = rhs[a]; for (let k = 0; k < a; k++) s -= L[a * m + k] * rhs[k]; rhs[a] = s / L[a * m + a]; }\n for (let a = q - 1; a >= 0; a--) { let s = rhs[a]; for (let k = a + 1; k < q; k++) s -= L[k * m + a] * rhs[k]; rhs[a] = s / L[a * m + a]; }\n let step = Infinity, any = false; for (let a = 0; a < q; a++) { const i = ix[a], t = rhs[a]; z[i] = t; if (t < -tol) { any = true; step = Math.min(step, w[i] / Math.max(w[i] - t, 1e-300)); } else if (t > 1 + tol) { any = true; step = Math.min(step, (1 - w[i]) / Math.max(t - w[i], 1e-300)); } }\n if (!any) { for (let a = 0; a < q; a++) w[ix[a]] = z[ix[a]]; break; }\n step = Math.max(0, step);\n for (let a = 0; a < q; a++) { const i = ix[a], t = z[i], s = t < -tol ? w[i] / Math.max(w[i] - t, 1e-300) : t > 1 + tol ? (1 - w[i]) / Math.max(t - w[i], 1e-300) : Infinity; w[i] += step * (t - w[i]); if (s <= step + 1e-12) { if (t < 0) { lo[i] = 1; w[i] = 0; } else { hi[i] = 1; w[i] = 1; } } }\n }\n let k = -1, worst = 1e-10; for (let i = 0; i < m; i++) { if (!lo[i] && !hi[i]) continue; let g = -b[i]; for (let j = 0; j < m; j++) g += H[i * m + j] * w[j]; const bad = lo[i] ? -g : g; if (bad > worst) { worst = bad; k = i; } } // a bound weight that would rather move inward\n if (k < 0) break; lo[k] = hi[k] = 0;\n }\n return w;\n }\n // A frame (118 numbers) -> its 51 weights. The returned array is reused by the next call: copy it to keep it.\n convert(f) {\n const { n, A, d, b, free, m, out } = this, jo = this.index.jawOpen, r = this.restPoints, wj = Math.min(1, Math.max(0, (f[103] - this.rest[103]) / this.jaw)), X = jo * n; this.points(f, d);\n for (let k = 0; k < n; k++) d[k] -= r[k] + wj * A[X + k]; // the jaw's turn is known; the other shapes explain what is left\n for (let a = 0; a < m; a++) { let s = 0; const o = free[a] * n; for (let k = 0; k < n; k++) s += A[o + k] * d[k]; b[a] = s; }\n const w = this.box(); out.fill(0); for (let a = 0; a < m; a++) out[free[a]] = Math.min(1, Math.max(0, w[a])); out[jo] = wj;\n const R = this.lookRange, set = (name, x) => { out[this.index[name]] = Math.min(1, Math.max(0, x / R)); }; // +x is the face's left; turning about +x looks down, about +y towards the face's left\n set('eyeLookDownLeft', f[109]); set('eyeLookUpLeft', -f[109]); set('eyeLookOutLeft', f[110]); set('eyeLookInLeft', -f[110]);\n set('eyeLookDownRight', f[112]); set('eyeLookUpRight', -f[112]); set('eyeLookInRight', f[113]); set('eyeLookOutRight', -f[113]);\n return out;\n }\n}\n\nreturn { Arkit };\n})();\n__m['resample'] = (() => {\n// A streaming resampler: audio at any rate in, 16 kHz (or any rate) out, anti-aliased by a windowed-sinc filter.\n// Output sample j is the input at time j / outRate from the stream's first sample: no delay, so timestamps stay exact\n// (the output for a moment is ready once the input is `reach` seconds past it). The same input cut into different\n// chunks gives the same output.\n//\n// const r = new Resampler(48000); // to 16 kHz\n// const y = r.push(block); // Float32Array: the output samples this block completes (possibly none)\nclass Resampler {\n constructor(inRate, outRate = 16000, { zeros = 16, phases = 256 } = {}) {\n this.step = inRate / outRate; this.same = inRate === outRate; // input samples per output sample\n const down = Math.min(1, outRate / inRate), fc = 0.45 * down; // cutoff, cycles per input sample: 0.9 of the lower Nyquist\n this.R = zeros / down; this.P = phases; this.reach = this.R / inRate; // the kernel's half-width in input samples\n const n = Math.ceil(this.R * phases) + 2, T = this.table = new Float64Array(n);\n for (let k = 0; k < n; k++) { const x = k / phases; if (x >= this.R) break; const w = 0.5 + 0.5 * Math.cos(Math.PI * x / this.R), a = 2 * Math.PI * fc * x; T[k] = w * (x === 0 ? 2 * fc : Math.sin(a) / (Math.PI * x)); }\n this.buf = new Float32Array(4096); this.base = 0; this.n = 0; this.j = 0; // input samples [base, n) are held; j: the next output sample\n }\n push(x) {\n if (this.same) { this.n += x.length; this.j += x.length; return Float32Array.from(x); }\n const keep = Math.min(this.n, Math.max(this.base, Math.floor(this.j * this.step - this.R) - 1)), held = this.n - keep; // drop the input no output needs any more\n if (keep > this.base || held + x.length > this.buf.length) {\n const size = Math.max(this.buf.length, 2 ** Math.ceil(Math.log2(held + x.length))), b = size > this.buf.length ? new Float32Array(size) : this.buf;\n if (b === this.buf) b.copyWithin(0, keep - this.base, this.n - this.base);\n else b.set(this.buf.subarray(keep - this.base, this.n - this.base));\n this.buf = b; this.base = keep;\n }\n this.buf.set(x, this.n - this.base); this.n += x.length;\n const out = [], { buf, base, step, R, P, table } = this;\n for (;;) {\n const p = this.j * step, hi = Math.floor(p + R); if (hi >= this.n) break;\n let s = 0, ws = 0;\n for (let i = Math.ceil(p - R); i <= hi; i++) {\n const d = Math.abs(i - p) * P, k = Math.floor(d), h = table[k] + (d - k) * (table[k + 1] - table[k]); ws += h; if (i >= 0) s += h * buf[i - base];\n }\n out.push(s / ws); this.j++;\n }\n return Float32Array.from(out);\n }\n}\n\nreturn { Resampler };\n})();\n__m['index'] = (() => {\n// callable-lipsync: 16 kHz speech in, FLAME 2023 Open frames out at 25 fps. Runs on onnxruntime-web, in a page, a worker or Node.\n//\n// import * as ort from 'onnxruntime-web';\n// import { LipSync } from 'callable-lipsync';\n// const model = await LipSync.load(ort, { model: 'tiny', base: '/models/tiny/' }); // in Node, leave `base` out\n// const frames = await model.process(samples); // Float32Array, 16 kHz mono -> [Float32Array(118), ...]\nconst { Engine } = __m['engine'];\nconst { Arkit } = __m['arkit'];\n\nconst VERSION = '0.3.0'; // this package's version (kept equal to package.json's by the tests)\nconst SAMPLE_RATE = 16000, FPS = 25, FRAME = 640;\n// what the 118 numbers of a frame are: [first, one past the last]. Rotations are axis-angle, in radians.\nconst LAYOUT = { expression: [0, 100], chest: [100, 103], jaw: [103, 106], neck: [106, 109], leftEye: [109, 112], rightEye: [112, 115], travel: [115, 118] };\n// seconds of audio ahead of a frame -> the engine's settings; `ready`: frames after a frame's own start until it is computed\nconst AHEAD = { 0.64: { known: 12, wait: 4, ready: 16 }, 0.48: { known: 8, wait: 4, ready: 12 }, 0.32: { known: 4, wait: 4, ready: 8 }, 0.16: { known: 0, wait: 4, ready: 5 }, 0.08: { known: -2, wait: 2, ready: 3 }, 0: { known: -4, wait: 0, ready: 1 } };\n\n// A function that fetches a model's files ('tiny', 'nano', or 'arkit' for the blendshape converter's data): from `base` (a URL ending in /), or, in Node, from this package's models/ folder.\nasync function loader(model = 'tiny', base = null) {\n if (base) return async name => { const r = await fetch(base + name); if (!r.ok) throw new Error(`callable-lipsync: ${base + name}: ${r.status}`); return r.arrayBuffer(); };\n if (typeof process === 'undefined' || !process.versions?.node) throw new Error('callable-lipsync: in a browser, pass { base } (the URL of the folder with the model\\'s files)');\n const fs = await import(/* @vite-ignore */ /* webpackIgnore: true */ 'node:fs/promises'), dir = new URL(`../models/${model}/`, import.meta.url);\n return async name => { const b = await fs.readFile(new URL(name, dir)); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };\n}\n\nclass LipSync {\n // ort: onnxruntime-web (or anything with the same InferenceSession and Tensor). options:\n // model 'tiny' (lips, jaw, face, blinks, gaze, head, neck, upper body) or 'nano' (lips, jaw, face, head)\n // base URL of the folder with the model's files (browser); load: your own (name) => ArrayBuffer\n // ahead, seed, expressiveness: see reset(); session: options for InferenceSession.create\n static async load(ort, { model = 'tiny', base = null, load = null, session = null, ...settings } = {}) {\n const m = new LipSync(); m.engine = await Engine.create(ort, load || await loader(model, base), session ? { session } : {}); m.nano = m.engine.nano; m.ahead = 0.64; m.expressiveness = 2; m.reset(settings); return m;\n }\n // Start a new stream. ahead: seconds of audio the model may hear before a frame is due (0.64, 0.48, 0.32, 0.16, 0.08, 0;\n // nano always uses 0.16). seed: same seed and audio give the same motion (default: a new one). expressiveness: 1 to 3 (tiny).\n reset({ ahead = this.ahead, seed = null, expressiveness = this.expressiveness } = {}) {\n if (this.nano) ahead = 0.16; const mode = AHEAD[ahead]; if (!mode) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', '));\n this.ahead = +ahead; this.expressiveness = expressiveness; this.delayFrames = mode.ready; this.seed = seed ?? (Math.random() * 2 ** 31) | 0; this.samples = 0;\n this.engine.reset({ known: mode.known, wait: mode.wait, guide: expressiveness, seed: this.seed });\n }\n // Feed 16 kHz mono samples (any length); resolves to the frames it settled, in order (possibly none).\n async process(samples) { this.samples += samples.length; this.engine.push(samples); return (await this.engine.step()).map(f => f.data); }\n // The frames still owed for the audio fed so far (the model waits for audio ahead; this feeds it silence).\n async flush() { const want = Math.floor(this.samples / FRAME) - this.engine.out; if (want <= 0) return []; return (await this.process(new Float32Array((this.delayFrames + 12) * FRAME))).slice(0, want); }\n}\n\nreturn { Engine, Arkit, VERSION, SAMPLE_RATE, FPS, FRAME, LAYOUT, AHEAD, loader, LipSync };\n})();\n__m['web-worker'] = (() => {\n// The worker half of LipSyncNode (web.js): resamples the captured audio to 16 kHz, runs the model on one WebAssembly\n// thread and posts the frames (and their ARKit weights) back to the page, off its main thread.\n//\n// From the page: init (where onnxruntime and the models are), load (a model), and a MessagePort from the capture\n// worklet that brings start (a new stream: its settings and the audio clock's sample index where it begins), audio\n// (chunks of it) and set (expressiveness). The stream's messages run one after another; loading a model runs beside them.\n// onnxruntime-web: `ort` from the page, else (run as a module file by a bundler) its own package, else the CDN. Bundling\n// this file therefore needs onnxruntime-web 1.19 or newer installed (its 'onnxruntime-web/wasm' entry).\nconst { LipSync, AHEAD } = __m['index'];\nconst { Arkit } = __m['arkit'];\nconst { Resampler } = __m['resample'];\n\nconst ORT_CDN = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.wasm.min.mjs';\nconst MAX_GAP = 1, BEHIND = 0.5, CAUGHT_UP = 0.05; // seconds of missing audio filled with silence (past that the stream starts over); seconds of audio waiting before it is skipped, down to this much\nlet ort = null, cfg = null, queue = Promise.resolve(), s = null, newest = { stream: -1, end: 0 }; // s: the stream being run; newest: the end of the latest audio that came in\nconst models = {}, arkits = {}; let arkitFiles = null; // the ARKit converter's files, fetched once for all models\n\nasync function runtime() {\n if (ort) return ort;\n let o;\n if (cfg.ort) o = await import(/* @vite-ignore */ /* webpackIgnore: true */ cfg.ort);\n else { try { o = await import('onnxruntime-web/wasm'); } catch (e) { o = await import(/* @vite-ignore */ /* webpackIgnore: true */ ORT_CDN); } } // a bundler resolves the package; a plain page cannot, so the CDN\n o = o.default && o.default.InferenceSession ? o.default : o;\n if (!o.InferenceSession || !o.env || !o.env.wasm) throw new Error('callable-lipsync: ' + (cfg.ort || 'that module') + ' is not onnxruntime-web');\n o.env.wasm.numThreads = 1; if (cfg.wasmPaths) o.env.wasm.wasmPaths = cfg.wasmPaths;\n return (ort = o); // kept only once it works: a failure can be tried again\n}\nfunction fetcher(dir, model) { // (name) => ArrayBuffer from dir, reporting the download's progress\n let bytes = 0, total = 0;\n return async (name) => {\n const r = await fetch(dir + name); if (!r.ok) throw new Error(`callable-lipsync: ${dir + name}: ${r.status}`); const b = await r.arrayBuffer();\n if (name === 'meta.json') total = JSON.parse(new TextDecoder().decode(b)).bytes || 0; else bytes += b.byteLength;\n if (model) postMessage({ type: 'progress', model, bytes, total }); return b;\n };\n}\nfunction load(model) { // the model (and its ARKit converter), once\n if (models[model]) return models[model];\n models[model] = (async () => {\n const t0 = performance.now(), o = await runtime(), lip = await LipSync.load(o, { model, load: fetcher(cfg.base + model + '/', model), seed: 0 });\n const ms = performance.now() - t0; // the model's own start-up\n await Promise.race([converter(model), new Promise((r) => setTimeout(r, 3000))]); // `names` usually comes with 'loaded'; a slow download sends them later\n postMessage({ type: 'loaded', model, ms, bytes: lip.engine.bytes, weights: lip.engine.meta.weights || 0, names: arkits[model] ? arkits[model].names : null });\n return lip;\n })();\n models[model].catch(() => { delete models[model]; delete arkits[model]; }); // a failed download can be tried again\n return models[model];\n}\nconst noArkit = {}, warned = {}, converting = {}; // models whose converter could not be built from its files (not tried again)\nfunction converter(model) { // the model's ARKit converter (with arkit on), built once at a time; a failure costs only the weights\n if (!cfg.arkit || arkits[model] || noArkit[model]) return Promise.resolve();\n if (!converting[model]) converting[model] = build(model).finally(() => { delete converting[model]; });\n return converting[model];\n}\nasync function build(model) {\n let files;\n try {\n if (!arkitFiles) { const get = fetcher(cfg.base + 'arkit/'); arkitFiles = Promise.all([get('arkit.json'), get('arkit.bin')]); arkitFiles.catch(() => { arkitFiles = null; }); }\n files = await arkitFiles;\n } catch (e) { // a download that failed: the next stream tries again (warned once)\n if (!warned[model]) postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights for now: ' + text(e) }); warned[model] = true; return;\n }\n try { arkits[model] = new Arkit(JSON.parse(new TextDecoder().decode(files[0])), files[1], { model }); warned[model] = false; postMessage({ type: 'names', names: arkits[model].names }); }\n catch (e) { noArkit[model] = true; postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights: ' + text(e) }); } // bad data: not tried again\n}\nasync function begin(m, frame) { // a stream from the audio clock's sample `frame` on\n const lip = await load(m.model); lip.reset({ ahead: m.ahead, seed: m.seed, expressiveness: m.expressiveness });\n converter(m.model); // in the background: the weights join the frames once it is there\n s = { stream: m.stream, m, lip, start: frame, rate: m.rate, next: frame, r: new Resampler(m.rate), first: 0 };\n}\nlet ping = null, woke = null;\nfunction yieldTask() {\n if (!ping) { ping = new MessageChannel(); ping.port1.onmessage = () => { const w = woke; woke = null; if (w) w(); }; } // made when first needed\n return new Promise((r) => { woke = r; ping.port2.postMessage(0); });\n} // a macrotask: the audio messages waiting are dispatched first, so `newest` is current\nasync function audio(m) {\n await yieldTask();\n if (!s || m.stream !== s.stream || m.stream !== newest.stream) return; // a newer stream is on its way: this one is over\n if (newest.end - m.frame - m.samples.length > (s.dropped ? CAUGHT_UP : BEHIND) * s.rate) { s.dropped = true; return; } // slower than real time: skip to (nearly) the newest audio\n const gap = m.frame - s.next;\n if (s.dropped || gap > MAX_GAP * s.rate || gap < 0) { const n = (s.restarts || 0) + 1, m0 = s.m; await begin({ ...m0, seed: m0.seed == null ? null : (m0.seed + n) | 0 }, m.frame); s.m = m0; s.restarts = n; } // audio skipped, or the clock jumped: start over from here (a new draw of the head's motion)\n else if (gap > 0) await feed(new Float32Array(gap));\n await feed(m.samples);\n}\nasync function feed(x) {\n s.next += x.length; const t0 = performance.now(), frames = await s.lip.process(s.r.push(x)), n = frames.length; if (!n) return;\n const ak = arkits[s.m.model], data = new Float32Array(n * 118), w = ak ? new Float32Array(n * 51) : null;\n frames.forEach((f, i) => { data.set(f, i * 118); if (w) w.set(ak.convert(f), i * 51); }); const ms = performance.now() - t0; // the model and the ARKit weights\n postMessage({ type: 'frames', stream: s.stream, start: s.start, rate: s.rate, first: s.first, count: n, data, weights: w, ms, restarts: s.restarts || 0 }, w ? [data.buffer, w.buffer] : [data.buffer]); s.first += n;\n}\nfunction stream(m) { // the capture worklet's messages, in order\n if (m.type === 'stop') { if (s && s.stream === m.stream) s = null; return; }\n if (m.type === 'set') { if (s && m.expressiveness != null) { s.lip.expressiveness = s.m.expressiveness = m.expressiveness; s.lip.engine.guide = m.expressiveness; } return; }\n if (m.type === 'start') { if (!AHEAD[m.ahead]) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', ')); return begin(m, m.frame); }\n if (m.type === 'audio') return audio(m);\n}\nconst text = (e) => (e && e.message && !String(e.stack || '').includes(e.message) ? e.message + '\\n' : '') + String((e && e.stack) || e); // Firefox and Safari leave the message out of the stack\npostMessage({ type: 'hello' }); // started: from now on an uncaught error is not fatal\nself.onmessage = (e) => {\n const m = e.data;\n if (m.type === 'init') cfg = m;\n else if (m.type === 'load') load(m.model).then(() => {}, (err) => postMessage({ type: 'error', model: m.model, message: text(err) }));\n else if (m.type === 'port') m.port.onmessage = (ev) => {\n const a = ev.data;\n if (a.type === 'start') newest = { stream: a.stream, end: a.frame };\n else if (a.type === 'stop' && a.stream === newest.stream) newest = { stream: -1, end: 0 }; // its queued audio is dropped at once\n else if (a.type === 'audio' && a.stream === newest.stream && a.frame + a.samples.length > newest.end) newest.end = a.frame + a.samples.length;\n queue = queue.then(() => stream(a)).catch((err) => { if (s && s.stream === a.stream) s = null; postMessage({ type: 'error', stream: a.stream, message: text(err) }); }); // a failed stream stops\n };\n};\n\nreturn { };\n})();";
|
|
2
|
+
export const WORKER = "// Generated by scripts/build_web.mjs from the files in js/: do not edit.\nconst __m = {};\n__m['engine'] = (() => {\n// callable-lipsync as a stream: 16 kHz audio in, FLAME 2023 Open frames out at 25 fps\n// (118 numbers: 100 expression, 3 chest rotation, 3 jaw, 3 neck, 6 eyes, 3 travel in m).\n// Runs the model's ONNX graphs with onnxruntime (web or node); works in a page, a worker or Node.\n//\n// Audio ahead of a frame: the lips use `wait` frames of it (4 = 0.16 s, the model's full view; fewer: silence stands\n// in for the rest), the head `known` frames more past that (12 = 0.64 s in all; 8, 4, 0; -4 with wait 0 = none).\n// `quiet` (default on): after 0.4 s without sound the mouth is eased to the model's closed pose (meta.closed), and released as sound returns.\n// `floor`: the level of a faint noise added to the audio (1e-4 = -80 dB; 0 = none), so that long digital silence reads as a quiet room.\n// Every block of the network keeps its past outputs, so a new 40 ms of audio costs one frame of each block.\nconst FRAME = 640, LOUD = 1e-5, HOLD = 10; // samples a frame; the mean square of a frame with sound in it (-50 dB); frames after the last sound before the mouth is eased shut\nfunction rng(seed) { let a = seed >>> 0; return () => { a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }\n\nclass Engine {\n static async create(ort, load, options = {}) {\n const e = new Engine(); e.ort = ort; e.meta = JSON.parse(new TextDecoder().decode(await load('meta.json'))); e.s = {}; e.bytes = 0;\n for (const n of e.meta.graphs) { const b = await load(n + '.onnx'); e.bytes += b.byteLength; e.s[n] = await ort.InferenceSession.create(new Uint8Array(b), options.session || {}); }\n e.nano = e.meta.kind === 'nano'; // the small model: face, jaw and the head's rotation straight from the audio; no draws, no chest, eyes or blinks; always 0.16 s of audio ahead\n if (!e.nano) { const tb = await load('tables.bin'), T = e.meta.tables; e.dig = new Float32Array(tb, T.dig.offset, T.dig.shape[0] * T.dig.shape[1]); e.template = new Float32Array(tb, T.template.offset, T.template.shape[0] * T.template.shape[1]); }\n e.layers = []; let src = 'e'; e.meta.trunk.forEach((b, i) => { e.layers.push({ name: 't' + i, src, ...b }); src = 't' + i; }); e.hName = src; e.meta.slow.forEach((b, i) => { e.layers.push({ name: 's' + i, src, ...b }); src = 's' + i; }); e.sName = src;\n e.zero = new Float32Array(e.meta.width); e.reset({}); return e;\n }\n reset({ known = 12, wait = 4, guide = 2, temp = 1, blinkTemp = 1, smooth = 0.75, seed = 1, hop = null, record = false, floor = 1e-4, quiet = true } = {}) {\n const m = this.meta; if (this.nano) { wait = m.future; known = 0; hop = 1; } Object.assign(this, { known, wait, guide, temp, blinkTemp, smooth, record, floor, quiet }); this.en = []; this.en0 = 0; this.enAcc = 0; this.enN = 0; this.lastLoud = -1e9; this.gate = 0; this.hiss = rng(0x5bd1e995); // the noise floor is the same on every run: the lips do not depend on the seed\n this.hop = hop || (wait === m.future && known >= m.stride ? m.stride : 1); this.rand = rng(seed); this.blinkRand = rng(seed ^ 0x9e3779b9); // blinks draw from their own sequence, so the motion does not depend on how the audio was cut into chunks\n this.audio = new Float32Array(1 << 16); this.a0 = 0; this.an = 0; // samples [a0, an) are held\n this.col = { e: [] }; this.n = { e: 0 }; for (const l of this.layers) { this.col[l.name] = []; this.n[l.name] = 0; } // each block's outputs per frame, final up to n\n this.naux = 0; this.aux = []; this.nface = 0; this.face = [];\n if (!this.nano) { this.ha = new Float32Array(2 * m.ahid); this.hb = new Float32Array(2 * m.ahid); this.hx = new Float32Array(4 * m.hid); } this.blinkLast = 0; this.blinkStart = -1;\n this.nb = 0; this.q = []; this.pose = []; this.y1 = null; this.y2 = null; this.out = 0;\n this.ms = { lips: 0, heads: 0, tokens: 0, frames: 0, calls: 0 }; this.log = { digits: [], probs: [], blinks: [], face: [] };\n }\n push(x) {\n if (this.an - this.a0 + x.length > this.audio.length) { const from = Math.max(this.a0, this.an - 16 * FRAME); let n = this.audio.length; while (n < this.an - from + x.length) n *= 2; const b = new Float32Array(n); b.set(this.audio.subarray(from - this.a0, this.an - this.a0)); this.audio = b; this.a0 = from; }\n const o = this.an - this.a0, a = this.audio, g = 2 * this.floor, r = this.hiss; this.an += x.length;\n for (let i = 0; i < x.length; i++) { this.enAcc += x[i] * x[i]; if (++this.enN === FRAME) { this.en.push(this.enAcc / FRAME > LOUD); this.enAcc = 0; this.enN = 0; } } // per frame: is there sound (over -50 dB); en[k - en0] is frame k's\n if (this.en.length > 4096) { const cut = Math.min(this.en.length - 1024, (this.nano ? this.out : this.nface) - HOLD - 1 - this.en0); if (cut > 0) { this.en.splice(0, cut); this.en0 += cut; } } // a long stream: drop what the silence gate no longer reads\n if (g) for (let i = 0; i < x.length; i++) a[o + i] = x[i] + g * (r() + r() + r() - 1.5); else a.set(x, o); // a noise floor (-80 dB): exact digital silence is something the model never heard, and after 2.5 s of it the lips drift open\n }\n t(data, dims) { return new this.ort.Tensor('float32', data, dims); }\n async run(name, feeds) { this.ms.calls++; return this.s[name].run(feeds); }\n window(f0, f1, end) { // audio of frames [f0, f1), zeros before the stream and from sample `end` on\n const x = new Float32Array((f1 - f0) * FRAME), a = Math.max(f0 * FRAME, this.a0, 0), b = Math.min(f1 * FRAME, end, this.an); if (b > a) x.set(this.audio.subarray(a - this.a0, b - this.a0), a - f0 * FRAME); return x;\n }\n async fe(f0, f1, end) { // the vectors into the trunk for frames [f0, f1) -> rows\n const w = this.meta.width, x = this.window(f0 - 2, f1, end), r = (await this.run('fe', { audio: this.t(x, [1, x.length]) })).e.data, o = []; for (let i = f0; i < f1; i++) o.push(r.slice((i - f0 + 2) * w, (i - f0 + 3) * w)); return o;\n }\n async blockCols(l, frames, get) { // block l at `frames` from its input's columns\n const w = this.meta.width, N = frames.length, x = new Float32Array(N * w * 3);\n for (let i = 0; i < N; i++) { const t = frames[i], taps = l.ahead ? [t - l.d, t, t + l.d] : [t - 2 * l.d, t - l.d, t]; for (let k = 0; k < 3; k++) { const c = await get(l.src, taps[k]); for (let j = 0; j < w; j++) x[(i * w + j) * 3 + k] = c[j]; } }\n const y = (await this.run(l.name, { x: this.t(x, [N, w, 3]) })).y.data, o = []; for (let i = 0; i < N; i++) o.push(y.slice(i * w, (i + 1) * w)); return o;\n }\n async final(nE) { // everything the audio up to frame nE (exclusive) settles for good\n if (nE > this.n.e) { (await this.fe(this.n.e, nE, nE * FRAME)).forEach((c, i) => { this.col.e[this.n.e + i] = c; }); this.n.e = nE; }\n const get = async (name, t) => (t < 0 ? this.zero : this.col[name][t]);\n for (const l of this.layers) { const lim = this.n[l.src] - (l.ahead ? l.d : 0); if (lim > this.n[l.name]) { const fr = []; for (let t = this.n[l.name]; t < lim; t++) fr.push(t); (await this.blockCols(l, fr, get)).forEach((c, i) => { this.col[l.name][fr[i]] = c; }); this.n[l.name] = lim; } }\n }\n async spec(f) { // frame f's features [h, s] from audio up to frame f + wait only, silence after it\n const nE = f + this.wait + 1, lim = { e: nE }, sc = { e: [] }; for (const l of this.layers) { lim[l.name] = lim[l.src] - (l.ahead ? l.d : 0); sc[l.name] = []; }\n (await this.fe(nE, f + this.meta.future + 1, nE * FRAME)).forEach((c, i) => { sc.e[nE + i] = c; });\n const get = async (name, t) => { if (t < 0) return this.zero; if (t < lim[name]) return this.col[name][t]; if (!sc[name][t]) sc[name][t] = (await this.blockCols(this.layers.find(l => l.name === name), [t], get))[0]; return sc[name][t]; };\n return [await get(this.hName, f), await get(this.sName, f)];\n }\n async faces(H) { // output frames [nface, nface + H): face, upper face, blinks\n const m = this.meta, w = m.width, hs = new Float32Array(H * w), fh = new Float32Array(2 * w * H);\n for (let i = 0; i < H; i++) { const t = this.nface + i, [h, s] = this.wait === m.future ? [this.col[this.hName][t], this.col[this.sName][t]] : await this.spec(t); hs.set(h, i * w); for (let c = 0; c < w; c++) { fh[c * H + i] = h[c]; fh[(w + c) * H + i] = s[c]; } }\n const fc = new Float32Array((await this.run('face', { h: this.t(hs, [H, w]) })).face.data), closed = this.meta.closed;\n for (let i = 0; i < H; i++) { // no sound for a while (as far as this frame may hear): the mouth eases to the model's own closed pose. Left alone it drifts half open in long silences\n const tt = this.nface + i, upto = Math.min(this.en0 + this.en.length - 1, tt + this.wait); for (let k = Math.max(this.en0, tt - HOLD); k <= upto; k++) if (this.en[k - this.en0]) this.lastLoud = Math.max(this.lastLoud, k);\n const silent = this.lastLoud < tt - HOLD; this.gate = silent ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; const gt = this.quiet && closed ? this.gate : 0;\n if (this.record) this.log.face.push(Array.from(fc.subarray(i * 101, i * 101 + 101)));\n if (gt > 1e-3) for (let c = 0; c < 101; c++) fc[i * 101 + c] += gt * (closed[c] - fc[i * 101 + c]);\n }\n const hd = await this.run('head', { f: this.t(fh, [1, 2 * w, H]) }), B = m.blink, Z = m.Z, z = new Float32Array(hd.z.data);\n for (let i = 0; i < H; i++) {\n const tt = this.nface + i, bucket = Math.min(Math.floor((tt - this.blinkLast) / 5), B.since - 1), p = 1 / (1 + Math.exp(-hd.blink.data[i * B.since + bucket] / this.blinkTemp));\n if ((tt - this.blinkLast >= B.gap || this.blinkStart < 0) && this.blinkRand() < p) { this.blinkStart = tt; this.blinkLast = tt + 1; if (this.record) this.log.blinks.push(tt); }\n if (this.blinkStart >= 0 && tt - this.blinkStart < B.len) for (let k = 0; k < Z; k++) z[i * Z + k] += this.template[(tt - this.blinkStart) * Z + k];\n }\n const o = await this.run('open', { face: this.t(fc, [H, 101]), z: this.t(z, [H, Z]) });\n for (let i = 0; i < H; i++) this.face[this.nface + i] = { expr: o.expr.data.slice(i * 100, i * 100 + 100), jaw: o.jaw.data.slice(i * 3, i * 3 + 3) };\n this.nface += H;\n }\n async sides() { // what the audio sides say for the frames whose features are final\n const m = this.meta, w = m.width, a = this.naux, b = this.n[this.sName], H = b - a, fw = new Float32Array(2 * w * (H + 4)); // their first convolution reads 4 frames back (zeros before the stream)\n for (let i = 0; i < H + 4; i++) { const t = a - 4 + i; if (t < 0) continue; const h = this.col[this.hName][t], s = this.col[this.sName][t]; for (let c = 0; c < w; c++) { fw[c * (H + 4) + i] = h[c]; fw[(w + c) * (H + 4) + i] = s[c]; } }\n const au = await this.run('aud', { f: this.t(fw, [1, 2 * w, H + 4]), ha: this.t(this.ha, [2, 1, m.ahid]), hb: this.t(this.hb, [2, 1, m.ahid]) }); this.ha = au.ha2.data; this.hb = au.hb2.data;\n for (let i = 0; i < H; i++) this.aux[a + i] = au.aux.data.slice(i * 34, i * 34 + 34); this.naux = b;\n }\n async block() { // the pose of frames [nb * stride, (nb + 1) * stride)\n const m = this.meta, S = m.stride, K = S + m.look, i0 = this.nb * S, v = new Float32Array(35 * K);\n for (let k = 0; k < K; k++) { if (k - S >= this.known) continue; v[34 * K + k] = 1; const a = this.aux[i0 - S + k]; if (a) for (let c = 0; c < 34; c++) v[c * K + k] = a[c]; }\n const bank = Math.min(Math.max(Math.floor((m.look - this.known + 3) / 4), 0), m.bank - 1), c = (await this.run('ctx', { v: this.t(v, [1, 35 * K]) })).c.data.slice(bank * m.hid, (bank + 1) * m.hid);\n const D = m.dim, n = this.q.length, q1 = n ? this.q[n - 1] : new Float32Array(D), q2 = n > 1 ? this.q[n - 2] : q1;\n const g = await this.run('gru', { c: this.t(c, [1, m.hid]), q1: this.t(q1, [1, D]), q2: this.t(q2, [1, D]), first: this.t(new Float32Array([n ? 0 : 1]), [1]), hx: this.t(this.hx, [2, 2, m.hid]) });\n this.hx = g.hx2.data; const h = new Float32Array(g.h.data), q = new Float32Array(D), dg = [], pr = [];\n for (let d = 0; d < D; d++) {\n const p = (await this.run('digit', { h: this.t(h, [2, m.hid]), d: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(d)]), []), guide: this.t(new Float32Array([this.guide]), []), temp: this.t(new Float32Array([this.temp]), []) })).p.data;\n let u = this.rand(), t = 0, acc = 0; for (; t < m.levels[d] - 1; t++) { acc += p[t]; if (u < acc) break; }\n const row = (d * m.Lm + t) * m.hid; for (let k = 0; k < m.hid; k++) { h[k] += this.dig[row + k]; h[m.hid + k] += this.dig[row + k]; }\n q[d] = (t - m.half[d]) / m.half[d]; if (this.record) { dg.push(t); pr.push(Array.from(p)); }\n }\n if (this.record) { this.log.digits.push(dg); this.log.probs.push(pr); }\n this.q.push(q); if (this.q.length > m.dec_blocks) this.q.shift(); const N = this.q.length, qw = new Float32Array(N * D); this.q.forEach((x, j) => qw.set(x, j * D));\n const pose = (await this.run('vqdec', { q: this.t(qw, [1, N, D]) })).pose.data, body = [0, 1, 2, 12, 13, 14];\n for (let j = 0; j < S; j++) {\n const p = pose.slice(j * 15, j * 15 + 15);\n if (this.smooth < 1) { if (!this.y1) { this.y1 = body.map(b => p[b]); this.y2 = this.y1.slice(); } body.forEach((b, k) => { this.y1[k] += this.smooth * (p[b] - this.y1[k]); this.y2[k] += this.smooth * (this.y1[k] - this.y2[k]); p[b] = this.y2[k]; }); }\n this.pose[i0 + j] = p;\n }\n this.nb++;\n }\n mute(tt) { // the silence gate's value for frame tt (frames in order)\n const upto = Math.min(this.en0 + this.en.length - 1, tt + this.wait); for (let k = Math.max(this.en0, tt - HOLD); k <= upto; k++) if (this.en[k - this.en0]) this.lastLoud = Math.max(this.lastLoud, k);\n this.gate = this.lastLoud < tt - HOLD ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; return this.quiet && this.meta.closed ? this.gate : 0;\n }\n async stepNano() {\n const m = this.meta, w = m.width, done = [], have = Math.floor(this.an / FRAME), t0 = performance.now(); if (have > this.n.e) await this.final(have);\n for (let lim = Math.min(this.n[this.hName], this.n[this.sName]); this.out < lim;) {\n const H = Math.min(8, lim - this.out), h = new Float32Array(H * w), s = new Float32Array(H * w); for (let i = 0; i < H; i++) { h.set(this.col[this.hName][this.out + i], i * w); s.set(this.col[this.sName][this.out + i], i * w); }\n const o = await this.run('out', { h: this.t(h, [H, w]), s: this.t(s, [H, w]) }), closed = m.closed;\n for (let i = 0; i < H; i++) {\n const d = new Float32Array(118), fc = new Float32Array(103); fc.set(o.expr.data.subarray(i * 100, i * 100 + 100)); fc.set(o.jaw.data.subarray(i * 3, i * 3 + 3), 100); if (this.record) this.log.face.push(Array.from(fc));\n const gt = this.mute(this.out); if (gt > 1e-3) for (let c = 0; c < 103; c++) fc[c] += gt * (closed[c] - fc[c]);\n d.set(fc.subarray(0, 100)); d.set(fc.subarray(100, 103), 103); d.set(o.rot.data.subarray(i * 3, i * 3 + 3), 106); // the head's rotation goes on the neck\n done.push({ index: this.out, data: d }); const old = this.out - 160; if (old >= 0) for (const k in this.col) delete this.col[k][old]; this.out++; this.ms.frames++;\n }\n }\n this.ms.lips += performance.now() - t0; return done;\n }\n // Runs whatever the audio pushed so far allows; returns the new frames [{index, data}] in order.\n async step() {\n if (this.nano) return this.stepNano();\n const m = this.meta, S = m.stride, done = [], have = Math.floor(this.an / FRAME); let t0 = performance.now();\n const nE = this.hop > 1 ? Math.floor((have - m.future) / this.hop) * this.hop + m.future : have;\n if (nE > this.n.e) await this.final(nE);\n const H = Math.min(nE - this.wait, this.wait === m.future ? this.n[this.sName] : 1e9) - this.nface; if (H > 0) for (let i = 0; i < H; i += 8) await this.faces(Math.min(8, H - i));\n this.ms.lips += performance.now() - t0; t0 = performance.now();\n if (this.n[this.sName] > this.naux) await this.sides();\n this.ms.heads += performance.now() - t0; t0 = performance.now();\n while (this.nb * S < this.nface && this.naux >= this.nb * S + this.known) await this.block();\n this.ms.tokens += performance.now() - t0;\n while (this.out < this.nface && this.out < this.nb * S) {\n const fr = this.face[this.out], p = this.pose[this.out], d = new Float32Array(118); d.set(fr.expr); d.set(p.subarray(0, 3), 100); d.set(fr.jaw, 103); d.set(p.subarray(3, 15), 106);\n done.push({ index: this.out, data: d }); delete this.face[this.out]; delete this.pose[this.out]; const old = this.out - 160; if (old >= 0) { delete this.aux[old]; for (const k in this.col) delete this.col[k][old]; } this.out++; this.ms.frames++;\n }\n return done;\n }\n}\n\nreturn { Engine };\n})();\n__m['arkit'] = (() => {\n// Frames as ARKit blendshape weights.\n//\n// import { LipSync, Arkit } from 'callable-lipsync';\n// const arkit = await Arkit.load({ model: 'tiny', base: '/models/arkit/' }); // in Node, leave `base` out\n// const weights = arkit.convert(frame); // Float32Array(51), each 0..1, in the order of arkit.names\n//\n// The 51 ARKit shapes are displacements of the FLAME head's vertices, so a frame's weights are the mix of them closest\n// to how far the frame's face is from the model's resting face. jawOpen comes straight from the jaw's rotation and the\n// eight eyeLook weights from the eyes'; the rest are solved from the face's shape (exactly: the problem has one answer,\n// so the Python package gives the same weights). The head, neck and chest rotations and the travel are not\n// blendshapes: apply those to your rig's bones from the frame itself.\nconst LOOK = ['eyeLookDownLeft', 'eyeLookDownRight', 'eyeLookInLeft', 'eyeLookInRight', 'eyeLookOutLeft', 'eyeLookOutRight', 'eyeLookUpLeft', 'eyeLookUpRight'];\n\nfunction rotation(x, y, z, R) { // axis-angle -> row-major 3x3\n const t = Math.hypot(x, y, z); if (t < 1e-9) { R[0] = 1; R[1] = -z; R[2] = y; R[3] = z; R[4] = 1; R[5] = -x; R[6] = -y; R[7] = x; R[8] = 1; return R; }\n const kx = x / t, ky = y / t, kz = z / t, c = Math.cos(t), s = Math.sin(t), v = 1 - c;\n R[0] = c + kx * kx * v; R[1] = kx * ky * v - kz * s; R[2] = kx * kz * v + ky * s; R[3] = ky * kx * v + kz * s; R[4] = c + ky * ky * v; R[5] = ky * kz * v - kx * s; R[6] = kz * kx * v - ky * s; R[7] = kz * ky * v + kx * s; R[8] = c + kz * kz * v; return R;\n}\n\nclass Arkit {\n // options: model 'tiny' or 'nano' (whose resting face the weights are measured from) or rest (your own frame of 118);\n // base: URL of the folder with arkit.json and arkit.bin (browser); load: your own (name) => ArrayBuffer;\n // jaw: the jaw rotation, in radians past rest, that counts as jawOpen = 1; lookRange: the same for the eyeLook weights\n static async load({ model = 'tiny', base = null, load = null, ...options } = {}) {\n if (!load) { const { loader } = await import('./index.js'); load = await loader('arkit', base); }\n const meta = JSON.parse(new TextDecoder().decode(await load('arkit.json'))); return new Arkit(meta, await load('arkit.bin'), { model, ...options });\n }\n constructor(meta, buf, { model = 'tiny', rest = null, jaw = 0.35, lookRange = 0.5, ridge = 0.01 } = {}) {\n const d = {}; for (const [k, a] of Object.entries(meta.arrays)) { const n = a.shape.reduce((x, y) => x * y, 1); d[k] = a.dtype === 'uint32' ? new Uint32Array(buf, a.offset, n) : Float64Array.from(new Float32Array(buf, a.offset, n)); }\n Object.assign(this, d); this.names = meta.names; this.index = Object.fromEntries(this.names.map((n, i) => [n, i])); this.U = meta.vertices; this.nS = meta.skin; this.P = meta.points; this.jaw = jaw; this.lookRange = lookRange;\n this.rest = Float64Array.from(rest || meta.rest[model]); const K = this.K = this.names.length, n = this.n = 3 * (this.nS + this.P), jo = this.index.jawOpen;\n this.v = new Float64Array(this.U * 3); this.R = new Float64Array(9); this.restPoints = this.points(this.rest, new Float64Array(n));\n const A = this.A = Float64Array.from(this.shapes), step = Float64Array.from(this.rest); step[103] += 0.05; const p = this.points(step, new Float64Array(n)); // jawOpen is the jaw's own rotation: the direction it starts in, from rest\n for (let k = 0; k < n; k++) A[jo * n + k] = (p[k] - this.restPoints[k]) * jaw / 0.05;\n const free = this.free = []; this.names.forEach((x, i) => { if (!LOOK.includes(x) && i !== jo) free.push(i); }); const m = this.m = free.length, H = this.H = new Float64Array(m * m); let tr = 0;\n for (let a = 0; a < K; a++) { let s = 0; for (let k = 0; k < n; k++) s += A[a * n + k] * A[a * n + k]; tr += s; }\n for (let a = 0; a < m; a++) for (let b = a; b < m; b++) { let s = 0; const X = free[a] * n, Y = free[b] * n; for (let k = 0; k < n; k++) s += A[X + k] * A[Y + k]; H[a * m + b] = H[b * m + a] = s; }\n const lam = ridge * tr / K; for (let a = 0; a < m; a++) H[a * m + a] += lam;\n this.d = new Float64Array(n); this.b = new Float64Array(m); this.w = new Float64Array(m); this.z = new Float64Array(m); this.lo = new Uint8Array(m).fill(1); this.hi = new Uint8Array(m); this.L = new Float64Array(m * m); this.rhs = new Float64Array(m); this.out = new Float32Array(K);\n }\n points(f, out) { // a frame -> the compared points in the head's frame: the skin vertices, then the control points (weighted)\n const U = this.U, v = this.v, E = this.expr, R = rotation(f[103], f[104], f[105], this.R), T = this.template, PD = this.jaw_dirs, JE = this.jaw_joint_expr, n3 = U * 3; v.set(T); let jx = this.jaw_joint[0], jy = this.jaw_joint[1], jz = this.jaw_joint[2];\n for (let i = 0; i < 100; i++) { const c = f[i]; if (c === 0) continue; const o = i * n3; for (let k = 0; k < n3; k++) v[k] += c * E[o + k]; jx += c * JE[3 * i]; jy += c * JE[3 * i + 1]; jz += c * JE[3 * i + 2]; }\n for (let p = 0; p < 9; p++) { const c = R[p] - (p % 4 === 0 ? 1 : 0); if (c === 0) continue; const o = p * n3; for (let k = 0; k < n3; k++) v[k] += c * PD[o + k]; }\n for (let u = 0; u < U; u++) { const w = this.jaw_weight[u]; if (w === 0) continue; const x = v[3 * u] - jx, y = v[3 * u + 1] - jy, z = v[3 * u + 2] - jz; v[3 * u] += w * (R[0] * x + R[1] * y + R[2] * z - x); v[3 * u + 1] += w * (R[3] * x + R[4] * y + R[5] * z - y); v[3 * u + 2] += w * (R[6] * x + R[7] * y + R[8] * z - z); }\n const nS = this.nS, S = this.skin, C = this.corners, B = this.bary, W = this.point_weight;\n for (let i = 0; i < nS; i++) for (let c = 0; c < 3; c++) out[3 * i + c] = v[3 * S[i] + c];\n for (let i = 0; i < this.P; i++) for (let c = 0; c < 3; c++) out[3 * (nS + i) + c] = W[i] * (B[3 * i] * v[3 * C[3 * i] + c] + B[3 * i + 1] * v[3 * C[3 * i + 1] + c] + B[3 * i + 2] * v[3 * C[3 * i + 2] + c]);\n return out;\n }\n box() { // the weights in 0..1 that minimise w.H.w / 2 - b.w, exactly (an active-set solve, started from where the last frame's ended; the answer does not depend on the start)\n const { H, b, w, z, lo, hi, m, L, rhs } = this, tol = 1e-9, ix = []; for (let i = 0; i < m; i++) w[i] = hi[i] ? 1 : lo[i] ? 0 : w[i];\n for (let it = 0; it < 20 * m; it++) {\n for (;;) { // the best weights with the bound ones held; walk towards them until none leaves 0..1\n ix.length = 0; for (let i = 0; i < m; i++) if (!lo[i] && !hi[i]) ix.push(i); const q = ix.length; if (!q) break;\n for (let a = 0; a < q; a++) { let s = b[ix[a]]; for (let j = 0; j < m; j++) if (lo[j] || hi[j]) s -= H[ix[a] * m + j] * w[j]; rhs[a] = s; }\n for (let a = 0; a < q; a++) for (let c = 0; c <= a; c++) { let s = H[ix[a] * m + ix[c]]; for (let k = 0; k < c; k++) s -= L[a * m + k] * L[c * m + k]; L[a * m + c] = a === c ? Math.sqrt(s) : s / L[c * m + c]; } // Cholesky\n for (let a = 0; a < q; a++) { let s = rhs[a]; for (let k = 0; k < a; k++) s -= L[a * m + k] * rhs[k]; rhs[a] = s / L[a * m + a]; }\n for (let a = q - 1; a >= 0; a--) { let s = rhs[a]; for (let k = a + 1; k < q; k++) s -= L[k * m + a] * rhs[k]; rhs[a] = s / L[a * m + a]; }\n let step = Infinity, any = false; for (let a = 0; a < q; a++) { const i = ix[a], t = rhs[a]; z[i] = t; if (t < -tol) { any = true; step = Math.min(step, w[i] / Math.max(w[i] - t, 1e-300)); } else if (t > 1 + tol) { any = true; step = Math.min(step, (1 - w[i]) / Math.max(t - w[i], 1e-300)); } }\n if (!any) { for (let a = 0; a < q; a++) w[ix[a]] = z[ix[a]]; break; }\n step = Math.max(0, step);\n for (let a = 0; a < q; a++) { const i = ix[a], t = z[i], s = t < -tol ? w[i] / Math.max(w[i] - t, 1e-300) : t > 1 + tol ? (1 - w[i]) / Math.max(t - w[i], 1e-300) : Infinity; w[i] += step * (t - w[i]); if (s <= step + 1e-12) { if (t < 0) { lo[i] = 1; w[i] = 0; } else { hi[i] = 1; w[i] = 1; } } }\n }\n let k = -1, worst = 1e-10; for (let i = 0; i < m; i++) { if (!lo[i] && !hi[i]) continue; let g = -b[i]; for (let j = 0; j < m; j++) g += H[i * m + j] * w[j]; const bad = lo[i] ? -g : g; if (bad > worst) { worst = bad; k = i; } } // a bound weight that would rather move inward\n if (k < 0) break; lo[k] = hi[k] = 0;\n }\n return w;\n }\n // A frame (118 numbers) -> its 51 weights. The returned array is reused by the next call: copy it to keep it.\n convert(f) {\n const { n, A, d, b, free, m, out } = this, jo = this.index.jawOpen, r = this.restPoints, wj = Math.min(1, Math.max(0, (f[103] - this.rest[103]) / this.jaw)), X = jo * n; this.points(f, d);\n for (let k = 0; k < n; k++) d[k] -= r[k] + wj * A[X + k]; // the jaw's turn is known; the other shapes explain what is left\n for (let a = 0; a < m; a++) { let s = 0; const o = free[a] * n; for (let k = 0; k < n; k++) s += A[o + k] * d[k]; b[a] = s; }\n const w = this.box(); out.fill(0); for (let a = 0; a < m; a++) out[free[a]] = Math.min(1, Math.max(0, w[a])); out[jo] = wj;\n const R = this.lookRange, set = (name, x) => { out[this.index[name]] = Math.min(1, Math.max(0, x / R)); }; // +x is the face's left; turning about +x looks down, about +y towards the face's left\n set('eyeLookDownLeft', f[109]); set('eyeLookUpLeft', -f[109]); set('eyeLookOutLeft', f[110]); set('eyeLookInLeft', -f[110]);\n set('eyeLookDownRight', f[112]); set('eyeLookUpRight', -f[112]); set('eyeLookInRight', f[113]); set('eyeLookOutRight', -f[113]);\n return out;\n }\n}\n\nreturn { Arkit };\n})();\n__m['resample'] = (() => {\n// A streaming resampler: audio at any rate in, 16 kHz (or any rate) out, anti-aliased by a windowed-sinc filter.\n// Output sample j is the input at time j / outRate from the stream's first sample: no delay, so timestamps stay exact\n// (the output for a moment is ready once the input is `reach` seconds past it). The same input cut into different\n// chunks gives the same output.\n//\n// const r = new Resampler(48000); // to 16 kHz\n// const y = r.push(block); // Float32Array: the output samples this block completes (possibly none)\nclass Resampler {\n constructor(inRate, outRate = 16000, { zeros = 16, phases = 256 } = {}) {\n this.step = inRate / outRate; this.same = inRate === outRate; // input samples per output sample\n const down = Math.min(1, outRate / inRate), fc = 0.45 * down; // cutoff, cycles per input sample: 0.9 of the lower Nyquist\n this.R = zeros / down; this.P = phases; this.reach = this.R / inRate; // the kernel's half-width in input samples\n const n = Math.ceil(this.R * phases) + 2, T = this.table = new Float64Array(n);\n for (let k = 0; k < n; k++) { const x = k / phases; if (x >= this.R) break; const w = 0.5 + 0.5 * Math.cos(Math.PI * x / this.R), a = 2 * Math.PI * fc * x; T[k] = w * (x === 0 ? 2 * fc : Math.sin(a) / (Math.PI * x)); }\n this.buf = new Float32Array(4096); this.base = 0; this.n = 0; this.j = 0; // input samples [base, n) are held; j: the next output sample\n }\n push(x) {\n if (this.same) { this.n += x.length; this.j += x.length; return Float32Array.from(x); }\n const keep = Math.min(this.n, Math.max(this.base, Math.floor(this.j * this.step - this.R) - 1)), held = this.n - keep; // drop the input no output needs any more\n if (keep > this.base || held + x.length > this.buf.length) {\n const size = Math.max(this.buf.length, 2 ** Math.ceil(Math.log2(held + x.length))), b = size > this.buf.length ? new Float32Array(size) : this.buf;\n if (b === this.buf) b.copyWithin(0, keep - this.base, this.n - this.base);\n else b.set(this.buf.subarray(keep - this.base, this.n - this.base));\n this.buf = b; this.base = keep;\n }\n this.buf.set(x, this.n - this.base); this.n += x.length;\n const out = [], { buf, base, step, R, P, table } = this;\n for (;;) {\n const p = this.j * step, hi = Math.floor(p + R); if (hi >= this.n) break;\n let s = 0, ws = 0;\n for (let i = Math.ceil(p - R); i <= hi; i++) {\n const d = Math.abs(i - p) * P, k = Math.floor(d), h = table[k] + (d - k) * (table[k + 1] - table[k]); ws += h; if (i >= 0) s += h * buf[i - base];\n }\n out.push(s / ws); this.j++;\n }\n return Float32Array.from(out);\n }\n}\n\nreturn { Resampler };\n})();\n__m['index'] = (() => {\n// callable-lipsync: 16 kHz speech in, FLAME 2023 Open frames out at 25 fps. Runs on onnxruntime-web, in a page, a worker or Node.\n//\n// import * as ort from 'onnxruntime-web';\n// import { LipSync } from 'callable-lipsync';\n// const model = await LipSync.load(ort, { model: 'tiny', base: '/models/tiny/' }); // in Node, leave `base` out\n// const frames = await model.process(samples); // Float32Array, 16 kHz mono -> [Float32Array(118), ...]\nconst { Engine } = __m['engine'];\nconst { Arkit } = __m['arkit'];\n\nconst VERSION = '0.3.1'; // this package's version (kept equal to package.json's by the tests)\nconst SAMPLE_RATE = 16000, FPS = 25, FRAME = 640;\n// what the 118 numbers of a frame are: [first, one past the last]. Rotations are axis-angle, in radians.\nconst LAYOUT = { expression: [0, 100], chest: [100, 103], jaw: [103, 106], neck: [106, 109], leftEye: [109, 112], rightEye: [112, 115], travel: [115, 118] };\n// seconds of audio ahead of a frame -> the engine's settings; `ready`: frames after a frame's own start until it is computed\nconst AHEAD = { 0.64: { known: 12, wait: 4, ready: 16 }, 0.48: { known: 8, wait: 4, ready: 12 }, 0.32: { known: 4, wait: 4, ready: 8 }, 0.16: { known: 0, wait: 4, ready: 5 }, 0.08: { known: -2, wait: 2, ready: 3 }, 0: { known: -4, wait: 0, ready: 1 } };\n\n// A function that fetches a model's files ('tiny', 'nano', or 'arkit' for the blendshape converter's data): from `base` (a URL ending in /), or, in Node, from this package's models/ folder.\nasync function loader(model = 'tiny', base = null) {\n if (base) return async name => { const r = await fetch(base + name); if (!r.ok) throw new Error(`callable-lipsync: ${base + name}: ${r.status}`); return r.arrayBuffer(); };\n if (typeof process === 'undefined' || !process.versions?.node) throw new Error('callable-lipsync: in a browser, pass { base } (the URL of the folder with the model\\'s files)');\n const fs = await import(/* @vite-ignore */ /* webpackIgnore: true */ 'node:fs/promises'), dir = new URL(`../models/${model}/`, import.meta.url);\n return async name => { const b = await fs.readFile(new URL(name, dir)); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };\n}\n\nclass LipSync {\n // ort: onnxruntime-web (or anything with the same InferenceSession and Tensor). options:\n // model 'tiny' (lips, jaw, face, blinks, gaze, head, neck, upper body) or 'nano' (lips, jaw, face, head)\n // base URL of the folder with the model's files (browser); load: your own (name) => ArrayBuffer\n // ahead, seed, expressiveness: see reset(); session: options for InferenceSession.create\n static async load(ort, { model = 'tiny', base = null, load = null, session = null, ...settings } = {}) {\n const m = new LipSync(); m.engine = await Engine.create(ort, load || await loader(model, base), session ? { session } : {}); m.nano = m.engine.nano; m.ahead = 0.64; m.expressiveness = 2; m.reset(settings); return m;\n }\n // Start a new stream. ahead: seconds of audio the model may hear before a frame is due (0.64, 0.48, 0.32, 0.16, 0.08, 0;\n // nano always uses 0.16). seed: same seed and audio give the same motion (default: a new one). expressiveness: 1 to 3 (tiny).\n reset({ ahead = this.ahead, seed = null, expressiveness = this.expressiveness } = {}) {\n if (this.nano) ahead = 0.16; const mode = AHEAD[ahead]; if (!mode) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', '));\n this.ahead = +ahead; this.expressiveness = expressiveness; this.delayFrames = mode.ready; this.seed = seed ?? (Math.random() * 2 ** 31) | 0; this.samples = 0;\n this.engine.reset({ known: mode.known, wait: mode.wait, guide: expressiveness, seed: this.seed });\n }\n // Feed 16 kHz mono samples (any length); resolves to the frames it settled, in order (possibly none).\n async process(samples) { this.samples += samples.length; this.engine.push(samples); return (await this.engine.step()).map(f => f.data); }\n // The frames still owed for the audio fed so far (the model waits for audio ahead; this feeds it silence).\n async flush() { const want = Math.floor(this.samples / FRAME) - this.engine.out; if (want <= 0) return []; return (await this.process(new Float32Array((this.delayFrames + 12) * FRAME))).slice(0, want); }\n}\n\nreturn { Engine, Arkit, VERSION, SAMPLE_RATE, FPS, FRAME, LAYOUT, AHEAD, loader, LipSync };\n})();\n__m['web-worker'] = (() => {\n// The worker half of LipSyncNode (web.js): resamples the captured audio to 16 kHz, runs the model on one WebAssembly\n// thread and posts the frames (and their ARKit weights) back to the page, off its main thread.\n//\n// From the page: init (where onnxruntime and the models are), load (a model), and a MessagePort from the capture\n// worklet that brings start (a new stream: its settings and the audio clock's sample index where it begins), audio\n// (chunks of it) and set (expressiveness). The stream's messages run one after another; loading a model runs beside them.\n// onnxruntime-web: `ort` from the page, else (run as a module file by a bundler) its own package, else the CDN. Bundling\n// this file therefore needs onnxruntime-web 1.19 or newer installed (its 'onnxruntime-web/wasm' entry).\nconst { LipSync, AHEAD } = __m['index'];\nconst { Arkit } = __m['arkit'];\nconst { Resampler } = __m['resample'];\n\nconst ORT_CDN = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.wasm.min.mjs';\nconst MAX_GAP = 1, BEHIND = 0.5, CAUGHT_UP = 0.05; // seconds of missing audio filled with silence (past that the stream starts over); seconds of audio waiting before it is skipped, down to this much\nlet ort = null, cfg = null, queue = Promise.resolve(), s = null, newest = { stream: -1, end: 0 }; // s: the stream being run; newest: the end of the latest audio that came in\nconst models = {}, arkits = {}; let arkitFiles = null; // the ARKit converter's files, fetched once for all models\n\nasync function runtime() {\n if (ort) return ort;\n let o;\n if (cfg.ort) o = await import(/* @vite-ignore */ /* webpackIgnore: true */ cfg.ort);\n else { try { o = await import('onnxruntime-web/wasm'); } catch (e) { o = await import(/* @vite-ignore */ /* webpackIgnore: true */ ORT_CDN); } } // a bundler resolves the package; a plain page cannot, so the CDN\n o = o.default && o.default.InferenceSession ? o.default : o;\n if (!o.InferenceSession || !o.env || !o.env.wasm) throw new Error('callable-lipsync: ' + (cfg.ort || 'that module') + ' is not onnxruntime-web');\n o.env.wasm.numThreads = 1; if (cfg.wasmPaths) o.env.wasm.wasmPaths = cfg.wasmPaths;\n return (ort = o); // kept only once it works: a failure can be tried again\n}\nfunction fetcher(dir, model) { // (name) => ArrayBuffer from dir, reporting the download's progress\n let bytes = 0, total = 0;\n return async (name) => {\n const r = await fetch(dir + name); if (!r.ok) throw new Error(`callable-lipsync: ${dir + name}: ${r.status}`); const b = await r.arrayBuffer();\n if (name === 'meta.json') total = JSON.parse(new TextDecoder().decode(b)).bytes || 0; else bytes += b.byteLength;\n if (model) postMessage({ type: 'progress', model, bytes, total }); return b;\n };\n}\nfunction load(model) { // the model (and its ARKit converter), once\n if (models[model]) return models[model];\n models[model] = (async () => {\n const t0 = performance.now(), o = await runtime(), lip = await LipSync.load(o, { model, load: fetcher(cfg.base + model + '/', model), seed: 0 });\n const ms = performance.now() - t0; // the model's own start-up\n await Promise.race([converter(model), new Promise((r) => setTimeout(r, 3000))]); // `names` usually comes with 'loaded'; a slow download sends them later\n postMessage({ type: 'loaded', model, ms, bytes: lip.engine.bytes, weights: lip.engine.meta.weights || 0, names: arkits[model] ? arkits[model].names : null });\n return lip;\n })();\n models[model].catch(() => { delete models[model]; delete arkits[model]; }); // a failed download can be tried again\n return models[model];\n}\nconst noArkit = {}, warned = {}, converting = {}; // models whose converter could not be built from its files (not tried again)\nfunction converter(model) { // the model's ARKit converter (with arkit on), built once at a time; a failure costs only the weights\n if (!cfg.arkit || arkits[model] || noArkit[model]) return Promise.resolve();\n if (!converting[model]) converting[model] = build(model).finally(() => { delete converting[model]; });\n return converting[model];\n}\nasync function build(model) {\n let files;\n try {\n if (!arkitFiles) { const get = fetcher(cfg.base + 'arkit/'); arkitFiles = Promise.all([get('arkit.json'), get('arkit.bin')]); arkitFiles.catch(() => { arkitFiles = null; }); }\n files = await arkitFiles;\n } catch (e) { // a download that failed: the next stream tries again (warned once)\n if (!warned[model]) postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights for now: ' + text(e) }); warned[model] = true; return;\n }\n try { arkits[model] = new Arkit(JSON.parse(new TextDecoder().decode(files[0])), files[1], { model }); warned[model] = false; postMessage({ type: 'names', names: arkits[model].names }); }\n catch (e) { noArkit[model] = true; postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights: ' + text(e) }); } // bad data: not tried again\n}\nasync function begin(m, frame) { // a stream from the audio clock's sample `frame` on\n const lip = await load(m.model); lip.reset({ ahead: m.ahead, seed: m.seed, expressiveness: m.expressiveness });\n converter(m.model); // in the background: the weights join the frames once it is there\n s = { stream: m.stream, m, lip, start: frame, rate: m.rate, next: frame, r: new Resampler(m.rate), first: 0 };\n}\nlet ping = null, woke = null;\nfunction yieldTask() {\n if (!ping) { ping = new MessageChannel(); ping.port1.onmessage = () => { const w = woke; woke = null; if (w) w(); }; } // made when first needed\n return new Promise((r) => { woke = r; ping.port2.postMessage(0); });\n} // a macrotask: the audio messages waiting are dispatched first, so `newest` is current\nasync function audio(m) {\n await yieldTask();\n if (!s || m.stream !== s.stream || m.stream !== newest.stream) return; // a newer stream is on its way: this one is over\n if (newest.end - m.frame - m.samples.length > (s.dropped ? CAUGHT_UP : BEHIND) * s.rate) { s.dropped = true; return; } // slower than real time: skip to (nearly) the newest audio\n const gap = m.frame - s.next;\n if (s.dropped || gap > MAX_GAP * s.rate || gap < 0) { const n = (s.restarts || 0) + 1, m0 = s.m; await begin({ ...m0, seed: m0.seed == null ? null : (m0.seed + n) | 0 }, m.frame); s.m = m0; s.restarts = n; } // audio skipped, or the clock jumped: start over from here (a new draw of the head's motion)\n else if (gap > 0) await feed(new Float32Array(gap));\n await feed(m.samples);\n}\nasync function feed(x) {\n s.next += x.length; const t0 = performance.now(), frames = await s.lip.process(s.r.push(x)), n = frames.length; if (!n) return;\n const ak = arkits[s.m.model], data = new Float32Array(n * 118), w = ak ? new Float32Array(n * 51) : null;\n frames.forEach((f, i) => { data.set(f, i * 118); if (w) w.set(ak.convert(f), i * 51); }); const ms = performance.now() - t0; // the model and the ARKit weights\n postMessage({ type: 'frames', stream: s.stream, start: s.start, rate: s.rate, first: s.first, count: n, data, weights: w, ms, restarts: s.restarts || 0 }, w ? [data.buffer, w.buffer] : [data.buffer]); s.first += n;\n}\nfunction stream(m) { // the capture worklet's messages, in order\n if (m.type === 'stop') { if (s && s.stream === m.stream) s = null; return; }\n if (m.type === 'set') { if (s && m.expressiveness != null) { s.lip.expressiveness = s.m.expressiveness = m.expressiveness; s.lip.engine.guide = m.expressiveness; } return; }\n if (m.type === 'start') { if (!AHEAD[m.ahead]) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', ')); return begin(m, m.frame); }\n if (m.type === 'audio') return audio(m);\n}\nconst text = (e) => (e && e.message && !String(e.stack || '').includes(e.message) ? e.message + '\\n' : '') + String((e && e.stack) || e); // Firefox and Safari leave the message out of the stack\npostMessage({ type: 'hello' }); // started: from now on an uncaught error is not fatal\nself.onmessage = (e) => {\n const m = e.data;\n if (m.type === 'init') cfg = m;\n else if (m.type === 'load') load(m.model).then(() => {}, (err) => postMessage({ type: 'error', model: m.model, message: text(err) }));\n else if (m.type === 'port') m.port.onmessage = (ev) => {\n const a = ev.data;\n if (a.type === 'start') newest = { stream: a.stream, end: a.frame };\n else if (a.type === 'stop' && a.stream === newest.stream) newest = { stream: -1, end: 0 }; // its queued audio is dropped at once\n else if (a.type === 'audio' && a.stream === newest.stream && a.frame + a.samples.length > newest.end) newest.end = a.frame + a.samples.length;\n queue = queue.then(() => stream(a)).catch((err) => { if (s && s.stream === a.stream) s = null; postMessage({ type: 'error', stream: a.stream, message: text(err) }); }); // a failed stream stops\n };\n};\n\nreturn { };\n})();";
|
|
3
3
|
export const WORKLET = "// The AudioWorklet half of LipSyncNode (web.js): passes its input, mixed to mono by the node, to the worker that runs the\n// model, every 20 ms (at any sample rate), each chunk tagged with the audio clock's sample index of its first sample. Self-contained (no\n// imports), so a bundler can copy it as it is.\nclass CallableLipSyncCapture extends AudioWorkletProcessor {\n constructor() {\n super(); this.to = null; this.on = false; this.pending = null; this.alive = true; this.stream = 0; this.size = Math.max(128, Math.round(sampleRate * 0.02)); this.buf = null; this.n = 0; this.t = 0;\n this.port.onmessage = (e) => {\n const m = e.data;\n if (m.type === 'port') this.to = m.port;\n else if (m.type === 'start') { this.send(); this.pending = m; this.on = false; } // the stream starts with the next block\n else if (m.type === 'stop') { this.send(); this.pending = null; if (this.on && this.to) this.to.postMessage({ type: 'stop', stream: this.stream }); this.on = false; } // the worker drops what it still holds of the stream\n else if (m.type === 'set') { if (this.pending) this.pending.expressiveness = m.expressiveness; else if (this.to) this.to.postMessage({ ...m, stream: this.stream }); } // in order with the stream's start\n else if (m.type === 'close') { this.send(); this.alive = false; this.on = false; if (this.to) this.to.close(); }\n };\n }\n send() {\n if (this.on && this.n && this.to) { const x = this.buf.subarray(0, this.n); this.to.postMessage({ type: 'audio', stream: this.stream, frame: this.t, samples: x }, [x.buffer]); }\n this.buf = null; this.n = 0;\n }\n process(inputs) {\n if (!this.alive) return false;\n if (this.pending && this.to) { const m = this.pending; this.pending = null; this.stream = m.stream; this.on = true; this.to.postMessage({ ...m, frame: currentFrame, rate: sampleRate }); }\n if (!this.on) return true;\n const ch = inputs[0] && inputs[0][0], len = ch ? ch.length : (typeof renderQuantumSize !== 'undefined' ? renderQuantumSize : 128);\n if (!this.buf) { this.buf = new Float32Array(Math.max(this.size, len)); this.t = currentFrame; }\n if (ch) this.buf.set(ch, this.n); else this.buf.fill(0, this.n, this.n + len); // nothing connected: silence\n this.n += len; if (this.n >= this.size || this.n + len > this.buf.length) this.send();\n return true;\n }\n}\nregisterProcessor('callable-lipsync-capture', CallableLipSyncCapture);\n";
|
package/package.json
CHANGED