callable-lipsync 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -13
- package/js/engine.js +5 -4
- package/js/index.d.ts +1 -0
- package/js/index.js +2 -1
- package/js/resample.js +38 -0
- package/js/talkinghead.d.ts +13 -0
- package/js/talkinghead.js +134 -0
- package/js/web-capture.js +31 -0
- package/js/web-inline.js +3 -0
- package/js/web-worker.js +109 -0
- package/js/web.d.ts +71 -0
- package/js/web.js +174 -0
- package/models/arkit/arkit.json +206 -206
- package/models/nano/fe.onnx +0 -0
- package/models/nano/meta.json +107 -107
- package/models/nano/out.onnx +0 -0
- package/models/nano/s0.onnx +0 -0
- package/models/nano/s1.onnx +0 -0
- package/models/nano/t0.onnx +0 -0
- package/models/nano/t1.onnx +0 -0
- package/models/nano/t2.onnx +0 -0
- package/models/nano/t3.onnx +0 -0
- package/models/nano/t4.onnx +0 -0
- package/models/tiny/face.onnx +0 -0
- package/models/tiny/meta.json +104 -104
- package/models/tiny/open.onnx +0 -0
- package/package.json +6 -2
package/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` (
|
|
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>
|
|
@@ -90,11 +119,11 @@ Python and JavaScript run the same engine: the same audio and seed give the same
|
|
|
90
119
|
|
|
91
120
|
- **Tiny**
|
|
92
121
|
|
|
93
|
-
Two sizes. `tiny` is
|
|
122
|
+
Two sizes. `tiny` is 17.1M parameters and a 17.7 MB download. `nano` is 2.4M parameters and 2.5 MB.
|
|
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
|
|
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
|
|
|
@@ -118,6 +147,59 @@ Python and JavaScript run the same engine: the same audio and seed give the same
|
|
|
118
147
|
|
|
119
148
|
<br/>
|
|
120
149
|
|
|
150
|
+
<h2 align="center">Benchmarks</h2>
|
|
151
|
+
<br/>
|
|
152
|
+
|
|
153
|
+
<!-- benchmarks:start (generated by the research repo's compare/summary.py) -->
|
|
154
|
+
<p align="center">
|
|
155
|
+
<picture>
|
|
156
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/callabledev/callable-lipsync/main/files/benchmarks-dark.svg">
|
|
157
|
+
<img alt="Benchmark summary: callable-lipsync tiny and nano against 13 other speech-to-face models on seven measures" src="https://raw.githubusercontent.com/callabledev/callable-lipsync/main/files/benchmarks-light.svg" width="100%">
|
|
158
|
+
</picture>
|
|
159
|
+
</p>
|
|
160
|
+
|
|
161
|
+
Each column is colored by rank among the models: blue is better, red is worse, and **bold** marks the best few.
|
|
162
|
+
|
|
163
|
+
- On speech from people it has never heard (Multiface), `tiny` has the best overall score and exact timing, and it has the lowest lip error on Callable held-out.
|
|
164
|
+
- Since 0.2.0 both models close the lips on p, b and m as often as real speakers do (93% and 91%; real 92%), up from 75% and 45% in 0.1.0.
|
|
165
|
+
- Lip reading is where they still trail: the larger SelfTalk, UniTalker and ARTalk read better.
|
|
166
|
+
- On VOCASET's own test the models trained on VOCASET win clearly, as expected.
|
|
167
|
+
|
|
168
|
+
<details>
|
|
169
|
+
<summary>The table as text, and how it was measured</summary>
|
|
170
|
+
|
|
171
|
+
| Model | Size | Audio ahead | Runs on | Head | Multiface score | Lip error, Callable held-out (mm) | Lip error, VOCASET (×10⁻⁵ m²) | Timing on Multiface (ms) | Lips close on p/b/m (real 92%) | SyncNet confidence | Lip-reading error |
|
|
172
|
+
|---|---|---|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
|
|
173
|
+
| *Real speech* | | | | | *0.00* | *0.0* | *0.0* | *0* | *92%* | – | – |
|
|
174
|
+
| **callable-lipsync tiny** | 17.1M | 0.16 s lips / 0.64 s head | 1 CPU thread | ✓ | **0.67** | **7.4** | 6.1 | **0** | **93%** | 6.07 | 72% |
|
|
175
|
+
| **callable-lipsync nano** | 2.4M | 0.16 s | 1 CPU thread | ✓ | **0.69** | **7.7** | 6.3 | **0** | 91% | **6.13** | 74% |
|
|
176
|
+
| UniTalker-B | 96M | whole clip | GPU | | **0.81** | 9.5 | **1.4** | −28 | 81% | 5.76 | **67%** |
|
|
177
|
+
| ARTalk | 490M | 4 s windows | GPU | ✓ | 0.87 | **8.1** | 7.6 | +12 | 89% | 5.44 | **69%** |
|
|
178
|
+
| NVIDIA Audio2Face-3D v3.0 † | 181M | 0.75 s | GPU | | 1.00 | 13.3 | 12.1 | −24 | **96%** | 2.13 | 80% |
|
|
179
|
+
| EmoTalk | 641M | whole clip | GPU | | 1.00 | 8.2 | 4.1 | −16 | 0% | 2.56 | 85% |
|
|
180
|
+
| NVIDIA Audio2Face-3D v2.3 † | 18M | 0.26 s | GPU | | 1.00 | 8.9 | 5.3 | **0** | **98%** | 4.53 | 78% |
|
|
181
|
+
| SelfTalk | 769M | whole clip | GPU | | 1.11 | 9.0 | **2.6** | −80 | 90% | **6.10** | **52%** |
|
|
182
|
+
| CodeTalker | 319M | whole clip | GPU | | 1.17 | 9.3 | **3.2** | −84 | 68% | **6.08** | 69% |
|
|
183
|
+
| HeadAudio | 3.6K | none | browser | | 1.26 | 9.4 | 5.6 | +132 | 47% | 1.68 | 80% |
|
|
184
|
+
| LAM-A2E | 102M | whole clip | GPU | | 1.30 | 9.2 | 3.9 | −80 | 18% | 3.77 | 78% |
|
|
185
|
+
| SAiD | 101M | whole clip | GPU | | 1.30 | 10.0 | 4.9 | −80 | 83% | 3.36 | 79% |
|
|
186
|
+
| DiffPoseTalk | 129M | whole clip | GPU | ✓ | 1.57 | 11.0 | 17.2 | −96 | 38% | 5.68 | 71% |
|
|
187
|
+
| wawa-lipsync | rules | none | browser | | 1.98 | 11.2 | 12.9 | +240 | 14% | 1.32 | 79% |
|
|
188
|
+
| DualTalk | 647M | whole clip | GPU | ✓ | 2.07 | 11.9 | 15.5 | −64 | 14% | 4.51 | 74% |
|
|
189
|
+
| *Still face* | | | | | *1.00* | – | – | – | *0%* | *0.68* | *77%* |
|
|
190
|
+
|
|
191
|
+
- Every model ran with its public weights and its default settings. Each output is turned into the motion of the same FLAME face and compared with the real speaker.
|
|
192
|
+
- Multiface (612 sentences, 10 people) is the neutral set: none of these models was trained on it. Callable held-out is held-out clips of Callable's proprietary dataset, recorded like our training data, so it favours our models. VOCASET is the field's standard test, and favours the models trained on it (UniTalker, CodeTalker, SelfTalk).
|
|
193
|
+
- † Audio2Face is measured on its own face for the Multiface columns. Models with ARKit output (Audio2Face, LAM-A2E, EmoTalk, SAiD) are otherwise shown through one ARKit rig on FLAME, which may cost them some lip closures.
|
|
194
|
+
- SyncNet and lip reading run on grey renders of the face. Their numbers are relative: the real speaker's render reads far better than any model.
|
|
195
|
+
- Size is the parameter count, audio encoder included. Audio ahead is how much audio after a frame the model uses to make it; "whole clip" models need the whole recording first. tiny's lips use 0.16 s and its head 0.64 s; it also runs with less (0 to 0.64 s, your choice).
|
|
196
|
+
- Speed is not compared: ours run on one CPU thread, the others on a GPU.
|
|
197
|
+
|
|
198
|
+
</details>
|
|
199
|
+
<!-- benchmarks:end -->
|
|
200
|
+
|
|
201
|
+
<br/>
|
|
202
|
+
|
|
121
203
|
<h2 align="center">Models</h2>
|
|
122
204
|
<br/>
|
|
123
205
|
|
|
@@ -136,11 +218,11 @@ Python and JavaScript run the same engine: the same audio and seed give the same
|
|
|
136
218
|
| Streaming, any chunk size | ✅ | ✅ |
|
|
137
219
|
| ARKit blendshape weights | ✅ | ✅ |
|
|
138
220
|
| Python and JavaScript | ✅ | ✅ |
|
|
139
|
-
| Parameters |
|
|
140
|
-
| Size (ONNX, 8-bit weights) | 17.
|
|
221
|
+
| Parameters | 17.1M | 2.4M |
|
|
222
|
+
| Size (ONNX, 8-bit weights) | 17.7 MB | 2.5 MB |
|
|
141
223
|
| Audio ahead | 0 to 0.64 s, your choice | 0.16 s, fixed |
|
|
142
224
|
| Python, one thread | 1.1 ms a frame | 0.4 ms a frame |
|
|
143
|
-
| Browser (WebAssembly), one thread | 5.
|
|
225
|
+
| Browser (WebAssembly), one thread | 5.9 ms a frame | 2.2 ms a frame |
|
|
144
226
|
|
|
145
227
|
Measured on an AMD Ryzen 7 9700X; a frame is 40 ms of audio. `tiny` at 0.64 s of audio ahead.
|
|
146
228
|
|
|
@@ -199,6 +281,52 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
|
|
|
199
281
|
|
|
200
282
|
<br/>
|
|
201
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.
|
|
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/>
|
|
202
330
|
<h2 align="center">Typical Use Cases</h2>
|
|
203
331
|
<br/>
|
|
204
332
|
|
|
@@ -218,11 +346,13 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
|
|
|
218
346
|
- ✅ JavaScript package (`npm install callable-lipsync`), for browsers and Node
|
|
219
347
|
- ✅ FLAME 2023 Open output
|
|
220
348
|
- ✅ ARKit blendshape converter in both packages
|
|
221
|
-
- ✅ Browser demo
|
|
349
|
+
- ✅ Browser demo, with your own audio or your microphone
|
|
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
|
|
222
353
|
|
|
223
354
|
**Planned**
|
|
224
355
|
|
|
225
|
-
- ⬜ Benchmarks
|
|
226
356
|
- ⬜ Unreal Engine MetaHuman support
|
|
227
357
|
- ⬜ VRM model support
|
|
228
358
|
- ⬜ Unity support
|
|
@@ -231,7 +361,9 @@ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come st
|
|
|
231
361
|
<h2 align="center">Links</h2>
|
|
232
362
|
<br/>
|
|
233
363
|
|
|
234
|
-
- [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)
|
|
235
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)
|
|
236
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)
|
|
237
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)
|
|
@@ -248,7 +380,13 @@ Try the models, create an [issue](https://github.com/callabledev/callable-lipsyn
|
|
|
248
380
|
- One speaker at a time. Feed it a mix of two voices and it will lip-sync both.
|
|
249
381
|
- Measured mostly on English. It listens to sound, not text, so other languages work, but we have not measured how well.
|
|
250
382
|
- No tongue and no teeth in the output.
|
|
251
|
-
- 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).
|
|
252
390
|
|
|
253
391
|
**Model card**
|
|
254
392
|
|
|
@@ -276,4 +414,4 @@ Try the models, create an [issue](https://github.com/callabledev/callable-lipsyn
|
|
|
276
414
|
<h2 align="center">Third-party material</h2>
|
|
277
415
|
<br/>
|
|
278
416
|
|
|
279
|
-
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(
|
|
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(
|
|
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.0'; // 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,13 @@
|
|
|
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
|
+
}
|
|
12
|
+
/** Drive a TalkingHead avatar (its ARKit blend shapes, head and body) from the node. Returns a function that gives it back. */
|
|
13
|
+
export declare function driveTalkingHead(head: unknown, lip: LipSyncNode, options?: DriveOptions): () => void;
|
|
@@ -0,0 +1,134 @@
|
|
|
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) and the
|
|
30
|
+
// head bone by headRotate + bodyRotate. So bodyRotate = chest / share turns the torso as the model's chest, and
|
|
31
|
+
// headRotate = neck - chest / share leaves the head bone the model's neck: the head lands at chest + neck, as in the model.
|
|
32
|
+
const SHARE = [1 / 2 + 1 / 8 + 1 / 24, 1 / 2 + 1 / 2 + 1 / 4, 1 / 12 + 1 / 12 + 1 / 24];
|
|
33
|
+
// its own shapes that would add to ours: the mouth mixes and the visemes always, the eye mixes while the model has the eyes
|
|
34
|
+
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'];
|
|
35
|
+
const QUIET_EYES = ['eyesClosed', 'eyesLookUp', 'eyesLookDown'];
|
|
36
|
+
// TalkingHead's eye contact (read each time it plans a look): off while the model has the eyes. Its head moves are fixed
|
|
37
|
+
// when it starts, so they stay; the model's head turns override them while it has frames.
|
|
38
|
+
const LOOKS = ['avatarIdleEyeContact', 'avatarSpeakingEyeContact'];
|
|
39
|
+
const isEye = (n) => n.startsWith('eyeBlink') || n.startsWith('eyeLook'); // blinks and gaze; eyeSquint and eyeWide are expression, always the model's
|
|
40
|
+
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
41
|
+
|
|
42
|
+
// options: audio (default true: route TalkingHead's speech and stream through the node), head (default true: the head and
|
|
43
|
+
// body turns), eyes (default true: blinks and gaze from the model, with tiny; false leaves them to TalkingHead), gain
|
|
44
|
+
// (default 1: how far the face and head move). Returns a function that gives the avatar back to TalkingHead.
|
|
45
|
+
export function driveTalkingHead(head, lip, { audio = true, head: turns = true, eyes = true, gain = 1 } = {}) {
|
|
46
|
+
if (!head || !head.opt) throw new Error('callable-lipsync: driveTalkingHead needs a TalkingHead'); // before showAvatar too: the avatar is picked up when it comes
|
|
47
|
+
if (audio && (head.audioCtx !== lip.ctx || head.opt.audioCtx !== lip.ctx)) throw new Error('callable-lipsync: make one AudioContext and give it to both: new TalkingHead(el, { audioCtx: ctx }) and LipSyncNode.create(ctx) (or pass { audio: false })');
|
|
48
|
+
let mt = null, set = null, names = null, eyesOn = null, active = false, outTo = null, warned = false, bare = false, released = false;
|
|
49
|
+
const routed = new Map(); // TalkingHead's gain nodes sent into the node -> the reverb each played to
|
|
50
|
+
const before = head.opt.update, limits = new Map(), looks = new Map();
|
|
51
|
+
|
|
52
|
+
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)
|
|
53
|
+
if (!set) return;
|
|
54
|
+
const back = (m) => { m.realtime = null; if (m.baseline == null) m.base = 0; m.needsUpdate = true; };
|
|
55
|
+
for (const [m, , eye] of set.shapes) if (all || !eye || !eyesOn) back(m);
|
|
56
|
+
for (const m of [...set.quiet, ...set.quietEyes, ...set.rot.map(([r]) => r)]) back(m);
|
|
57
|
+
active = false;
|
|
58
|
+
}
|
|
59
|
+
function eyesTo(on) { // hand the eyes to the model (on) or back to TalkingHead
|
|
60
|
+
if (on === eyesOn) return; eyesOn = on;
|
|
61
|
+
if (on) {
|
|
62
|
+
const av = head.avatar || {}; // the avatar these belong to, so they go back onto it (not onto a newer one)
|
|
63
|
+
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; }
|
|
64
|
+
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
|
|
65
|
+
} else {
|
|
66
|
+
for (const [k, [o, av, wasOwn, v]] of looks) { head.opt[k] = o; if (wasOwn) av[k] = v; } looks.clear();
|
|
67
|
+
for (const [k, l] of limits) if (mt[k]) mt[k].limit = l; limits.clear();
|
|
68
|
+
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; }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function build() { // what we set on the avatar now shown
|
|
72
|
+
const get = (list) => list.map((n) => mt[n]).filter(Boolean);
|
|
73
|
+
set = { shapes: (names || []).map((n, i) => [mt[n], i, isEye(n)]).filter(([m]) => m), quiet: get(QUIET), quietEyes: get(QUIET_EYES),
|
|
74
|
+
rot: turns ? [...HEAD, ...BODY].filter(([n]) => mt[n]).map(([n, k]) => [mt[n], k, BODY.some(([b]) => b === n)]) : [] };
|
|
75
|
+
}
|
|
76
|
+
function bind() { // (again) for the avatar now shown: its morph targets, and the shape names the node knows
|
|
77
|
+
if (mt === head.mtAvatar && names === lip.names) return;
|
|
78
|
+
names = lip.names;
|
|
79
|
+
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
|
|
80
|
+
const on = eyesOn; eyesTo(false); free(true);
|
|
81
|
+
mt = head.mtAvatar; eyesOn = null; build(); free(true); if (on) eyesTo(true); return;
|
|
82
|
+
}
|
|
83
|
+
mt = head.mtAvatar; build();
|
|
84
|
+
}
|
|
85
|
+
function route() { // TalkingHead's speech and stream into the node, its output to the reverb (again, if TalkingHead rebuilt its graph)
|
|
86
|
+
if (!audio || lip.disposed) return; // a disposed node takes no audio: what it had goes back once, in update()
|
|
87
|
+
const now = [head.audioSpeechGainNode, head.audioStreamGainNode].filter((n) => n && !routed.has(n));
|
|
88
|
+
if (!now.length && outTo === head.audioReverbNode) return;
|
|
89
|
+
if (head.audioCtx !== lip.ctx) {
|
|
90
|
+
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); }
|
|
91
|
+
warned = true; return;
|
|
92
|
+
}
|
|
93
|
+
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)
|
|
94
|
+
// (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)
|
|
95
|
+
if (outTo !== head.audioReverbNode) { if (outTo) { try { lip.output.disconnect(outTo); } catch (e) { /* already */ } } outTo = head.audioReverbNode; lip.output.connect(outTo); }
|
|
96
|
+
}
|
|
97
|
+
function unroute() {
|
|
98
|
+
for (const [n, reverb] of routed) { try { n.disconnect(lip.input); } catch (e) { /* already */ } try { n.connect(reverb); } catch (e) { /* its context is gone */ } }
|
|
99
|
+
if (outTo) { try { lip.output.disconnect(outTo); } catch (e) { /* already */ } } routed.clear(); outTo = null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
bind(); route();
|
|
103
|
+
const rebuild = head.initAudioGraph; // TalkingHead's own graph rebuild (a stream at another sample rate): routed at once, before any audio plays through it
|
|
104
|
+
const wrapped = function (...a) { const r = rebuild.apply(this, a); if (!released) route(); return r; };
|
|
105
|
+
if (typeof rebuild === 'function') head.initAudioGraph = wrapped;
|
|
106
|
+
head.opt.update = (dt) => {
|
|
107
|
+
if (before) before(dt);
|
|
108
|
+
if (released) return; // still called by a hook wrapped around ours after release: does nothing
|
|
109
|
+
bind(); route();
|
|
110
|
+
const w = lip.weights(), f = lip.frame();
|
|
111
|
+
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
|
|
112
|
+
if (!lip.running) { eyesTo(false); if (active) free(true); return; } // the node stopped: the face (eyes too) is TalkingHead's
|
|
113
|
+
if (!w || !f) return; // a new stream's first frames are on their way: the last pose holds
|
|
114
|
+
if (lip.names && !set.shapes.length && !bare) { bare = true; console.warn('callable-lipsync: this avatar has none of the ARKit blend shapes: only its head turns follow the model'); }
|
|
115
|
+
const nano = lip.model === 'nano'; eyesTo(eyes && !nano);
|
|
116
|
+
for (const [m, i, eye] of set.shapes) { if (eye && !eyesOn) continue; m.realtime = eye ? w[i] : Math.min(1, gain * w[i]); m.needsUpdate = true; }
|
|
117
|
+
for (const m of set.quiet) { m.realtime = 0; m.needsUpdate = true; }
|
|
118
|
+
if (eyesOn) for (const m of set.quietEyes) { m.realtime = 0; m.needsUpdate = true; }
|
|
119
|
+
const withBody = !nano && set.rot.some(([, , body]) => body), clamp = (x) => Math.max(-1, Math.min(1, x));
|
|
120
|
+
for (const [m, k, body] of set.rot) {
|
|
121
|
+
if (body && nano) { if (m.realtime !== null) { m.realtime = null; m.base = 0; m.needsUpdate = true; } continue; }
|
|
122
|
+
const torso = (i) => clamp(gain * f[100 + i] / SHARE[i]); // bodyRotate for axis i
|
|
123
|
+
m.realtime = body ? torso(k - 100) : withBody ? gain * f[k] - torso(k - 106) : gain * f[k]; m.needsUpdate = true;
|
|
124
|
+
}
|
|
125
|
+
active = true;
|
|
126
|
+
};
|
|
127
|
+
const hook = head.opt.update;
|
|
128
|
+
return () => { // once; the update hook goes back only if it is still ours (someone may have wrapped it since)
|
|
129
|
+
if (released) return; released = true;
|
|
130
|
+
if (head.opt.update === hook) head.opt.update = before;
|
|
131
|
+
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
|
|
132
|
+
bind(); eyesTo(false); free(true); unroute(); // bind(): a new avatar shown since the last frame is cleaned up too
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -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);
|