callable-lipsync 0.2.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 CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  **callable-lipsync** - a tiny pre-trained streaming speech-to-face model by [Callable](https://callable.com.ai/). Speech (audio) goes in, face animation parameters come out (FLAME 2023 Open / ARKit). Needs 160ms lookahead for lips+face and 640ms for head movements. Try the [live demo](https://research.callable.com.ai/lipsync/).
10
10
 
11
- Comes in 2 sizes: `tiny` (17.1M; 36x realtime) and `nano` (2.4M; 95x realtime), on one CPU thread in Python. In a browser (WebAssembly) they run at 7x and 18x realtime.
11
+ Comes in 2 sizes: `tiny` (17.1M; 36x realtime) and `nano` (2.4M; 95x realtime), on one CPU thread in Python. In a browser (WebAssembly) `tiny` runs at 7x realtime with 0.64 s of audio ahead (5x with the default 0.16 s) and `nano` at 18x.
12
12
 
13
13
  Trained on English, might work on other languages.
14
14
 
@@ -29,6 +29,16 @@ A recorded two-person conversation. The avatar voices one speaker and listens to
29
29
 
30
30
  <br/>
31
31
 
32
+ | [Demo](https://research.callable.com.ai/lipsync/) | [On a 3D avatar, next to HeadAudio](https://research.callable.com.ai/lipsync/avatar.html) |
33
+ |:---:|:---:|
34
+ | [<img src="https://raw.githubusercontent.com/callabledev/callable-lipsync/main/files/page-demo.jpg" width="260" />](https://research.callable.com.ai/lipsync/) | [<img src="https://raw.githubusercontent.com/callabledev/callable-lipsync/main/files/page-avatar.jpg" width="260" />](https://research.callable.com.ai/lipsync/avatar.html) |
35
+ | A FLAME head and a 2D ARKit face on a recorded conversation, your own audio file or your microphone | Two [TalkingHead](https://github.com/met4citizen/TalkingHead) avatars on the same voice: callable-lipsync and [HeadAudio](https://github.com/met4citizen/HeadAudio) |
36
+ | [Run](https://research.callable.com.ai/lipsync/) · [Code](https://github.com/callabledev/callable-lipsync/blob/main/examples/browser/app.js) | [Run](https://research.callable.com.ai/lipsync/avatar.html) · [Code](https://github.com/callabledev/callable-lipsync/blob/main/examples/browser/avatar.js) |
37
+
38
+ Everything runs in your browser: the model, the faces and the audio. No audio leaves it.
39
+
40
+ <br/>
41
+
32
42
  <h2 align="center">Fast start</h2>
33
43
  <br/>
34
44
 
@@ -43,10 +53,10 @@ A recorded two-person conversation. The avatar voices one speaker and listens to
43
53
 
44
54
  JavaScript:
45
55
 
46
- - `onnxruntime-web>=1.17` (a peer dependency);
56
+ - `onnxruntime-web>=1.17` (a peer dependency; 1.19 or newer to bundle the browser node's worker yourself);
47
57
  - any current browser, or Node 18+.
48
58
 
49
- The model files ship inside both packages (about 21 MB for the two models and the ARKit converter's data together). Nothing is downloaded at run time.
59
+ The model files ship inside both packages (about 21 MB for the two models and the ARKit converter's data together). Nothing is downloaded at run time, except by `LipSyncNode`, which by default fetches them (and onnxruntime-web) from the jsDelivr CDN unless you point `base` and `ort` at your own copies (`ort`: the `ort.wasm.min.mjs` of onnxruntime-web 1.19 or newer).
50
60
 
51
61
  </details>
52
62
 
@@ -83,6 +93,25 @@ const frames = await model.process(samples); // Float32Array, 16 kHz mono -> [
83
93
 
84
94
  Python and JavaScript run the same engine: the same audio and seed give the same frames in both.
85
95
 
96
+ **In a web page, on any audio**: `LipSyncNode` is a Web Audio node. Connect any speech to it (text-to-speech output, an `<audio>` element, a WebRTC stream, a microphone), play its output, and ask it for the face that goes with what is being heard:
97
+
98
+ ```js
99
+ import { LipSyncNode } from 'callable-lipsync/web';
100
+
101
+ const lip = await LipSyncNode.create(audioCtx, { model: 'tiny' });
102
+ speech.connect(lip.input); // any AudioNode
103
+ lip.output.connect(audioCtx.destination); // the same audio, lip.delay seconds later (0.32 s by default)
104
+
105
+ function draw() {
106
+ const weights = lip.weights(); // 51 ARKit weights for what is heard now, in the order of lip.names
107
+ const frame = lip.frame(); // or the FLAME frame (118 numbers)
108
+ requestAnimationFrame(draw);
109
+ }
110
+ requestAnimationFrame(draw);
111
+ ```
112
+
113
+ The model runs in a worker, off the page's thread, and the node keeps the face in time with the sound. `frame()` and `weights()` return null until the first frames of a stream (also after `start()`), so draw your resting face then. With a microphone, leave the output unconnected and create it with `{ playback: false, ahead: 0 }`. By default it loads the model and ONNX Runtime from the jsDelivr CDN; `base` and `ort` point it at your own copies.
114
+
86
115
  <br/>
87
116
 
88
117
  <h2 align="center">Key Features</h2>
@@ -94,7 +123,7 @@ Python and JavaScript run the same engine: the same audio and seed give the same
94
123
 
95
124
  - **Fast**
96
125
 
97
- One 40 ms frame takes about **1 ms** on a single CPU thread in Python and about **6 ms** in WebAssembly in a browser (`tiny`). `nano` takes 0.4 ms and 2 ms.
126
+ One 40 ms frame takes about **1 ms** on a single CPU thread in Python and about **6 ms** in WebAssembly in a browser (`tiny`, with 0.64 s of audio ahead; 8 ms with 0.16 s, 16 ms with none). `nano` takes 0.4 ms and 2 ms.
98
127
 
99
128
  - **The whole face, not only the lips**
100
129
 
@@ -252,6 +281,52 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
252
281
 
253
282
  <br/>
254
283
 
284
+ <h2 align="center">Integrations</h2>
285
+ <br/>
286
+
287
+ **Any audio in a web page**: `LipSyncNode` (`callable-lipsync/web`, see Fast start above) takes any Web Audio source. A few common ones:
288
+
289
+ ```js
290
+ speechSource.connect(lip.input); // text-to-speech you play with Web Audio
291
+ ctx.createMediaElementSource(audioElement).connect(lip.input); // an <audio> or <video> element
292
+ ctx.createMediaStreamSource(remoteStream).connect(lip.input); // a WebRTC call (peerConnection.ontrack's stream; in Chrome also attach it to a muted <audio> element, or no sound flows)
293
+ ctx.createMediaStreamSource(await navigator.mediaDevices.getUserMedia({ audio: true })).connect(lip.input); // a microphone: create the node with { playback: false, ahead: 0 }
294
+ ```
295
+
296
+ Play `lip.output` instead of the source itself (it is the same audio, `lip.delay` seconds later), except for a microphone, which nobody needs to hear.
297
+
298
+ **[TalkingHead](https://github.com/met4citizen/TalkingHead)** avatars: one call drives the face, head, eyes and upper body, and routes what TalkingHead plays (its speech, its streams, its text-to-speech) through the model.
299
+
300
+ ```js
301
+ import { TalkingHead } from 'talkinghead';
302
+ import { LipSyncNode } from 'callable-lipsync/web';
303
+ import { driveTalkingHead } from 'callable-lipsync/talkinghead';
304
+
305
+ const ctx = new AudioContext({ sampleRate: 24000 }); // the rate of what you stream to TalkingHead, if you stream
306
+ const head = new TalkingHead(element, { audioCtx: ctx, lipsyncModules: ['en'] });
307
+ await head.showAvatar({ url: 'avatar.glb' });
308
+ const lip = await LipSyncNode.create(ctx);
309
+ const release = driveTalkingHead(head, lip); // head.speakAudio(...) and its streams (and its TTS, with ttsEndpoint set) now animate through the model
310
+ ```
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. 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
+
314
+ **Any three.js avatar with ARKit blend shapes** (the 52 named shapes many web avatars carry):
315
+
316
+ ```js
317
+ const meshes = []; // the avatar's meshes that have morph targets
318
+ gltf.scene.traverse((o) => { if (o.morphTargetDictionary) meshes.push(o); });
319
+ function draw() {
320
+ const w = lip.weights(), f = lip.frame();
321
+ if (w) for (const m of meshes) lip.names.forEach((name, i) => { const k = m.morphTargetDictionary[name]; if (k !== undefined) m.morphTargetInfluences[k] = w[i]; });
322
+ if (f) headBone.quaternion.copy(rest).multiply(turn.setFromEuler(euler.set(f[106], f[107], f[108]))); // the neck's turn on the bone's own rest pose (axis-angle, small: as Euler; check your rig's axes); the chest's f[100..102] goes on a spine bone the same way. The rotations are in the model's axes (x across the face, y up, z forward): on a rig whose bone axes differ, map them first
323
+ renderer.render(scene, camera); requestAnimationFrame(draw);
324
+ }
325
+ const rest = headBone.quaternion.clone(), turn = new THREE.Quaternion(), euler = new THREE.Euler();
326
+ requestAnimationFrame(draw);
327
+ ```
328
+
329
+ <br/>
255
330
  <h2 align="center">Typical Use Cases</h2>
256
331
  <br/>
257
332
 
@@ -271,8 +346,10 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
271
346
  - ✅ JavaScript package (`npm install callable-lipsync`), for browsers and Node
272
347
  - ✅ FLAME 2023 Open output
273
348
  - ✅ ARKit blendshape converter in both packages
274
- - ✅ Browser demo
349
+ - ✅ Browser demo, with your own audio or your microphone
275
350
  - ✅ Benchmarks against 13 other speech-to-face models
351
+ - ✅ `LipSyncNode`: any Web Audio source in, the face in time with what is heard out
352
+ - ✅ TalkingHead avatars (`driveTalkingHead`), with a side-by-side page next to HeadAudio
276
353
 
277
354
  **Planned**
278
355
 
@@ -284,7 +361,9 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
284
361
  <h2 align="center">Links</h2>
285
362
  <br/>
286
363
 
287
- - [Live demo](https://research.callable.com.ai/lipsync/), and its [source](https://github.com/callabledev/callable-lipsync/tree/main/examples/browser): both models on a recorded conversation, a 3D head and a 2D face
364
+ - [Live demo](https://research.callable.com.ai/lipsync/), and its [source](https://github.com/callabledev/callable-lipsync/tree/main/examples/browser): both models on a recorded conversation, your own audio or your microphone, a 3D head and a 2D face
365
+ - [On a 3D avatar](https://research.callable.com.ai/lipsync/avatar.html), next to HeadAudio
366
+ - [The browser node](https://github.com/callabledev/callable-lipsync/blob/main/js/web.js) and [the TalkingHead adapter](https://github.com/callabledev/callable-lipsync/blob/main/js/talkinghead.js)
288
367
  - The ARKit converter [in JavaScript](https://github.com/callabledev/callable-lipsync/blob/main/js/arkit.js) and [in Python](https://github.com/callabledev/callable-lipsync/blob/main/src/callable_lipsync/arkit.py)
289
368
  - [Python example](https://github.com/callabledev/callable-lipsync/blob/main/examples/python/wav_to_frames.py) and [Node example](https://github.com/callabledev/callable-lipsync/blob/main/examples/node/wav_to_frames.mjs)
290
369
  - [The engine in JavaScript](https://github.com/callabledev/callable-lipsync/blob/main/js/engine.js) and [in Python](https://github.com/callabledev/callable-lipsync/blob/main/src/callable_lipsync/engine.py)
@@ -301,7 +380,13 @@ Try the models, create an [issue](https://github.com/callabledev/callable-lipsyn
301
380
  - One speaker at a time. Feed it a mix of two voices and it will lip-sync both.
302
381
  - Measured mostly on English. It listens to sound, not text, so other languages work, but we have not measured how well.
303
382
  - No tongue and no teeth in the output.
304
- - Input is 16 kHz mono. Resample other audio first.
383
+ - Input is 16 kHz mono. Resample other audio first (`LipSyncNode` does it for you).
384
+ - Lip reading trails the larger models (SelfTalk, UniTalker, ARTalk): see the benchmarks.
385
+ - In a page, the model needs its audio ahead of time: `LipSyncNode` plays its output `lip.delay` late (0.32 s by default). With a microphone and `tiny` (no audio ahead), the face follows the voice about 0.16 s behind it; `nano` always waits for 0.16 s of audio, so 0.32 s.
386
+ - `LipSyncNode` needs AudioWorklet: a page served over https (or localhost) in a current browser. `tiny` takes about 20% of one CPU core while it runs with 0.16 s ahead and about 40% with none (as for a microphone); `nano` about 6%.
387
+ - `lip.load()` sets the new model up on the worker that runs the stream. On a slow CPU (two cores) that can hold the face for half a second or more when you switch models mid-speech; await `lip.load()` for both models before the speech starts, and switch with `lip.start({ model })`.
388
+ - The ARKit weights reproduce about three quarters of the face's motion: a starting point for your rig.
389
+ - Below about 0.3 s of audio ahead, head motion stops following the words (the lips do not need more than 0.16 s).
305
390
 
306
391
  **Model card**
307
392
 
@@ -329,4 +414,4 @@ Try the models, create an [issue](https://github.com/callabledev/callable-lipsyn
329
414
  <h2 align="center">Third-party material</h2>
330
415
  <br/>
331
416
 
332
- The browser demo uses the [FLAME 2023 Open](https://flame.is.tue.mpg.de/) head model (CC BY 4.0), conversations from [DailyTalkContiguous](https://huggingface.co/datasets/kyutai/DailyTalkContiguous) (CC BY-SA 4.0, unmodified), [ONNX Runtime Web](https://onnxruntime.ai/) and [three.js](https://threejs.org/). The demo video uses the same head model and one of those conversations.
417
+ The browser demo uses the [FLAME 2023 Open](https://flame.is.tue.mpg.de/) head model (CC BY 4.0), conversations from [DailyTalkContiguous](https://huggingface.co/datasets/kyutai/DailyTalkContiguous) (CC BY-SA 4.0, unmodified), [ONNX Runtime Web](https://onnxruntime.ai/) and [three.js](https://threejs.org/). The demo video uses the same head model and one of those conversations. The avatar page uses [TalkingHead](https://github.com/met4citizen/TalkingHead) and [HeadAudio](https://github.com/met4citizen/HeadAudio) (MIT, loaded from a CDN) and TalkingHead's `mpfb.glb` avatar (CC0, made with Blender and [MPFB](https://github.com/makehumancommunity/mpfb2)), made smaller for the web.
package/js/engine.js CHANGED
@@ -20,7 +20,7 @@ export class Engine {
20
20
  e.zero = new Float32Array(e.meta.width); e.reset({}); return e;
21
21
  }
22
22
  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 } = {}) {
23
- 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.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
23
+ 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
24
24
  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
25
25
  this.audio = new Float32Array(1 << 16); this.a0 = 0; this.an = 0; // samples [a0, an) are held
26
26
  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
@@ -32,7 +32,8 @@ export class Engine {
32
32
  push(x) {
33
33
  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; }
34
34
  const o = this.an - this.a0, a = this.audio, g = 2 * this.floor, r = this.hiss; this.an += x.length;
35
- 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)
35
+ 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
36
+ 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
36
37
  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
37
38
  }
38
39
  t(data, dims) { return new this.ort.Tensor('float32', data, dims); }
@@ -64,7 +65,7 @@ export class Engine {
64
65
  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]; } }
65
66
  const fc = new Float32Array((await this.run('face', { h: this.t(hs, [H, w]) })).face.data), closed = this.meta.closed;
66
67
  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
67
- const tt = this.nface + i, upto = Math.min(this.en.length - 1, tt + this.wait); for (let k = Math.max(0, tt - HOLD); k <= upto; k++) if (this.en[k]) this.lastLoud = Math.max(this.lastLoud, k);
68
+ 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);
68
69
  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;
69
70
  if (this.record) this.log.face.push(Array.from(fc.subarray(i * 101, i * 101 + 101)));
70
71
  if (gt > 1e-3) for (let c = 0; c < 101; c++) fc[i * 101 + c] += gt * (closed[c] - fc[i * 101 + c]);
@@ -109,7 +110,7 @@ export class Engine {
109
110
  this.nb++;
110
111
  }
111
112
  mute(tt) { // the silence gate's value for frame tt (frames in order)
112
- const upto = Math.min(this.en.length - 1, tt + this.wait); for (let k = Math.max(0, tt - HOLD); k <= upto; k++) if (this.en[k]) this.lastLoud = Math.max(this.lastLoud, k);
113
+ 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);
113
114
  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;
114
115
  }
115
116
  async stepNano() {
package/js/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export declare const VERSION: string;
1
2
  export declare const SAMPLE_RATE: 16000, FPS: 25, FRAME: 640;
2
3
  export declare const LAYOUT: Record<'expression' | 'chest' | 'jaw' | 'neck' | 'leftEye' | 'rightEye' | 'travel', [number, number]>;
3
4
  export declare const AHEAD: Record<number, { known: number; wait: number; ready: number }>;
package/js/index.js CHANGED
@@ -8,6 +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.1'; // this package's version (kept equal to package.json's by the tests)
11
12
  export const SAMPLE_RATE = 16000, FPS = 25, FRAME = 640;
12
13
  // what the 118 numbers of a frame are: [first, one past the last]. Rotations are axis-angle, in radians.
13
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] };
@@ -18,7 +19,7 @@ export const AHEAD = { 0.64: { known: 12, wait: 4, ready: 16 }, 0.48: { known: 8
18
19
  export async function loader(model = 'tiny', base = null) {
19
20
  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(); };
20
21
  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)');
21
- const fs = await import(/* @vite-ignore */ 'node:fs/promises'), dir = new URL(`../models/${model}/`, import.meta.url);
22
+ const fs = await import(/* @vite-ignore */ /* webpackIgnore: true */ 'node:fs/promises'), dir = new URL(`../models/${model}/`, import.meta.url);
22
23
  return async name => { const b = await fs.readFile(new URL(name, dir)); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };
23
24
  }
24
25
 
package/js/resample.js ADDED
@@ -0,0 +1,38 @@
1
+ // A streaming resampler: audio at any rate in, 16 kHz (or any rate) out, anti-aliased by a windowed-sinc filter.
2
+ // Output sample j is the input at time j / outRate from the stream's first sample: no delay, so timestamps stay exact
3
+ // (the output for a moment is ready once the input is `reach` seconds past it). The same input cut into different
4
+ // chunks gives the same output.
5
+ //
6
+ // const r = new Resampler(48000); // to 16 kHz
7
+ // const y = r.push(block); // Float32Array: the output samples this block completes (possibly none)
8
+ export class Resampler {
9
+ constructor(inRate, outRate = 16000, { zeros = 16, phases = 256 } = {}) {
10
+ this.step = inRate / outRate; this.same = inRate === outRate; // input samples per output sample
11
+ const down = Math.min(1, outRate / inRate), fc = 0.45 * down; // cutoff, cycles per input sample: 0.9 of the lower Nyquist
12
+ this.R = zeros / down; this.P = phases; this.reach = this.R / inRate; // the kernel's half-width in input samples
13
+ const n = Math.ceil(this.R * phases) + 2, T = this.table = new Float64Array(n);
14
+ 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)); }
15
+ 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
16
+ }
17
+ push(x) {
18
+ if (this.same) { this.n += x.length; this.j += x.length; return Float32Array.from(x); }
19
+ 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
20
+ if (keep > this.base || held + x.length > this.buf.length) {
21
+ 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;
22
+ if (b === this.buf) b.copyWithin(0, keep - this.base, this.n - this.base);
23
+ else b.set(this.buf.subarray(keep - this.base, this.n - this.base));
24
+ this.buf = b; this.base = keep;
25
+ }
26
+ this.buf.set(x, this.n - this.base); this.n += x.length;
27
+ const out = [], { buf, base, step, R, P, table } = this;
28
+ for (;;) {
29
+ const p = this.j * step, hi = Math.floor(p + R); if (hi >= this.n) break;
30
+ let s = 0, ws = 0;
31
+ for (let i = Math.ceil(p - R); i <= hi; i++) {
32
+ 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];
33
+ }
34
+ out.push(s / ws); this.j++;
35
+ }
36
+ return Float32Array.from(out);
37
+ }
38
+ }
@@ -0,0 +1,15 @@
1
+ import type { LipSyncNode } from './web.js';
2
+ export interface DriveOptions {
3
+ /** Route TalkingHead's speech and stream through the node (default true). */
4
+ audio?: boolean;
5
+ /** The head and body turns from the model (default true). */
6
+ head?: boolean;
7
+ /** Blinks and gaze from the model (default true); false leaves them to TalkingHead. */
8
+ eyes?: boolean;
9
+ /** How far the face and head move (default 1). */
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>;
13
+ }
14
+ /** Drive a TalkingHead avatar (its ARKit blend shapes, head and body) from the node. Returns a function that gives it back. */
15
+ export declare function driveTalkingHead(head: unknown, lip: LipSyncNode, options?: DriveOptions): () => void;
@@ -0,0 +1,136 @@
1
+ // callable-lipsync driving a TalkingHead avatar (github.com/met4citizen/TalkingHead, MIT): its face (the ARKit blend
2
+ // shapes), head, upper body and eyes, from the speech it plays.
3
+ //
4
+ // import { TalkingHead } from 'talkinghead';
5
+ // import { LipSyncNode } from 'callable-lipsync/web';
6
+ // import { driveTalkingHead } from 'callable-lipsync/talkinghead';
7
+ // const ctx = new AudioContext({ sampleRate: 24000 }); // the stream's rate, if you stream to TalkingHead (see below)
8
+ // const head = new TalkingHead(el, { audioCtx: ctx, lipsyncModules: ['en'] }); await head.showAvatar({ url: 'avatar.glb' });
9
+ // const lip = await LipSyncNode.create(ctx);
10
+ // const release = driveTalkingHead(head, lip); // head.speakAudio(), its streaming and its TTS now animate through the model
11
+ //
12
+ // What TalkingHead plays (its speech and its stream) goes through the node: the model hears it `lip.delay` seconds before
13
+ // you do, so TalkingHead's own events (subtitles, word timings, the end of speech) come that much before the sound, and
14
+ // audio already in the delay still plays after it stops. Other audio can feed `lip.input` too (pass { audio: false } to
15
+ // leave TalkingHead's audio alone). Each animation frame the weights go in as TalkingHead "realtime" values, which
16
+ // override its own lip sync (it still needs a lipsync module for its text and word timings), its moods and emoji faces,
17
+ // and, with tiny, its blinks, looks and body turns; its hands and the rest of its body animation go on. TalkingHead's own
18
+ // nod to the loudness of its speech hears the audio before the delay, so it comes lip.delay seconds early. While the node
19
+ // has no frame (before the first, just after start(), or once it stopped) TalkingHead has the face back. nano has no blinks, gaze or upper
20
+ // body: with it those stay TalkingHead's. A new avatar (showAvatar) is picked up as it comes, and so are the new nodes
21
+ // TalkingHead makes when a stream asks for another sample rate. Give TalkingHead your AudioContext (its `audioCtx` option)
22
+ // and make the node in it: otherwise such a stream makes TalkingHead close its context and the node with it. The avatar
23
+ // needs ARKit blend shapes (TalkingHead's own avatars have them). Make that AudioContext at the sample rate of what TalkingHead
24
+ // streams (or resample it before streamAudio): in a shared context its stream is not resampled. The gain nodes of each
25
+ // graph TalkingHead builds stay routed until release (a stream may still play through an older one).
26
+
27
+ // TalkingHead's head and body turns, from the frame's neck and chest rotations (radians; small, so axis-angle = Euler)
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), 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.
33
+ const SHARE = [1 / 2 + 1 / 8 + 1 / 24, 1 / 2 + 1 / 2 + 1 / 4, 1 / 12 + 1 / 12 + 1 / 24];
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
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'];
36
+ const QUIET_EYES = ['eyesClosed', 'eyesLookUp', 'eyesLookDown'];
37
+ // TalkingHead's eye contact (read each time it plans a look): off while the model has the eyes. Its head moves are fixed
38
+ // when it starts, so they stay; the model's head turns override them while it has frames.
39
+ const LOOKS = ['avatarIdleEyeContact', 'avatarSpeakingEyeContact'];
40
+ const isEye = (n) => n.startsWith('eyeBlink') || n.startsWith('eyeLook'); // blinks and gaze; eyeSquint and eyeWide are expression, always the model's
41
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
42
+
43
+ // options: audio (default true: route TalkingHead's speech and stream through the node), head (default true: the head and
44
+ // body turns), eyes (default true: blinks and gaze from the model, with tiny; false leaves them to TalkingHead), gain
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 = {} } = {}) {
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
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 })');
50
+ let mt = null, set = null, names = null, eyesOn = null, active = false, outTo = null, warned = false, bare = false, released = false;
51
+ const routed = new Map(); // TalkingHead's gain nodes sent into the node -> the reverb each played to
52
+ const before = head.opt.update, limits = new Map(), looks = new Map();
53
+
54
+ function free(all) { // realtime off on what we set (all: also the eye shapes); TalkingHead eases them home (base 0: some have no baseline and would stay put)
55
+ if (!set) return;
56
+ const back = (m) => { m.realtime = null; if (m.baseline == null) m.base = 0; m.needsUpdate = true; };
57
+ for (const [m, , eye] of set.shapes) if (all || !eye || !eyesOn) back(m);
58
+ for (const m of [...set.quiet, ...set.quietEyes, ...set.rot.map(([r]) => r)]) back(m);
59
+ active = false;
60
+ }
61
+ function eyesTo(on) { // hand the eyes to the model (on) or back to TalkingHead
62
+ if (on === eyesOn) return; eyesOn = on;
63
+ if (on) {
64
+ const av = head.avatar || {}; // the avatar these belong to, so they go back onto it (not onto a newer one)
65
+ for (const k of LOOKS) { looks.set(k, [head.opt[k], av, own(av, k), av[k]]); head.opt[k] = 0; if (own(av, k)) av[k] = 0; }
66
+ for (const k of ['eyeBlinkLeft', 'eyeBlinkRight']) if (mt[k] && !limits.has(k)) { limits.set(k, mt[k].limit); mt[k].limit = null; } // its limit mixes the brows into the lids: a frown would half-close the eyes
67
+ } else {
68
+ for (const [k, [o, av, wasOwn, v]] of looks) { head.opt[k] = o; if (wasOwn) av[k] = v; } looks.clear();
69
+ for (const [k, l] of limits) if (mt[k]) mt[k].limit = l; limits.clear();
70
+ if (set) for (const [m, , eye] of set.shapes) if (eye) { m.realtime = null; m.needsUpdate = true; } if (set) for (const m of set.quietEyes) { m.realtime = null; m.needsUpdate = true; }
71
+ }
72
+ }
73
+ function build() { // what we set on the avatar now shown
74
+ const get = (list) => list.map((n) => mt[n]).filter(Boolean);
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),
76
+ rot: turns ? [...HEAD, ...BODY].filter(([n]) => mt[n]).map(([n, k]) => [mt[n], k, BODY.some(([b]) => b === n)]) : [] };
77
+ }
78
+ function bind() { // (again) for the avatar now shown: its morph targets, and the shape names the node knows
79
+ if (mt === head.mtAvatar && names === lip.names) return;
80
+ names = lip.names;
81
+ if (mt && mt !== head.mtAvatar) { // a new avatar: the old one's settings go back, and the values TalkingHead copied over to it are cleared
82
+ const on = eyesOn; eyesTo(false); free(true);
83
+ mt = head.mtAvatar; eyesOn = null; build(); free(true); if (on) eyesTo(true); return;
84
+ }
85
+ mt = head.mtAvatar; build();
86
+ }
87
+ function route() { // TalkingHead's speech and stream into the node, its output to the reverb (again, if TalkingHead rebuilt its graph)
88
+ if (!audio || lip.disposed) return; // a disposed node takes no audio: what it had goes back once, in update()
89
+ const now = [head.audioSpeechGainNode, head.audioStreamGainNode].filter((n) => n && !routed.has(n));
90
+ if (!now.length && outTo === head.audioReverbNode) return;
91
+ if (head.audioCtx !== lip.ctx) {
92
+ if (!warned) { const e = new Error('callable-lipsync: TalkingHead replaced its AudioContext (give it yours, its audioCtx option); its audio no longer reaches the node'); if (lip.onerror) lip.onerror(e); else console.error(e); }
93
+ warned = true; return;
94
+ }
95
+ for (const n of now) { try { n.disconnect(head.audioReverbNode); } catch (e) { /* not connected there */ } n.connect(lip.input); routed.set(n, head.audioReverbNode); } // new ones too; the last graph's stay (a stream may still play through them)
96
+ // (a node of an older graph may still be fed: TalkingHead keeps its stream worklet across rebuilds in the same context, so none are let go)
97
+ if (outTo !== head.audioReverbNode) { if (outTo) { try { lip.output.disconnect(outTo); } catch (e) { /* already */ } } outTo = head.audioReverbNode; lip.output.connect(outTo); }
98
+ }
99
+ function unroute() {
100
+ for (const [n, reverb] of routed) { try { n.disconnect(lip.input); } catch (e) { /* already */ } try { n.connect(reverb); } catch (e) { /* its context is gone */ } }
101
+ if (outTo) { try { lip.output.disconnect(outTo); } catch (e) { /* already */ } } routed.clear(); outTo = null;
102
+ }
103
+
104
+ bind(); route();
105
+ const rebuild = head.initAudioGraph; // TalkingHead's own graph rebuild (a stream at another sample rate): routed at once, before any audio plays through it
106
+ const wrapped = function (...a) { const r = rebuild.apply(this, a); if (!released) route(); return r; };
107
+ if (typeof rebuild === 'function') head.initAudioGraph = wrapped;
108
+ head.opt.update = (dt) => {
109
+ if (before) before(dt);
110
+ if (released) return; // still called by a hook wrapped around ours after release: does nothing
111
+ bind(); route();
112
+ const w = lip.weights(), f = lip.frame();
113
+ if (lip.disposed) { if (routed.size) unroute(); if (active) { eyesTo(false); free(true); } return; } // the node is gone: TalkingHead's audio and face go back to it
114
+ if (!lip.running) { eyesTo(false); if (active) free(true); return; } // the node stopped: the face (eyes too) is TalkingHead's
115
+ if (!w || !f) return; // a new stream's first frames are on their way: the last pose holds
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'); }
117
+ const nano = lip.model === 'nano'; eyesTo(eyes && !nano);
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; }
119
+ for (const m of set.quiet) { m.realtime = 0; m.needsUpdate = true; }
120
+ if (eyesOn) for (const m of set.quietEyes) { m.realtime = 0; m.needsUpdate = true; }
121
+ const withBody = !nano && set.rot.some(([, , body]) => body), clamp = (x) => Math.max(-1, Math.min(1, x));
122
+ for (const [m, k, body] of set.rot) {
123
+ if (body && nano) { if (m.realtime !== null) { m.realtime = null; m.base = 0; m.needsUpdate = true; } continue; }
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;
126
+ }
127
+ active = true;
128
+ };
129
+ const hook = head.opt.update;
130
+ return () => { // once; the update hook goes back only if it is still ours (someone may have wrapped it since)
131
+ if (released) return; released = true;
132
+ if (head.opt.update === hook) head.opt.update = before;
133
+ if (head.initAudioGraph === wrapped) { if (own(head, 'initAudioGraph') && rebuild === Object.getPrototypeOf(head).initAudioGraph) delete head.initAudioGraph; else head.initAudioGraph = rebuild; } // only if still ours, like the update hook
134
+ bind(); eyesTo(false); free(true); unroute(); // bind(): a new avatar shown since the last frame is cleaned up too
135
+ };
136
+ }
@@ -0,0 +1,31 @@
1
+ // The AudioWorklet half of LipSyncNode (web.js): passes its input, mixed to mono by the node, to the worker that runs the
2
+ // 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
3
+ // imports), so a bundler can copy it as it is.
4
+ class CallableLipSyncCapture extends AudioWorkletProcessor {
5
+ constructor() {
6
+ 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;
7
+ this.port.onmessage = (e) => {
8
+ const m = e.data;
9
+ if (m.type === 'port') this.to = m.port;
10
+ else if (m.type === 'start') { this.send(); this.pending = m; this.on = false; } // the stream starts with the next block
11
+ 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
12
+ 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
13
+ else if (m.type === 'close') { this.send(); this.alive = false; this.on = false; if (this.to) this.to.close(); }
14
+ };
15
+ }
16
+ send() {
17
+ 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]); }
18
+ this.buf = null; this.n = 0;
19
+ }
20
+ process(inputs) {
21
+ if (!this.alive) return false;
22
+ 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 }); }
23
+ if (!this.on) return true;
24
+ const ch = inputs[0] && inputs[0][0], len = ch ? ch.length : (typeof renderQuantumSize !== 'undefined' ? renderQuantumSize : 128);
25
+ if (!this.buf) { this.buf = new Float32Array(Math.max(this.size, len)); this.t = currentFrame; }
26
+ if (ch) this.buf.set(ch, this.n); else this.buf.fill(0, this.n, this.n + len); // nothing connected: silence
27
+ this.n += len; if (this.n >= this.size || this.n + len > this.buf.length) this.send();
28
+ return true;
29
+ }
30
+ }
31
+ registerProcessor('callable-lipsync-capture', CallableLipSyncCapture);
@@ -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.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
+ 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";
@@ -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
+ }
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "callable-lipsync",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "A tiny speech-to-face model that runs in the browser: streaming lip sync, blinks, gaze and head motion on one CPU thread",
5
5
  "type": "module",
6
6
  "main": "js/index.js",
7
7
  "types": "js/index.d.ts",
8
8
  "exports": {
9
9
  ".": { "types": "./js/index.d.ts", "default": "./js/index.js" },
10
+ "./web": { "types": "./js/web.d.ts", "default": "./js/web.js" },
11
+ "./talkinghead": { "types": "./js/talkinghead.d.ts", "default": "./js/talkinghead.js" },
12
+ "./web-worker": "./js/web-worker.js",
13
+ "./web-capture": "./js/web-capture.js",
10
14
  "./engine": "./js/engine.js",
11
15
  "./models/*": "./models/*"
12
16
  },
@@ -18,5 +22,5 @@
18
22
  "repository": { "type": "git", "url": "git+https://github.com/callabledev/callable-lipsync.git" },
19
23
  "bugs": { "url": "https://github.com/callabledev/callable-lipsync/issues", "email": "support@callable.com.ai" },
20
24
  "peerDependencies": { "onnxruntime-web": ">=1.17.0" },
21
- "sideEffects": false
25
+ "sideEffects": ["./js/web-worker.js", "./js/web-capture.js"]
22
26
  }