callable-lipsync 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -13
- package/js/engine.js +5 -4
- package/js/index.d.ts +1 -0
- package/js/index.js +2 -1
- package/js/resample.js +38 -0
- package/js/talkinghead.d.ts +13 -0
- package/js/talkinghead.js +134 -0
- package/js/web-capture.js +31 -0
- package/js/web-inline.js +3 -0
- package/js/web-worker.js +109 -0
- package/js/web.d.ts +71 -0
- package/js/web.js +174 -0
- package/models/arkit/arkit.json +206 -206
- package/models/nano/fe.onnx +0 -0
- package/models/nano/meta.json +107 -107
- package/models/nano/out.onnx +0 -0
- package/models/nano/s0.onnx +0 -0
- package/models/nano/s1.onnx +0 -0
- package/models/nano/t0.onnx +0 -0
- package/models/nano/t1.onnx +0 -0
- package/models/nano/t2.onnx +0 -0
- package/models/nano/t3.onnx +0 -0
- package/models/nano/t4.onnx +0 -0
- package/models/tiny/face.onnx +0 -0
- package/models/tiny/meta.json +104 -104
- package/models/tiny/open.onnx +0 -0
- package/package.json +6 -2
package/js/web-inline.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
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})();";
|
|
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/js/web-worker.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// The worker half of LipSyncNode (web.js): resamples the captured audio to 16 kHz, runs the model on one WebAssembly
|
|
2
|
+
// thread and posts the frames (and their ARKit weights) back to the page, off its main thread.
|
|
3
|
+
//
|
|
4
|
+
// From the page: init (where onnxruntime and the models are), load (a model), and a MessagePort from the capture
|
|
5
|
+
// worklet that brings start (a new stream: its settings and the audio clock's sample index where it begins), audio
|
|
6
|
+
// (chunks of it) and set (expressiveness). The stream's messages run one after another; loading a model runs beside them.
|
|
7
|
+
// onnxruntime-web: `ort` from the page, else (run as a module file by a bundler) its own package, else the CDN. Bundling
|
|
8
|
+
// this file therefore needs onnxruntime-web 1.19 or newer installed (its 'onnxruntime-web/wasm' entry).
|
|
9
|
+
import { LipSync, AHEAD } from './index.js';
|
|
10
|
+
import { Arkit } from './arkit.js';
|
|
11
|
+
import { Resampler } from './resample.js';
|
|
12
|
+
|
|
13
|
+
const ORT_CDN = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.wasm.min.mjs';
|
|
14
|
+
const 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
|
|
15
|
+
let 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
|
|
16
|
+
const models = {}, arkits = {}; let arkitFiles = null; // the ARKit converter's files, fetched once for all models
|
|
17
|
+
|
|
18
|
+
async function runtime() {
|
|
19
|
+
if (ort) return ort;
|
|
20
|
+
let o;
|
|
21
|
+
if (cfg.ort) o = await import(/* @vite-ignore */ /* webpackIgnore: true */ cfg.ort);
|
|
22
|
+
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
|
|
23
|
+
o = o.default && o.default.InferenceSession ? o.default : o;
|
|
24
|
+
if (!o.InferenceSession || !o.env || !o.env.wasm) throw new Error('callable-lipsync: ' + (cfg.ort || 'that module') + ' is not onnxruntime-web');
|
|
25
|
+
o.env.wasm.numThreads = 1; if (cfg.wasmPaths) o.env.wasm.wasmPaths = cfg.wasmPaths;
|
|
26
|
+
return (ort = o); // kept only once it works: a failure can be tried again
|
|
27
|
+
}
|
|
28
|
+
function fetcher(dir, model) { // (name) => ArrayBuffer from dir, reporting the download's progress
|
|
29
|
+
let bytes = 0, total = 0;
|
|
30
|
+
return async (name) => {
|
|
31
|
+
const r = await fetch(dir + name); if (!r.ok) throw new Error(`callable-lipsync: ${dir + name}: ${r.status}`); const b = await r.arrayBuffer();
|
|
32
|
+
if (name === 'meta.json') total = JSON.parse(new TextDecoder().decode(b)).bytes || 0; else bytes += b.byteLength;
|
|
33
|
+
if (model) postMessage({ type: 'progress', model, bytes, total }); return b;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function load(model) { // the model (and its ARKit converter), once
|
|
37
|
+
if (models[model]) return models[model];
|
|
38
|
+
models[model] = (async () => {
|
|
39
|
+
const t0 = performance.now(), o = await runtime(), lip = await LipSync.load(o, { model, load: fetcher(cfg.base + model + '/', model), seed: 0 });
|
|
40
|
+
const ms = performance.now() - t0; // the model's own start-up
|
|
41
|
+
await Promise.race([converter(model), new Promise((r) => setTimeout(r, 3000))]); // `names` usually comes with 'loaded'; a slow download sends them later
|
|
42
|
+
postMessage({ type: 'loaded', model, ms, bytes: lip.engine.bytes, weights: lip.engine.meta.weights || 0, names: arkits[model] ? arkits[model].names : null });
|
|
43
|
+
return lip;
|
|
44
|
+
})();
|
|
45
|
+
models[model].catch(() => { delete models[model]; delete arkits[model]; }); // a failed download can be tried again
|
|
46
|
+
return models[model];
|
|
47
|
+
}
|
|
48
|
+
const noArkit = {}, warned = {}, converting = {}; // models whose converter could not be built from its files (not tried again)
|
|
49
|
+
function converter(model) { // the model's ARKit converter (with arkit on), built once at a time; a failure costs only the weights
|
|
50
|
+
if (!cfg.arkit || arkits[model] || noArkit[model]) return Promise.resolve();
|
|
51
|
+
if (!converting[model]) converting[model] = build(model).finally(() => { delete converting[model]; });
|
|
52
|
+
return converting[model];
|
|
53
|
+
}
|
|
54
|
+
async function build(model) {
|
|
55
|
+
let files;
|
|
56
|
+
try {
|
|
57
|
+
if (!arkitFiles) { const get = fetcher(cfg.base + 'arkit/'); arkitFiles = Promise.all([get('arkit.json'), get('arkit.bin')]); arkitFiles.catch(() => { arkitFiles = null; }); }
|
|
58
|
+
files = await arkitFiles;
|
|
59
|
+
} catch (e) { // a download that failed: the next stream tries again (warned once)
|
|
60
|
+
if (!warned[model]) postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights for now: ' + text(e) }); warned[model] = true; return;
|
|
61
|
+
}
|
|
62
|
+
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 }); }
|
|
63
|
+
catch (e) { noArkit[model] = true; postMessage({ type: 'warning', message: 'callable-lipsync: no ARKit weights: ' + text(e) }); } // bad data: not tried again
|
|
64
|
+
}
|
|
65
|
+
async function begin(m, frame) { // a stream from the audio clock's sample `frame` on
|
|
66
|
+
const lip = await load(m.model); lip.reset({ ahead: m.ahead, seed: m.seed, expressiveness: m.expressiveness });
|
|
67
|
+
converter(m.model); // in the background: the weights join the frames once it is there
|
|
68
|
+
s = { stream: m.stream, m, lip, start: frame, rate: m.rate, next: frame, r: new Resampler(m.rate), first: 0 };
|
|
69
|
+
}
|
|
70
|
+
let ping = null, woke = null;
|
|
71
|
+
function yieldTask() {
|
|
72
|
+
if (!ping) { ping = new MessageChannel(); ping.port1.onmessage = () => { const w = woke; woke = null; if (w) w(); }; } // made when first needed
|
|
73
|
+
return new Promise((r) => { woke = r; ping.port2.postMessage(0); });
|
|
74
|
+
} // a macrotask: the audio messages waiting are dispatched first, so `newest` is current
|
|
75
|
+
async function audio(m) {
|
|
76
|
+
await yieldTask();
|
|
77
|
+
if (!s || m.stream !== s.stream || m.stream !== newest.stream) return; // a newer stream is on its way: this one is over
|
|
78
|
+
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
|
|
79
|
+
const gap = m.frame - s.next;
|
|
80
|
+
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)
|
|
81
|
+
else if (gap > 0) await feed(new Float32Array(gap));
|
|
82
|
+
await feed(m.samples);
|
|
83
|
+
}
|
|
84
|
+
async function feed(x) {
|
|
85
|
+
s.next += x.length; const t0 = performance.now(), frames = await s.lip.process(s.r.push(x)), n = frames.length; if (!n) return;
|
|
86
|
+
const ak = arkits[s.m.model], data = new Float32Array(n * 118), w = ak ? new Float32Array(n * 51) : null;
|
|
87
|
+
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
|
|
88
|
+
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;
|
|
89
|
+
}
|
|
90
|
+
function stream(m) { // the capture worklet's messages, in order
|
|
91
|
+
if (m.type === 'stop') { if (s && s.stream === m.stream) s = null; return; }
|
|
92
|
+
if (m.type === 'set') { if (s && m.expressiveness != null) { s.lip.expressiveness = s.m.expressiveness = m.expressiveness; s.lip.engine.guide = m.expressiveness; } return; }
|
|
93
|
+
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); }
|
|
94
|
+
if (m.type === 'audio') return audio(m);
|
|
95
|
+
}
|
|
96
|
+
const 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
|
|
97
|
+
postMessage({ type: 'hello' }); // started: from now on an uncaught error is not fatal
|
|
98
|
+
self.onmessage = (e) => {
|
|
99
|
+
const m = e.data;
|
|
100
|
+
if (m.type === 'init') cfg = m;
|
|
101
|
+
else if (m.type === 'load') load(m.model).then(() => {}, (err) => postMessage({ type: 'error', model: m.model, message: text(err) }));
|
|
102
|
+
else if (m.type === 'port') m.port.onmessage = (ev) => {
|
|
103
|
+
const a = ev.data;
|
|
104
|
+
if (a.type === 'start') newest = { stream: a.stream, end: a.frame };
|
|
105
|
+
else if (a.type === 'stop' && a.stream === newest.stream) newest = { stream: -1, end: 0 }; // its queued audio is dropped at once
|
|
106
|
+
else if (a.type === 'audio' && a.stream === newest.stream && a.frame + a.samples.length > newest.end) newest.end = a.frame + a.samples.length;
|
|
107
|
+
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
|
|
108
|
+
};
|
|
109
|
+
};
|
package/js/web.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ModelName } from './index.js';
|
|
2
|
+
export interface LipSyncNodeOptions {
|
|
3
|
+
model?: ModelName;
|
|
4
|
+
/** Seconds of audio the model hears before a frame is due. More: better head motion, longer delay. Default 0.16. nano ignores it (keeping it for a switch to tiny) and always uses 0.16; `delay` shows what is in effect. */
|
|
5
|
+
ahead?: 0.64 | 0.48 | 0.32 | 0.16 | 0.08 | 0;
|
|
6
|
+
seed?: number | null;
|
|
7
|
+
/** 1 to 3 (tiny): how strongly head and eyes react to the speech. Default 2. */
|
|
8
|
+
expressiveness?: number;
|
|
9
|
+
/** true (default): the audio is heard through `output`, frames follow it. false: a microphone or audio not played here. */
|
|
10
|
+
playback?: boolean;
|
|
11
|
+
/** Also compute the 51 ARKit weights (default true). */
|
|
12
|
+
arkit?: boolean;
|
|
13
|
+
/** Seconds added to the delay for the computation, 0 to 1 (default 0.08). */
|
|
14
|
+
margin?: number;
|
|
15
|
+
/** URL of the folder with tiny/, nano/ and arkit/, relative to the page (default: this version's models on the jsDelivr CDN). */
|
|
16
|
+
base?: string | URL;
|
|
17
|
+
/** URL of onnxruntime-web's ort.wasm.min.mjs, relative to the page (default: the jsDelivr CDN). */
|
|
18
|
+
ort?: string | URL;
|
|
19
|
+
/** Where onnxruntime-web's .wasm files are: with `ort` (the same version), or for a `worker` that bundles onnxruntime-web. */
|
|
20
|
+
wasmPaths?: string | URL | Record<string, string | URL>;
|
|
21
|
+
/** URLs of web-worker.js and web-capture.js (exported as callable-lipsync/web-worker and /web-capture), to run files instead of
|
|
22
|
+
* the built-in code started from blob: URLs, e.g. under a Content-Security-Policy without blob: (then serve them from the page's
|
|
23
|
+
* origin). A web-worker.js run through a bundler also uses the bundler's onnxruntime-web. */
|
|
24
|
+
worker?: string | URL;
|
|
25
|
+
worklet?: string | URL;
|
|
26
|
+
onprogress?: (p: { model: ModelName; bytes: number; total: number }) => void;
|
|
27
|
+
/** Set from the start, so they also see warnings and stream errors inside create() (a failed create() itself rejects). */
|
|
28
|
+
onerror?: (err: Error) => void;
|
|
29
|
+
onwarning?: (err: Error) => void;
|
|
30
|
+
/** Start the stream at once (default true; else the model only loads). */
|
|
31
|
+
start?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export interface ModelInfo { model: ModelName; ms: number; bytes: number; weights: number; names: string[] | null }
|
|
34
|
+
export declare class LipSyncNode {
|
|
35
|
+
/** A real-time AudioContext (for a recording, use LipSync). */
|
|
36
|
+
static create(ctx: AudioContext, options?: LipSyncNodeOptions): Promise<LipSyncNode>;
|
|
37
|
+
readonly ctx: AudioContext;
|
|
38
|
+
/** Connect the speech here. */
|
|
39
|
+
readonly input: GainNode;
|
|
40
|
+
/** The same audio, `delay` seconds later: play this one. */
|
|
41
|
+
readonly output: DelayNode;
|
|
42
|
+
/** Seconds between the audio at `input` and its frame. */
|
|
43
|
+
readonly delay: number;
|
|
44
|
+
readonly model: ModelName; readonly ahead: number; readonly seed: number | null; readonly expressiveness: number; readonly playback: boolean;
|
|
45
|
+
/** The ARKit blendshape names, in the order of weights(). */
|
|
46
|
+
readonly names: string[] | null;
|
|
47
|
+
readonly running: boolean;
|
|
48
|
+
/** ms: compute time in all, frames: frames made, late: frames not ready when due, restarts: times the stream started over
|
|
49
|
+
* after falling behind (each restart draws a new head motion, seed + n with a fixed seed). */
|
|
50
|
+
readonly stats: { ms: number; frames: number; late: number; restarts: number };
|
|
51
|
+
/** The stream stopped or the worker failed. */
|
|
52
|
+
onerror: ((err: Error) => void) | null;
|
|
53
|
+
/** Something is missing but it runs, e.g. no ARKit weights (default: console.warn). */
|
|
54
|
+
onwarning: ((err: Error) => void) | null;
|
|
55
|
+
onprogress: ((p: { model: ModelName; bytes: number; total: number }) => void) | null;
|
|
56
|
+
load(model: ModelName): Promise<ModelInfo>;
|
|
57
|
+
/** A new stream (head motion and blinks drawn anew, unless a fixed `seed` repeats them; frame() and weights() give null until its first frames; a new `ahead` changes the output's delay at once). Resolves to true once running,
|
|
58
|
+
* false if a later start()/stop() replaced it; rejects (the old stream goes on) if the model fails to load. */
|
|
59
|
+
start(options?: Pick<LipSyncNodeOptions, 'model' | 'ahead' | 'seed' | 'expressiveness' | 'playback'>): Promise<boolean>;
|
|
60
|
+
stop(): void;
|
|
61
|
+
set(options: { expressiveness?: number }): void;
|
|
62
|
+
/** The audio clock's time of what is heard now (playback) or just came in. */
|
|
63
|
+
now(): number;
|
|
64
|
+
/** The FLAME frame (118 numbers) for what is heard now, null before the first; the array is reused. With a `time`: that moment's frame as a new array, or null if it is not there (not computed yet, or already dropped). */
|
|
65
|
+
frame(time?: number): Float32Array | null;
|
|
66
|
+
/** Its 51 ARKit weights, null before the first (or with arkit: false); like frame(). A worker restart after falling behind
|
|
67
|
+
* holds the last face until the new stream's first frame. */
|
|
68
|
+
weights(time?: number): Float32Array | null;
|
|
69
|
+
/** Stop for good: the worker ends, pending load()/start() calls reject. */
|
|
70
|
+
dispose(): void;
|
|
71
|
+
}
|
package/js/web.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// callable-lipsync on any Web Audio source: connect speech to `input`, play `output` (the same audio, delayed by the
|
|
2
|
+
// time the model needs), and each animation frame ask for the face that goes with what is being heard.
|
|
3
|
+
//
|
|
4
|
+
// import { LipSyncNode } from 'callable-lipsync/web';
|
|
5
|
+
// const lip = await LipSyncNode.create(ctx, { model: 'tiny' });
|
|
6
|
+
// speech.connect(lip.input); lip.output.connect(ctx.destination);
|
|
7
|
+
// function draw() { const w = lip.weights(); /* 51 ARKit weights, lip.names */ const f = lip.frame(); /* FLAME frame, 118 */ requestAnimationFrame(draw); }
|
|
8
|
+
// requestAnimationFrame(draw);
|
|
9
|
+
//
|
|
10
|
+
// A microphone, or any audio nobody hears through this page: connect it to `input`, leave `output` alone, and create it
|
|
11
|
+
// with { playback: false, ahead: 0 } (no audio ahead: the face follows the voice about 0.16 s behind it).
|
|
12
|
+
//
|
|
13
|
+
// The model runs in a worker on one WebAssembly thread; an AudioWorklet passes it the audio. Both start from code built
|
|
14
|
+
// into this module (web-inline.js), so nothing needs to be served beside it. By default the model files and
|
|
15
|
+
// onnxruntime-web come from the jsDelivr CDN (this package's version); `base` and `ort` point them elsewhere.
|
|
16
|
+
import { AHEAD, FPS, VERSION } from './index.js';
|
|
17
|
+
import { WORKER, WORKLET } from './web-inline.js';
|
|
18
|
+
|
|
19
|
+
const CDN = `https://cdn.jsdelivr.net/npm/callable-lipsync@${VERSION}/models/`, worklets = new WeakMap(); // AudioContext -> its addModule promise (one capture module per context)
|
|
20
|
+
const MOST = (AHEAD[0.64].ready + 1) / FPS; // the longest delay before the margin
|
|
21
|
+
|
|
22
|
+
function absolute(url) { return url == null ? null : new URL(String(url), typeof document !== 'undefined' ? document.baseURI : location.href).href; }
|
|
23
|
+
function blob(code) { return URL.createObjectURL(new Blob([code], { type: 'text/javascript' })); }
|
|
24
|
+
function workerFrom(url) { // [worker, blob URL to free or null]: a module worker from a URL; from another origin (a CDN) through a blob: stub that imports it
|
|
25
|
+
if (new URL(url).origin === location.origin) return [new Worker(url, { type: 'module' }), null];
|
|
26
|
+
const b = blob(`import ${JSON.stringify(url)};`); try { return [new Worker(b, { type: 'module' }), b]; } catch (e) { URL.revokeObjectURL(b); throw e; }
|
|
27
|
+
}
|
|
28
|
+
function checkExpressiveness(x) { if (typeof x !== 'number' || !(x >= 1 && x <= 3)) throw new Error('callable-lipsync: expressiveness must be a number from 1 to 3'); }
|
|
29
|
+
function checkSeed(x) { if (x != null && !Number.isInteger(x)) throw new Error('callable-lipsync: seed must be an integer or null'); }
|
|
30
|
+
function checkModel(m) { if (m !== 'tiny' && m !== 'nano') throw new Error("callable-lipsync: model must be 'tiny' or 'nano'"); }
|
|
31
|
+
function checkAhead(ahead) { if (!AHEAD[ahead]) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', ')); }
|
|
32
|
+
|
|
33
|
+
export class LipSyncNode {
|
|
34
|
+
// ctx: the AudioContext the speech plays in. options:
|
|
35
|
+
// model 'tiny' | 'nano'; ahead (seconds of audio the model hears before a frame is due: 0.64, 0.48, 0.32, 0.16 (default), 0.08, 0;
|
|
36
|
+
// more: better head motion, longer delay; nano always uses 0.16); seed; expressiveness (1 to 3); playback (default true: frames
|
|
37
|
+
// follow `output` as heard); arkit (default true: also the 51 ARKit weights); margin (s added to the delay for the computation,
|
|
38
|
+
// 0 to 1, default 0.08); base (URL of the models folder, with tiny/, nano/, arkit/); ort (URL of onnxruntime-web's
|
|
39
|
+
// ort.wasm.min.mjs; default: the jsDelivr CDN); wasmPaths; worker, worklet (URLs of web-worker.js and web-capture.js, to use
|
|
40
|
+
// files instead of the built-in code, e.g. under a Content-Security-Policy without blob: (then same-origin); a bundled
|
|
41
|
+
// web-worker.js also finds the bundler's onnxruntime-web); onprogress({model, bytes, total}); start (default true)
|
|
42
|
+
static async create(ctx, options = {}) {
|
|
43
|
+
if (!ctx.audioWorklet) throw new Error('callable-lipsync: this page has no AudioWorklet (it needs https or localhost, and a current browser)');
|
|
44
|
+
if (typeof OfflineAudioContext !== 'undefined' && ctx instanceof OfflineAudioContext) throw new Error('callable-lipsync: LipSyncNode runs in real time; for a recording use LipSync');
|
|
45
|
+
const n = new LipSyncNode(ctx, options);
|
|
46
|
+
try {
|
|
47
|
+
if (!worklets.has(ctx)) { // once per context (the first node's choice of file); a failure can be tried again
|
|
48
|
+
const url = options.worklet ? absolute(options.worklet) : blob(WORKLET), p = ctx.audioWorklet.addModule(url); worklets.set(ctx, p);
|
|
49
|
+
p.then(() => { if (!options.worklet) URL.revokeObjectURL(url); }, () => { worklets.delete(ctx); if (!options.worklet) URL.revokeObjectURL(url); });
|
|
50
|
+
}
|
|
51
|
+
const make = () => new AudioWorkletNode(ctx, 'callable-lipsync-capture', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1], channelCount: 1, channelCountMode: 'explicit', channelInterpretation: 'speakers' });
|
|
52
|
+
try { await worklets.get(ctx); n.capture = make(); } catch (e) {
|
|
53
|
+
try { n.capture = make(); } catch (e2) { // not registered yet (another copy of this module, e.g. a hot reload, may have done it): try this node's own choice of file
|
|
54
|
+
const own = options.worklet ? absolute(options.worklet) : blob(WORKLET);
|
|
55
|
+
try { await ctx.audioWorklet.addModule(own); n.capture = make(); } catch (e3) { throw e; } finally { if (!options.worklet) URL.revokeObjectURL(own); }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const ch = new MessageChannel(); n.capture.port.postMessage({ type: 'port', port: ch.port1 }, [ch.port1]); n.worker.postMessage({ type: 'port', port: ch.port2 }, [ch.port2]);
|
|
59
|
+
n.input.connect(n.capture); n.mute = ctx.createGain(); n.mute.gain.value = 0; n.capture.connect(n.mute); n.mute.connect(ctx.destination); // a silent output: every browser runs a node that reaches the speakers
|
|
60
|
+
if (options.start !== false) await n.start(); else await n.load(n.model);
|
|
61
|
+
} catch (e) { n.dispose(); throw e; }
|
|
62
|
+
n.creating = false; return n;
|
|
63
|
+
}
|
|
64
|
+
constructor(ctx, o) {
|
|
65
|
+
const wasm = o.wasmPaths, paths = typeof wasm === 'string' || wasm instanceof URL ? absolute(wasm) : wasm ? Object.fromEntries(Object.entries(wasm).map(([k, v]) => [k, absolute(v)])) : null;
|
|
66
|
+
const base = absolute(o.base || CDN), ort = absolute(o.ort), workerUrl = o.worker ? absolute(o.worker) : null; // every URL checked before anything starts
|
|
67
|
+
if (paths && !ort && !workerUrl) throw new Error('callable-lipsync: wasmPaths needs ort too (onnxruntime-web\'s JS and its .wasm files must be the same version)');
|
|
68
|
+
this.ctx = ctx; this.model = o.model || 'tiny'; this.ahead = o.ahead ?? 0.16; this.seed = o.seed ?? null; this.expressiveness = o.expressiveness ?? 2; this.playback = o.playback ?? true;
|
|
69
|
+
this.margin = o.margin ?? 0.08; checkAhead(this.ahead); checkModel(this.model); checkExpressiveness(this.expressiveness); checkSeed(this.seed);
|
|
70
|
+
if (typeof this.margin !== 'number' || !(this.margin >= 0 && this.margin <= 1)) throw new Error('callable-lipsync: margin must be 0 to 1 s');
|
|
71
|
+
this.onprogress = o.onprogress || null; this.onerror = o.onerror || null; this.onwarning = o.onwarning || null; this.names = null; this.models = {}; this.disposed = false; this.sets = 0; this.gen = 0; this.creating = true;
|
|
72
|
+
this.input = ctx.createGain(); this.output = ctx.createDelay(MOST + this.margin + 0.01); this.input.connect(this.output); this.output.delayTime.value = this.delay;
|
|
73
|
+
this.stream = 0; this.running = false; this.store = new Map(); this.t0 = null; this.stats = { ms: 0, frames: 0, late: 0, restarts: 0 };
|
|
74
|
+
this.out = [{ cur: new Float32Array(118), last: new Float32Array(118), has: false }, { cur: new Float32Array(51), last: new Float32Array(51), has: false }]; this.seen = -1; this.waiting = new Map();
|
|
75
|
+
try { if (workerUrl) [this.worker, this.url] = workerFrom(workerUrl); else { this.url = blob(WORKER); this.worker = new Worker(this.url, { type: 'module' }); } }
|
|
76
|
+
catch (e) { if (this.url) URL.revokeObjectURL(this.url); this.input.disconnect(); throw e; } // e.g. a Content-Security-Policy without blob: workers
|
|
77
|
+
this.worker.onmessage = (e) => this.message(e.data);
|
|
78
|
+
this.helloTimer = setTimeout(() => { if (!this.hello) this.fail(new Error('callable-lipsync: the worker did not start within 20 s (is `worker` this version\'s web-worker.js?)')); }, 20000);
|
|
79
|
+
this.worker.onerror = (e) => { // before the worker says hello (it did not load, or threw while starting) an error is fatal; after, an uncaught one is only reported
|
|
80
|
+
if (this.hello) {
|
|
81
|
+
e.preventDefault(); const err = new Error('callable-lipsync: ' + (e.message || 'an error in the worker'));
|
|
82
|
+
for (const [k] of this.waiting) this.fail(err, k); // a load it may have broken: its callers reject (and may try again)
|
|
83
|
+
if (this.onerror) this.onerror(err); else console.error(err);
|
|
84
|
+
}
|
|
85
|
+
else this.fail(new Error('callable-lipsync: the worker failed to start: ' + (e.message || e.type || 'error')));
|
|
86
|
+
};
|
|
87
|
+
this.worker.postMessage({ type: 'init', base: base.endsWith('/') ? base : base + '/', ort, wasmPaths: paths, arkit: o.arkit ?? true }); // the worker resolves nothing: every URL absolute, from the page
|
|
88
|
+
}
|
|
89
|
+
fail(err, model) { // model: a load that failed (its callers reject); null: the worker itself (all reject, the stream stops)
|
|
90
|
+
for (const [k, p] of this.waiting) if (model == null || k === model) { p.reject(err); this.waiting.delete(k); }
|
|
91
|
+
if (model == null) { // the worker is gone: everything after this fails at once, and nothing is left running
|
|
92
|
+
this.running = false; this.dead = err; clearTimeout(this.helloTimer); if (this.capture) this.capture.port.postMessage({ type: 'close' }); this.worker.terminate(); if (this.url) { URL.revokeObjectURL(this.url); this.url = null; }
|
|
93
|
+
}
|
|
94
|
+
if (this.disposed || this.creating || model != null) return; // a failed load is its caller's to report; during create() it rejects with the error
|
|
95
|
+
if (this.onerror) this.onerror(err); else console.error(err);
|
|
96
|
+
}
|
|
97
|
+
message(m) {
|
|
98
|
+
if (m.type === 'hello') { this.hello = true; clearTimeout(this.helloTimer); return; }
|
|
99
|
+
if (m.type === 'names') { this.names = m.names; return; }
|
|
100
|
+
if (m.type === 'frames') {
|
|
101
|
+
if (m.stream !== this.stream) return;
|
|
102
|
+
const t0 = m.start / m.rate; if (t0 !== this.t0) { this.t0 = t0; this.store.clear(); this.seen = -1; } // a new stream, or one that started over
|
|
103
|
+
for (let i = 0; i < m.count; i++) this.store.set(m.first + i, [m.data.subarray(i * 118, (i + 1) * 118), m.weights ? m.weights.subarray(i * 51, (i + 1) * 51) : null]);
|
|
104
|
+
const old = m.first + m.count - 4 * FPS; for (const j of this.store.keys()) { if (j >= old) break; this.store.delete(j); } // keep 4 s (nobody asked, e.g. a hidden tab)
|
|
105
|
+
this.stats.ms += m.ms; this.stats.frames += m.count; this.stats.restarts = m.restarts;
|
|
106
|
+
} else if (m.type === 'loaded') { this.models[m.model] = m; if (m.names) this.names = m.names; const p = this.waiting.get(m.model); if (p) { this.waiting.delete(m.model); p.resolve(m); } }
|
|
107
|
+
else if (m.type === 'progress') { if (this.onprogress) this.onprogress(m); }
|
|
108
|
+
else if (m.type === 'warning') { const e = new Error(m.message); if (this.onwarning) this.onwarning(e); else console.warn(e); } // not fatal: e.g. no ARKit weights
|
|
109
|
+
else if (m.type === 'error' && 'stream' in m) { if (m.stream !== this.stream) return; this.halt(); const e = new Error(m.message); if (this.onerror) this.onerror(e); else console.error(e); } // the stream failed: it stops
|
|
110
|
+
else if (m.type === 'error') this.fail(new Error(m.message), 'model' in m ? m.model : null);
|
|
111
|
+
}
|
|
112
|
+
// Load a model without starting it (start() loads it too); resolves to {model, ms, bytes, weights, names}.
|
|
113
|
+
load(model) {
|
|
114
|
+
if (this.disposed) return Promise.reject(new Error('callable-lipsync: disposed'));
|
|
115
|
+
try { checkModel(model); } catch (e) { return Promise.reject(e); }
|
|
116
|
+
if (this.dead) return Promise.reject(this.dead);
|
|
117
|
+
if (this.models[model]) return Promise.resolve(this.models[model]);
|
|
118
|
+
if (!this.waiting.has(model)) { let p; const pr = new Promise((resolve, reject) => { p = { resolve, reject }; }); pr.catch(() => {}); this.waiting.set(model, Object.assign(p, { pr })); this.worker.postMessage({ type: 'load', model }); } // a preload nobody awaits does not end as an unhandled rejection
|
|
119
|
+
return this.waiting.get(model).pr;
|
|
120
|
+
}
|
|
121
|
+
// The delay in seconds between the audio at `input` and the frame it gives: `output` plays the audio this late.
|
|
122
|
+
get delay() { return ((this.model === 'nano' ? AHEAD[0.16] : AHEAD[this.ahead]).ready + 1) / FPS + this.margin; }
|
|
123
|
+
// Start a new stream (the head's motion and the blinks are drawn anew, unless a fixed seed repeats them): any of the options of create() for model, ahead, seed,
|
|
124
|
+
// expressiveness, playback. A new `ahead` changes the delay of `output` at once, so audio passing through skips or repeats a little.
|
|
125
|
+
// Resolves to true once the stream runs, or false if a later start() or stop() replaced this one before it could.
|
|
126
|
+
// The model loads first: if that fails, start() rejects and the stream that was running goes on.
|
|
127
|
+
async start(o = {}) {
|
|
128
|
+
const want = {}; for (const k of ['model', 'ahead', 'seed', 'expressiveness', 'playback']) if (o[k] !== undefined) want[k] = o[k];
|
|
129
|
+
if (want.ahead !== undefined) checkAhead(want.ahead); // nano ignores it, but keeps it for a later switch to tiny
|
|
130
|
+
if (want.model !== undefined) checkModel(want.model); if (want.expressiveness !== undefined) checkExpressiveness(want.expressiveness); if (want.seed !== undefined) checkSeed(want.seed);
|
|
131
|
+
const gen = ++this.gen, sets = this.sets;
|
|
132
|
+
try { await this.load(want.model ?? this.model); } catch (e) { if (gen === this.gen) this.gen--; throw e; } // a failed start() does not call off an earlier one still loading
|
|
133
|
+
if (gen !== this.gen) return false;
|
|
134
|
+
if (this.sets !== sets) delete want.expressiveness; // set() was called meanwhile: it wins
|
|
135
|
+
this.halt(); for (const o of this.out) o.has = false; // frame()/weights(): null until the new stream's own frames
|
|
136
|
+
const stream = this.stream; Object.assign(this, want); this.output.delayTime.setValueAtTime(this.delay, this.ctx.currentTime); this.stats = { ms: 0, frames: 0, late: 0, restarts: 0 };
|
|
137
|
+
this.capture.port.postMessage({ type: 'start', stream, model: this.model, ahead: this.model === 'nano' ? 0.16 : this.ahead, seed: this.seed, expressiveness: this.expressiveness }); this.running = true;
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
// Stop running the model (the face holds its last frame); a start() still loading its model is called off. start() goes on again.
|
|
141
|
+
stop() { this.gen++; this.halt(); }
|
|
142
|
+
halt() { this.stream++; this.running = false; this.t0 = null; this.store.clear(); this.seen = -1; if (this.capture) this.capture.port.postMessage({ type: 'stop' }); }
|
|
143
|
+
// Change the expressiveness at once (the head motion still to be drawn follows it).
|
|
144
|
+
set({ expressiveness } = {}) { if (expressiveness != null) { checkExpressiveness(expressiveness); this.expressiveness = expressiveness; this.sets++; if (this.capture) this.capture.port.postMessage({ type: 'set', expressiveness }); } } // through the worklet, in order with start()
|
|
145
|
+
// The audio clock's time of what is being heard now (playback) or of what has just come in (no playback).
|
|
146
|
+
now() {
|
|
147
|
+
const c = this.ctx; if (!this.playback) return c.currentTime;
|
|
148
|
+
const ts = c.getOutputTimestamp ? c.getOutputTimestamp() : null;
|
|
149
|
+
if (ts && ts.performanceTime > 0 && c.state === 'running') return ts.contextTime + (performance.now() - ts.performanceTime) / 1000; // what the speakers play now, where the browser says
|
|
150
|
+
return c.currentTime - (c.baseLatency || 0) - (c.outputLatency || 0);
|
|
151
|
+
}
|
|
152
|
+
at(time, k, live) { // the frame (k 0) or the weights (k 1) for `time`, between the two frames around it; live: the last one shown while none is ready
|
|
153
|
+
const o = this.out[k], held = o.has ? o.last : null, blend = (a, b, w, out) => { if (b) for (let c = 0; c < a.length; c++) out[c] = a[c] + w * (b[c] - a[c]); else out.set(a); return out; };
|
|
154
|
+
if (this.t0 == null) return live ? held : null;
|
|
155
|
+
const u = (time - this.t0 - this.delay) * FPS, i = Math.floor(u), a = this.store.get(i), b = this.store.get(i + 1);
|
|
156
|
+
if (!live) { if (!a) return null; return a[k] ? blend(a[k], b && b[k], u - i, new Float32Array(a[k].length)) : null; } // an explicit time: a new array, and nothing the live calls hold changes
|
|
157
|
+
const due = a ? (b || u === i ? -1 : i + 1) : i; // a frame needed now that is not here yet: this one, or the next one to blend towards
|
|
158
|
+
if (due >= 0 && u >= 0 && this.running && due > this.seen) { this.stats.late++; this.seen = due; }
|
|
159
|
+
for (const j of this.store.keys()) { if (j >= i - 1) break; this.store.delete(j); } // the past is no longer needed
|
|
160
|
+
if (!a) return held;
|
|
161
|
+
if (!a[k]) return held; // no weights for this frame (arkit: false, or the converter is not there yet)
|
|
162
|
+
blend(a[k], b && b[k], u - i, o.cur); o.last.set(o.cur); o.has = true; return o.cur;
|
|
163
|
+
}
|
|
164
|
+
// The FLAME frame (118 numbers, see LAYOUT) for what is heard at `time` (default: now). Reused by the next call.
|
|
165
|
+
frame(time) { return time == null ? this.at(this.now(), 0, true) : this.at(time, 0, false); }
|
|
166
|
+
// Its 51 ARKit weights, in the order of `names` (with arkit: true). Reused by the next call.
|
|
167
|
+
weights(time) { return time == null ? this.at(this.now(), 1, true) : this.at(time, 1, false); }
|
|
168
|
+
// Stop for good: the worker ends, pending load()/start() calls reject.
|
|
169
|
+
dispose() {
|
|
170
|
+
if (this.disposed) return; clearTimeout(this.helloTimer); this.stop(); this.disposed = true; this.fail(new Error('callable-lipsync: disposed'));
|
|
171
|
+
try { this.input.disconnect(); this.output.disconnect(); if (this.mute) this.mute.disconnect(); } catch (e) { /* already */ }
|
|
172
|
+
if (this.capture) this.capture.port.postMessage({ type: 'close' }); this.worker.terminate(); if (this.url) URL.revokeObjectURL(this.url);
|
|
173
|
+
}
|
|
174
|
+
}
|