wireface 1.1.4 → 1.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/dist/wireface.js CHANGED
@@ -22,8 +22,29 @@
22
22
  * play(fromOffset?) → void
23
23
  * pause() → void
24
24
  * stop() → void
25
+ * setMuted(bool) / isMuted() → void/bool (analyse the loaded audio without sounding it)
26
+ * attachAudio(source) → void (lips follow a MediaStream or AudioNode the
27
+ * library does not play; never made audible)
28
+ * pushAudio(samples, rate, opts?)→ number (streamed PCM chunks drive the lips, on a clock;
29
+ * opts { at, run, end, delay, lead, audible };
30
+ * returns seconds queued)
31
+ * cutAudio(run?) → void (drop queued speech now; late chunks of the run too)
32
+ * isSpeaking() → bool
33
+ * on(event, fn) → () => void ('speechstart','speechend','underrun','behaviour';
34
+ * returns the unsubscribe function)
35
+ * detachAudio() → void
36
+ * getPreset() → object (the face's design, as loadPreset() takes it)
25
37
  * setMood(name) → void ('neutral','happy','sad','angry','fear','surprise','sleep')
26
- * setChannel(name, value) → void (manual override, auto-releases ~1.2s)
38
+ * setBehaviour(name, opts?) → bool (named framing recipe: yaw, pitch, zoom, dim, mood —
39
+ * glides there; opts { side, glide, for }; null clears)
40
+ * defineBehaviours(recipes) → void (add / override recipes; accepts { recipes, glide_s })
41
+ * getBehaviour() → string|null
42
+ * getBehaviourNames() → string[]
43
+ * getBehaviours() → object (copy of the recipe table)
44
+ * setChannel(name, value, opts?)→ void (manual override, auto-releases ~1.2s;
45
+ * opts { hold } keeps it until releaseChannel,
46
+ * opts { smooth } eases to the value)
47
+ * releaseChannel(name) → void
27
48
  * setChannelGain(name, gain) → void (multiplier on channel before render)
28
49
  * getChannel(name) → number (current smoothed value)
29
50
  * getChannelTarget(name) → number (latest target before smoothing)
@@ -188,8 +209,56 @@
188
209
  // is jawOpen-driven). Default 0 = current behavior.
189
210
  upperJawProtrude: 0.0, lowerJawProtrude: 0.0,
190
211
  cameraView: 'three-q', // initial view
212
+ // scene clear colour behind the face. Saved with the preset like every
213
+ // other colour, so each face can carry its own backdrop.
214
+ backgroundColor: '#000000',
191
215
  };
192
216
 
217
+ /* Named behaviours — framing recipes a face glides to, set by name the same
218
+ way a mood is (setBehaviour('attend')). The caller says what is going on;
219
+ the library owns the camera physics, so no camera object is exposed.
220
+ yaw radians the face is turned away from the viewer (0 = facing you)
221
+ pitch radians, positive looks down
222
+ zoom 1 = normal, bigger = closer
223
+ dim 0..1 brightness
224
+ mood a mood name, or 'persona' (the face's own mood)
225
+ toward advisory for the page: turn the yaw toward whoever holds the
226
+ floor — pass opts.side (-1 | 1) to setBehaviour
227
+ focus what the shot centres on: 'face' | 'center' | 'eyes' | 'nose' | 'mouth'
228
+ hop height of a short bounce on entry (scene units)
229
+ for seconds; a transient behaviour returns to the previous one
230
+ The first ten are states of a face in a group; the rest are shots.
231
+ Full table: SPEC.WIREFACE.BEHAVIOURS.v1.2.md §2. */
232
+ const BEHAVIOURS = {
233
+ asleep: { yaw: 0.60, pitch: 0.10, zoom: 0.80, dim: 0.55, mood: 'sleep', toward: false },
234
+ parked: { yaw: 0.65, pitch: 0.05, zoom: 0.82, dim: 0.60, mood: 'neutral', toward: true },
235
+ idle: { yaw: 0.45, pitch: 0.00, zoom: 0.90, dim: 0.75, mood: 'neutral', toward: true },
236
+ waiting: { yaw: 0.30, pitch: 0.00, zoom: 0.95, dim: 0.85, mood: 'neutral', toward: true },
237
+ busy: { yaw: 0.25, pitch: 0.22, zoom: 1.00, dim: 0.90, mood: 'fear', toward: false },
238
+ listen: { yaw: 0.00, pitch:-0.04, zoom: 1.10, dim: 1.00, mood: 'neutral', toward: false },
239
+ speak: { yaw: 0.00, pitch: 0.00, zoom: 1.22, dim: 1.00, mood: 'persona', toward: false },
240
+ attend: { yaw: 0.00, pitch:-0.06, zoom: 1.35, dim: 1.00, mood: 'happy', toward: false },
241
+ important: { yaw: 0.00, pitch:-0.08, zoom: 1.35, dim: 1.00, mood: 'surprise', toward: false },
242
+ cut: { yaw: 0.15, pitch: 0.08, zoom: 1.05, dim: 0.90, mood: 'surprise', toward: false },
243
+ // shots
244
+ point: { yaw: 0.00, pitch:-0.03, zoom: 1.70, dim: 1.00, mood: 'persona' },
245
+ distant: { yaw: 0.50, pitch: 0.04, zoom: 0.55, dim: 0.70, mood: 'neutral', toward: true },
246
+ away: { yaw: 0.80, pitch: 0.06, zoom: 0.90, dim: 0.80, mood: 'neutral' },
247
+ work: { yaw: 0.30, pitch: 0.32, zoom: 0.95, dim: 0.85, mood: 'neutral' },
248
+ jump: { yaw: 0.00, pitch:-0.06, zoom: 1.30, dim: 1.00, mood: 'surprise', hop: 0.30, for: 1.6 },
249
+ closeup: { yaw: 0, pitch: 0, zoom: 2.20, dim: 1, mood: 'persona', focus: 'center' },
250
+ 'closeup-eyes': { yaw: 0, pitch: 0, zoom: 2.40, dim: 1, mood: 'persona', focus: 'eyes' },
251
+ 'closeup-nose': { yaw: 0, pitch: 0, zoom: 3.00, dim: 1, mood: 'persona', focus: 'nose' },
252
+ 'closeup-mouth': { yaw: 0, pitch: 0, zoom: 2.80, dim: 1, mood: 'persona', focus: 'mouth' },
253
+ };
254
+ /* camera radius at zoom 1, and the height each focus centres on (face-local
255
+ y; warpToFace puts the eyes at +0.20 and the mouth at −0.38). */
256
+ const BEHAVIOUR_RADIUS = 3.3;
257
+ const FOCUS_Y = { face: 0, center: -0.08, eyes: 0.20, nose: -0.05, mouth: -0.38 };
258
+ const HEAD_CHANNELS = { headRotateX: 1, headRotateY: 1, headRotateZ: 1 };
259
+ const LIP_CHANNELS = { jawOpen: 1 };
260
+ for (const v of Object.keys(VISEME_PARAMS)) LIP_CHANNELS['viseme_' + v] = 1;
261
+
193
262
  /* ─── module helpers ─────────────────────────────────────────────────── */
194
263
 
195
264
  function hex2rgb(hex) {
@@ -201,6 +270,40 @@
201
270
  ];
202
271
  }
203
272
 
273
+ /* ── spectrum for the speech timeline ──
274
+ What an AnalyserNode computes, done here on the samples themselves:
275
+ fftSize 1024 at 48 kHz, one frame every 800 samples (60 per second),
276
+ smoothingTimeConstant 0.4. Radix-2 FFT, in place. */
277
+ const AN_RATE = 48000, FFT_N = 1024, AN_HOP = 800, AN_SMOOTH = 0.4;
278
+ const HOP_MS = 1000 * AN_HOP / AN_RATE;
279
+ const FFT_REV = new Uint16Array(FFT_N), FFT_COS = new Float32Array(FFT_N / 2), FFT_SIN = new Float32Array(FFT_N / 2);
280
+ const BLACKMAN = new Float32Array(FFT_N);
281
+ for (let i = 0; i < FFT_N; i++) {
282
+ let r = 0;
283
+ for (let b = 0; b < 10; b++) r |= ((i >> b) & 1) << (9 - b);
284
+ FFT_REV[i] = r;
285
+ BLACKMAN[i] = 0.42 - 0.5 * Math.cos(2 * Math.PI * i / FFT_N) + 0.08 * Math.cos(4 * Math.PI * i / FFT_N);
286
+ }
287
+ for (let i = 0; i < FFT_N / 2; i++) { FFT_COS[i] = Math.cos(2 * Math.PI * i / FFT_N); FFT_SIN[i] = Math.sin(2 * Math.PI * i / FFT_N); }
288
+ function fft(re, im) {
289
+ for (let i = 0; i < FFT_N; i++) {
290
+ const j = FFT_REV[i];
291
+ if (j > i) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
292
+ }
293
+ for (let size = 2; size <= FFT_N; size <<= 1) {
294
+ const half = size >> 1, stride = FFT_N / size;
295
+ for (let i = 0; i < FFT_N; i += size) {
296
+ for (let j = 0, k = 0; j < half; j++, k += stride) {
297
+ const c = FFT_COS[k], sn = -FFT_SIN[k];
298
+ const a = i + j, b = a + half;
299
+ const tr = re[b] * c - im[b] * sn, ti = re[b] * sn + im[b] * c;
300
+ re[b] = re[a] - tr; im[b] = im[a] - ti;
301
+ re[a] += tr; im[a] += ti;
302
+ }
303
+ }
304
+ }
305
+ }
306
+
204
307
  /* ──────────────────────────────────────────────────────────────────────
205
308
  * F A C T O R Y
206
309
  * ────────────────────────────────────────────────────────────────────── */
@@ -224,6 +327,12 @@
224
327
  const state = {};
225
328
  const stateTarget = {};
226
329
  const manualLock = {};
330
+ /* what a caller set through setChannel, kept apart from stateTarget: the
331
+ drivers (idle, mood blend, audio) keep writing stateTarget every frame,
332
+ and before v1.2 that overwrote any manual value on a driven channel in
333
+ the same frame it was set. */
334
+ const manualValue = {};
335
+ const manualSmooth = {};
227
336
  const channelGains = {};
228
337
  CHANNEL_NAMES.forEach(n => {
229
338
  state[n] = CHANNELS[n].def;
@@ -263,7 +372,7 @@
263
372
  // rewiring.
264
373
  const scene = new BABYLON.Scene(engine, { useRightHandedSystem: true });
265
374
  scene.useRightHandedSystem = true; // belt and braces — also assign post-ctor
266
- scene.clearColor = new BABYLON.Color4(0, 0, 0, 1);
375
+ scene.clearColor = new BABYLON.Color4(0, 0, 0, 1); // applyBackgroundColor() sets the configured one
267
376
  // we never pick on pointer-move; saves a per-frame ray test
268
377
  scene.skipPointerMovePicking = true;
269
378
 
@@ -1207,14 +1316,28 @@
1207
1316
 
1208
1317
  /* ── channel smoothing + mood blend + idle ── */
1209
1318
  function smoothChannels(dt) {
1319
+ const snapping = tl.snapUntil > performance.now();
1210
1320
  for (const ch of CHANNEL_NAMES) {
1211
- if (manualLock[ch]) { state[ch] = stateTarget[ch]; continue; }
1212
- const k = SMOOTH[ch] || SMOOTH.default;
1321
+ let target = stateTarget[ch];
1322
+ if (manualLock[ch]) {
1323
+ target = manualValue[ch];
1324
+ // a held head pose keeps the idle sway on top of it
1325
+ if (HEAD_CHANNELS[ch]) {
1326
+ const r = CHANNELS[ch].range;
1327
+ target = Math.max(r[0], Math.min(r[1], target + _bob[ch]));
1328
+ }
1329
+ if (!manualSmooth[ch]) { state[ch] = target; continue; }
1330
+ }
1331
+ // the mood's jaw under the speech: speech opens what the mood left closed
1332
+ else if (ch === 'jawOpen' && moodJaw > 0) target = moodJaw + target * (1 - moodJaw);
1333
+ let k = SMOOTH[ch] || SMOOTH.default;
1334
+ if (snapping && LIP_CHANNELS[ch]) k *= 3;
1213
1335
  const a = 1 - Math.exp(-k * dt * 30);
1214
- state[ch] = state[ch] + (stateTarget[ch] - state[ch]) * a;
1336
+ state[ch] = state[ch] + (target - state[ch]) * a;
1215
1337
  }
1216
1338
  }
1217
1339
 
1340
+ let moodJaw = 0;
1218
1341
  function updateMoodBlend(dt) {
1219
1342
  const T = Math.max(0.05, config.moodTransitionTime);
1220
1343
  const halflife = T / 4;
@@ -1227,6 +1350,13 @@
1227
1350
  for (const m of MOOD_NAMES) target += (MOODS[m][ch] || 0) * moodCurrentWeights[m];
1228
1351
  stateTarget[ch] = target;
1229
1352
  }
1353
+ // A mood's jaw. jawOpen is not a mood channel — speech owns its target —
1354
+ // so the mood's share is kept apart and laid under the speech in
1355
+ // smoothChannels. Until v1.3 it was never read: 'surprise' declared a
1356
+ // jaw drop and showed none.
1357
+ let jaw = 0;
1358
+ for (const m of MOOD_NAMES) jaw += (MOODS[m].jawOpen || 0) * moodCurrentWeights[m];
1359
+ moodJaw = Math.max(0, Math.min(1, jaw));
1230
1360
  }
1231
1361
 
1232
1362
  /* ── idle micro-animations: blinks + saccades + head bob ── */
@@ -1236,6 +1366,7 @@
1236
1366
  let _saccadeAccum = 0;
1237
1367
  let _saccTargetH = 0, _saccTargetV = 0;
1238
1368
  let _bobT = 0;
1369
+ const _bob = { headRotateX: 0, headRotateY: 0, headRotateZ: 0 };
1239
1370
  function idleAnimate(dt) {
1240
1371
  // blinks
1241
1372
  _blinkAccum += dt;
@@ -1262,9 +1393,12 @@
1262
1393
  stateTarget.eyeLookV = _saccTargetV;
1263
1394
  // head bob — gentle sway
1264
1395
  _bobT += dt;
1265
- stateTarget.headRotateX = Math.sin(_bobT * 0.27) * 0.04;
1266
- stateTarget.headRotateY = Math.sin(_bobT * 0.19) * 0.06;
1267
- stateTarget.headRotateZ = Math.sin(_bobT * 0.11) * 0.03;
1396
+ _bob.headRotateX = Math.sin(_bobT * 0.27) * 0.04;
1397
+ _bob.headRotateY = Math.sin(_bobT * 0.19) * 0.06;
1398
+ _bob.headRotateZ = Math.sin(_bobT * 0.11) * 0.03;
1399
+ stateTarget.headRotateX = _bob.headRotateX;
1400
+ stateTarget.headRotateY = _bob.headRotateY;
1401
+ stateTarget.headRotateZ = _bob.headRotateZ;
1268
1402
  }
1269
1403
 
1270
1404
  /* ── audio analysis for live lip-sync ── */
@@ -1276,6 +1410,9 @@
1276
1410
  let pausedAt = 0;
1277
1411
  let isPlayingFlag = false;
1278
1412
  let audioFreqData = null;
1413
+ let outGain = null; // playback volume: 0 when muted, so the analyser still runs
1414
+ let muted = false;
1415
+ let ext = null; // outside audio attached with attachAudio()
1279
1416
 
1280
1417
  function ensureAudioCtx() {
1281
1418
  if (!audioCtx) {
@@ -1302,8 +1439,11 @@
1302
1439
  analyser.fftSize = 1024;
1303
1440
  analyser.smoothingTimeConstant = 0.4;
1304
1441
  audioFreqData = new Uint8Array(analyser.frequencyBinCount);
1442
+ outGain = audioCtx.createGain();
1443
+ outGain.gain.value = muted ? 0 : 1;
1305
1444
  audioSource.connect(analyser);
1306
- analyser.connect(audioCtx.destination);
1445
+ analyser.connect(outGain);
1446
+ outGain.connect(audioCtx.destination);
1307
1447
  audioStartCtxTime = audioCtx.currentTime - (fromOffset || 0);
1308
1448
  audioSource.start(0, fromOffset || 0);
1309
1449
  audioSource.onended = () => {
@@ -1325,69 +1465,413 @@
1325
1465
  audioSource = null;
1326
1466
  }
1327
1467
  if (analyser) { try { analyser.disconnect(); } catch (_) {} analyser = null; }
1468
+ if (outGain) { try { outGain.disconnect(); } catch (_) {} outGain = null; }
1328
1469
  isPlayingFlag = false;
1329
1470
  }
1330
1471
 
1331
- function getPlaybackTime() {
1332
- if (!audioCtx || !audioBuffer) return 0;
1333
- if (isPlayingFlag) return audioCtx.currentTime - audioStartCtxTime;
1334
- return pausedAt || 0;
1472
+ function silenceLips() {
1473
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1474
+ stateTarget.viseme_sil = 1;
1475
+ stateTarget.jawOpen = 0;
1476
+ }
1477
+
1478
+ /* An analyser whose input goes quiet can stop being processed, and then
1479
+ keeps answering with its last spectrum — the mouth would freeze open
1480
+ when a stream ends. A constant source far below audibility (−180 dB,
1481
+ at 0 Hz, outside every band read here) keeps it running. */
1482
+ function keepAnalysing(ctx, an) {
1483
+ if (!ctx.createConstantSource) return null;
1484
+ const k = ctx.createConstantSource();
1485
+ k.offset.value = 1e-9;
1486
+ k.connect(an);
1487
+ k.start();
1488
+ return k;
1335
1489
  }
1336
1490
 
1337
- function freqEnergyHz(lo, hi) {
1338
- if (!audioFreqData) return 0;
1339
- const sr = audioCtx.sampleRate;
1340
- const binHz = sr / 2 / audioFreqData.length;
1491
+ /* Outside audio: speech the library does not play itself (a WebRTC or
1492
+ microphone stream, another graph's node). It runs through the same
1493
+ analyser → viseme pipeline as loadAudio()/play(), so the lips match the
1494
+ built-in path. The tap ends in a zero gain: wireface never makes
1495
+ attached audio audible — whoever owns the source plays it. */
1496
+ function attachAudio(source) {
1497
+ detachAudio();
1498
+ let node = null, owned = false;
1499
+ if (source && typeof source.connect === 'function' && source.context) {
1500
+ node = source;
1501
+ } else if (typeof MediaStream !== 'undefined' && source instanceof MediaStream) {
1502
+ ensureAudioCtx();
1503
+ node = audioCtx.createMediaStreamSource(source);
1504
+ owned = true;
1505
+ } else {
1506
+ throw new Error('wireface.attachAudio: expected a MediaStream or an AudioNode');
1507
+ }
1508
+ const ctx = node.context;
1509
+ const an = ctx.createAnalyser();
1510
+ an.fftSize = 1024;
1511
+ an.smoothingTimeConstant = 0.4;
1512
+ const sink = ctx.createGain();
1513
+ sink.gain.value = 0;
1514
+ node.connect(an);
1515
+ an.connect(sink);
1516
+ sink.connect(ctx.destination);
1517
+ ext = { node, an, sink, owned, keep: keepAnalysing(ctx, an), data: new Uint8Array(an.frequencyBinCount) };
1518
+ }
1519
+
1520
+ /* ── the lip analysis, as a pure function of five band energies ──
1521
+ One allocation, two callers: the live analyser (playback, attached
1522
+ audio) and the speech timeline (pushAudio). A lip frame is nine values:
1523
+ [sil, jaw, SS, FF, O, aa, U, E, I]. */
1524
+ const LIP_SLOTS = ['viseme_sil', 'jawOpen', 'viseme_SS', 'viseme_FF', 'viseme_O',
1525
+ 'viseme_aa', 'viseme_U', 'viseme_E', 'viseme_I'];
1526
+ const LIP_SILENT = new Float32Array([1, 0, 0, 0, 0, 0, 0, 0, 0]);
1527
+ function lipFrame(eLow, eMid, eHi, eSib, eAir, out) {
1528
+ out.fill(0);
1529
+ const amp = Math.max(eLow, eMid, eHi, eSib);
1530
+ if (amp < 0.08) { out[0] = 1; return out; }
1531
+ out[1] = amp * 0.7;
1532
+ // Proportional viseme allocation. v1.1.5: previous version was a
1533
+ // winner-takes-all branch tree where viseme_aa fired for any vowel-
1534
+ // like sound with low+mid energy, dominating with avg ~0.77 on TTS
1535
+ // input and leaving the mouth stuck wide-open. This approach instead
1536
+ // distributes amp across visemes by their corresponding band's share
1537
+ // of total energy, so the mouth shape blends through the audio's
1538
+ // formant spectrum frame-by-frame.
1539
+ const totalE = eLow + eMid + eHi + eSib + 1e-6;
1540
+ // Sibilants — sharp, high-energy fricatives. Boost separately because
1541
+ // they need to register as distinct mouth shapes (close lips + teeth)
1542
+ // even at modest absolute energy.
1543
+ if (eSib > 0.20) {
1544
+ out[2] = Math.min(1, eSib * 1.4);
1545
+ if (eAir > 0.20) out[3] = Math.min(0.7, eAir * 0.9);
1546
+ }
1547
+ // Vowels — proportional distribution across F1/F2 bands.
1548
+ // viseme_O uses low energy when low dominates (back rounded vowel).
1549
+ // viseme_aa uses mid energy (open vowel — F1 mid+low balanced).
1550
+ // viseme_E uses mid energy in front vowel range.
1551
+ // viseme_I uses high energy (high F2 = front close vowel).
1552
+ // viseme_U uses low when low dominates AND amp moderate (closed back).
1553
+ const wLow = eLow / totalE, wMid = eMid / totalE, wHi = eHi / totalE;
1554
+ if (eLow > eMid && eLow > 0.18) {
1555
+ // back vowel territory
1556
+ out[4] = Math.min(1, eLow * 1.1 * (eHi < 0.20 ? 1.1 : 0.8));
1557
+ out[5] = Math.min(1, wMid * amp * 1.6);
1558
+ if (eHi < 0.18) out[6] = Math.min(0.7, eLow * 0.9);
1559
+ } else if (eMid >= eLow * 0.9) {
1560
+ // mid / front vowel territory
1561
+ out[5] = Math.min(1, wLow * amp * 1.6);
1562
+ out[7] = Math.min(1, wMid * amp * 1.4);
1563
+ if (eHi > 0.18) out[8] = Math.min(1, wHi * amp * 1.5);
1564
+ }
1565
+ return out;
1566
+ }
1567
+ function applyLipFrame(f) {
1568
+ for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1569
+ for (let i = 0; i < LIP_SLOTS.length; i++) stateTarget[LIP_SLOTS[i]] = f[i];
1570
+ }
1571
+ /* mean of a byte spectrum over a band, 0..1 */
1572
+ function bandEnergy(data, rate, lo, hi) {
1573
+ const binHz = rate / 2 / data.length;
1341
1574
  const i0 = Math.max(0, Math.floor(lo / binHz));
1342
- const i1 = Math.min(audioFreqData.length - 1, Math.ceil(hi / binHz));
1575
+ const i1 = Math.min(data.length - 1, Math.ceil(hi / binHz));
1343
1576
  let s = 0, n = 0;
1344
- for (let i = i0; i <= i1; i++) { s += audioFreqData[i]; n++; }
1577
+ for (let i = i0; i <= i1; i++) { s += data[i]; n++; }
1345
1578
  return n ? (s / n) / 255 : 0;
1346
1579
  }
1580
+ function lipFrameFromSpectrum(data, rate, out) {
1581
+ return lipFrame(bandEnergy(data, rate, 200, 700), bandEnergy(data, rate, 700, 2000),
1582
+ bandEnergy(data, rate, 2000, 4000), bandEnergy(data, rate, 4000, 8000),
1583
+ bandEnergy(data, rate, 1500, 5000), out);
1584
+ }
1347
1585
 
1586
+ const _liveFrame = new Float32Array(9);
1348
1587
  function analyzeAudioFrame() {
1349
- if (!analyser) return;
1350
- analyser.getByteFrequencyData(audioFreqData);
1351
- // overall amplitude
1352
- const eLow = freqEnergyHz(200, 700);
1353
- const eMid = freqEnergyHz(700, 2000);
1354
- const eHi = freqEnergyHz(2000, 4000);
1355
- const eSib = freqEnergyHz(4000, 8000);
1356
- const eAir = freqEnergyHz(1500, 5000);
1357
- const amp = Math.max(eLow, eMid, eHi, eSib);
1358
- if (amp < 0.08) {
1359
- for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1360
- stateTarget.viseme_sil = 1;
1361
- stateTarget.jawOpen = 0;
1362
- return;
1363
- }
1364
- stateTarget.viseme_sil = 0;
1365
- stateTarget.jawOpen = amp * 0.7;
1366
- // Reset all visemes
1367
- for (const v of Object.keys(VISEME_PARAMS)) {
1368
- if (v !== 'sil') stateTarget['viseme_' + v] = 0;
1588
+ // attached outside audio takes the lips ahead of the library's own playback
1589
+ const an = ext ? ext.an : (isPlayingFlag ? analyser : null);
1590
+ if (!an) return;
1591
+ const data = ext ? ext.data : audioFreqData;
1592
+ an.getByteFrequencyData(data);
1593
+ applyLipFrame(lipFrameFromSpectrum(data, an.context.sampleRate, _liveFrame));
1594
+ }
1595
+
1596
+ /* ── events ── */
1597
+ const listeners = {};
1598
+ function on(name, fn) {
1599
+ if (typeof fn !== 'function') return () => {};
1600
+ (listeners[name] = listeners[name] || []).push(fn);
1601
+ return () => { const l = listeners[name]; const i = l ? l.indexOf(fn) : -1; if (i >= 0) l.splice(i, 1); };
1602
+ }
1603
+ function emit(name, detail) {
1604
+ const l = listeners[name];
1605
+ if (!l) return;
1606
+ for (const fn of l.slice()) { try { fn(detail); } catch (e) { if (typeof console !== 'undefined') console.error('[wireface] ' + name + ' listener', e); } }
1607
+ }
1608
+
1609
+ /* ── the speech timeline (pushAudio) ──
1610
+ Streamed speech is known before it sounds, so it is not analysed live.
1611
+ Each chunk is analysed the moment it arrives — the same windowed
1612
+ spectrum an AnalyserNode produces, at a fixed 48 kHz / 1024 / 60 frames
1613
+ per second — and the lip frames are placed on the page clock
1614
+ (performance.now) at the time their samples will sound. The render loop
1615
+ reads the frame for now + lead. So: the lips can run slightly ahead of
1616
+ the sound and close with it; a chunk can carry an absolute play time;
1617
+ and a silent stream needs no AudioContext at all. */
1618
+ const tl = {
1619
+ frames: [], head: 0, // queued lip frames { t, v, run }, time-ordered
1620
+ prev: null, // the last frame at or before the clock
1621
+ ring: new Float32Array(FFT_N), ringPos: 0, sinceHop: 0,
1622
+ mag: new Float32Array(FFT_N / 2), bytes: new Uint8Array(FFT_N / 2),
1623
+ re: new Float32Array(FFT_N), im: new Float32Array(FFT_N),
1624
+ end: -1, // clock time where the queued audio ends
1625
+ segT0: 0, segN: 0, // current segment: start time, 48 kHz samples written
1626
+ phase: 0, last: 0, inRate: 0, // resampler carry between chunks
1627
+ run: undefined, ended: false, // the run being queued, and whether its last chunk was flagged
1628
+ cut: [], // run ids that were cut: their late chunks are dropped
1629
+ active: false, spoke: false, spokeRun: undefined, dry: 0,
1630
+ // Defaults measured at 60 fps on a steady tone: the mouth starts to open
1631
+ // 40 ms before the sound, is 80% closed as the sound ends and under 0.05
1632
+ // 80 ms after it. With lead 0 and release 0 that is +33 ms and +250 ms.
1633
+ lead: 0.08, // seconds the lips run ahead of the sound
1634
+ release: 0.18, // seconds over which the mouth closes into a known silence
1635
+ snapUntil: 0, // after a cut: close fast until this clock time
1636
+ gain: null, sources: [], // audible chunks
1637
+ };
1638
+ const _mix = new Float32Array(9);
1639
+ const queuedSeconds = () => Math.max(0, (tl.end - performance.now()) / 1000);
1640
+
1641
+ function emitLipFrame(t, run) {
1642
+ // the window an AnalyserNode sees: the latest FFT_N samples, Blackman, |X|/N,
1643
+ // smoothed over time, in dB, mapped −100…−30 dB onto 0…255
1644
+ const re = tl.re, im = tl.im, ring = tl.ring;
1645
+ for (let i = 0; i < FFT_N; i++) { re[i] = ring[(tl.ringPos + i) & (FFT_N - 1)] * BLACKMAN[i]; im[i] = 0; }
1646
+ fft(re, im);
1647
+ const mag = tl.mag, bytes = tl.bytes;
1648
+ for (let k = 0; k < FFT_N / 2; k++) {
1649
+ const m = Math.sqrt(re[k] * re[k] + im[k] * im[k]) / FFT_N;
1650
+ mag[k] = AN_SMOOTH * mag[k] + (1 - AN_SMOOTH) * m;
1651
+ const b = mag[k] > 0 ? Math.floor((255 / 70) * (20 * Math.log10(mag[k]) + 100)) : 0;
1652
+ bytes[k] = b < 0 ? 0 : b > 255 ? 255 : b;
1369
1653
  }
1370
- // Heuristic mapping
1371
- if (eSib > 0.35 && eSib > eMid * 0.8) {
1372
- stateTarget.viseme_SS = Math.min(1, eSib * 1.3);
1373
- stateTarget.viseme_FF = Math.min(0.6, eAir * 1.2);
1654
+ tl.frames.push({ t, run, v: lipFrameFromSpectrum(bytes, AN_RATE, new Float32Array(9)) });
1655
+ }
1656
+
1657
+ function playChunk(f32, rate, startP, run) {
1658
+ ensureAudioCtx();
1659
+ if (!tl.gain) { tl.gain = audioCtx.createGain(); tl.gain.connect(audioCtx.destination); }
1660
+ const buf = audioCtx.createBuffer(1, f32.length, rate);
1661
+ buf.getChannelData(0).set(f32);
1662
+ const src = audioCtx.createBufferSource();
1663
+ src.buffer = buf;
1664
+ src.connect(tl.gain);
1665
+ // page clock → audio clock. getOutputTimestamp pairs the two at the output
1666
+ // device, so the chunk is HEARD at startP; without it, fall back to the
1667
+ // context's own latency figures.
1668
+ let when;
1669
+ const ts = audioCtx.getOutputTimestamp ? audioCtx.getOutputTimestamp() : null;
1670
+ if (ts && ts.performanceTime > 0 && ts.contextTime > 0) when = ts.contextTime + (startP - ts.performanceTime) / 1000;
1671
+ else when = audioCtx.currentTime + (startP - performance.now()) / 1000 - ((audioCtx.outputLatency || 0) + (audioCtx.baseLatency || 0));
1672
+ const late = audioCtx.currentTime - when;
1673
+ if (late <= 0) src.start(when);
1674
+ else if (late < buf.duration) src.start(0, late);
1675
+ else return;
1676
+ const rec = { src, run, startP };
1677
+ tl.sources.push(rec);
1678
+ src.onended = () => { const i = tl.sources.indexOf(rec); if (i >= 0) tl.sources.splice(i, 1); };
1679
+ }
1680
+
1681
+ /* drop queued lip frames and sounding chunks: all of them, or one run's */
1682
+ function dropQueued(run, fromT) {
1683
+ const all = run === undefined;
1684
+ const keep = [];
1685
+ for (let i = tl.head; i < tl.frames.length; i++) {
1686
+ const f = tl.frames[i];
1687
+ if ((all || f.run === run) && (fromT === undefined || f.t >= fromT)) continue;
1688
+ keep.push(f);
1374
1689
  }
1375
- if (eLow > eMid && eLow > 0.18) {
1376
- if (eHi > 0.25) {
1377
- stateTarget.viseme_aa = Math.min(1, eLow * 1.2);
1378
- } else {
1379
- stateTarget.viseme_O = Math.min(1, eLow * 1.2);
1380
- stateTarget.viseme_U = Math.min(0.7, eLow * 0.9);
1690
+ tl.frames = keep; tl.head = 0;
1691
+ for (const s of tl.sources.slice()) {
1692
+ if ((all || s.run === run) && (fromT === undefined || s.startP >= fromT)) {
1693
+ try { s.src.onended = null; s.src.stop(); s.src.disconnect(); } catch (_) {}
1694
+ tl.sources.splice(tl.sources.indexOf(s), 1);
1381
1695
  }
1382
- } else if (eMid > 0.20) {
1383
- if (eHi > eMid * 0.6) {
1384
- stateTarget.viseme_I = Math.min(1, eHi * 1.4);
1385
- stateTarget.viseme_E = Math.min(0.7, eMid * 1.1);
1386
- } else {
1387
- stateTarget.viseme_E = Math.min(1, eMid * 1.3);
1388
- stateTarget.viseme_aa = Math.min(0.4, eLow * 0.9);
1696
+ }
1697
+ }
1698
+
1699
+ /* Streamed speech: PCM chunks handed over as they arrive — no file, no
1700
+ MediaStream.
1701
+ samples Float32Array (−1..1), Int16Array, or an ArrayBuffer of int16; mono
1702
+ sampleRate of the chunk; any rate
1703
+ opts.at when the chunk's first sample SOUNDS, in wall-clock ms
1704
+ (Date.now() scale). Omitted: chunks follow each other,
1705
+ and a new run starts opts.delay seconds from now.
1706
+ opts.delay lead before a run that has no `at` (default 0.05)
1707
+ opts.run an id for the utterance this chunk belongs to. Chunks of
1708
+ a run that was cut are dropped when they arrive late.
1709
+ opts.end true on the last chunk of a run: speechend fires exactly
1710
+ when it has played
1711
+ opts.audible also sound the chunk (default: silent — the speech is
1712
+ sounded elsewhere)
1713
+ opts.lead seconds the lips run ahead of the sound (default 0.08)
1714
+ opts.release seconds over which the mouth closes into a silence it
1715
+ can see coming (default 0.18; 0 turns it off)
1716
+ Returns the seconds of audio queued ahead, so a sender can pace itself;
1717
+ an empty chunk just reports that figure (and may carry `end`). */
1718
+ function pushAudio(samples, sampleRate, opts) {
1719
+ opts = opts || {};
1720
+ const run = opts.run;
1721
+ if (run !== undefined && tl.cut.indexOf(run) >= 0) return queuedSeconds();
1722
+ if (!samples || (!samples.length && !samples.byteLength)) {
1723
+ if (opts.end && run === tl.run) tl.ended = true;
1724
+ return queuedSeconds();
1725
+ }
1726
+ let f32 = samples;
1727
+ if (!(samples instanceof Float32Array)) {
1728
+ const i16 = (samples instanceof Int16Array) ? samples
1729
+ : new Int16Array(samples.buffer || samples, samples.byteOffset || 0, Math.floor(samples.byteLength / 2));
1730
+ f32 = new Float32Array(i16.length);
1731
+ for (let i = 0; i < i16.length; i++) f32[i] = i16[i] / 32768;
1732
+ }
1733
+ const rate = sampleRate > 0 ? sampleRate : AN_RATE;
1734
+ if (typeof opts.lead === 'number') tl.lead = Math.max(0, Math.min(0.5, opts.lead));
1735
+ if (typeof opts.release === 'number') tl.release = Math.max(0, Math.min(0.5, opts.release));
1736
+ const nowP = performance.now();
1737
+
1738
+ // where this chunk starts on the page clock
1739
+ let start;
1740
+ if (typeof opts.at === 'number' && isFinite(opts.at)) start = nowP + (opts.at - Date.now());
1741
+ else start = tl.end > nowP ? tl.end : nowP + Math.max(0, num(opts.delay, 0.05)) * 1000;
1742
+ // a chunk that follows the previous one (within 40 ms) continues its
1743
+ // segment: the analysis window and the resampler carry across the seam
1744
+ if (run === tl.run && rate === tl.inRate && tl.end > 0 && Math.abs(start - tl.end) < 40) start = tl.end;
1745
+ else {
1746
+ if (start < tl.end) dropQueued(undefined, start); // an earlier play time replaces what was queued after it
1747
+ tl.ring.fill(0); tl.ringPos = 0; tl.sinceHop = 0; tl.mag.fill(0);
1748
+ tl.phase = 0; tl.last = 0; tl.inRate = rate;
1749
+ tl.segT0 = start; tl.segN = 0;
1750
+ if (run !== tl.run) { tl.run = run; tl.ended = false; }
1751
+ }
1752
+
1753
+ // resample to 48 kHz (linear), sliding the analysis window; one lip frame per hop
1754
+ const step = rate / AN_RATE;
1755
+ const ring = tl.ring, n = f32.length;
1756
+ let pos = tl.phase; // in input samples; −1…0 reaches back to the previous chunk
1757
+ while (pos < n - 1) {
1758
+ let s;
1759
+ if (pos < 0) s = tl.last * -pos + f32[0] * (1 + pos);
1760
+ else { const i = pos | 0, fr = pos - i; s = f32[i] * (1 - fr) + f32[i + 1] * fr; }
1761
+ ring[tl.ringPos] = s; tl.ringPos = (tl.ringPos + 1) & (FFT_N - 1);
1762
+ tl.segN++;
1763
+ if (++tl.sinceHop === AN_HOP) { tl.sinceHop = 0; emitLipFrame(tl.segT0 + tl.segN * 1000 / AN_RATE, run); }
1764
+ pos += step;
1765
+ }
1766
+ tl.phase = pos - n; tl.last = f32[n - 1];
1767
+
1768
+ const dur = n / rate * 1000;
1769
+ if (opts.audible) playChunk(f32, rate, start, run);
1770
+ tl.end = start + dur;
1771
+ if (opts.end) tl.ended = true;
1772
+ tl.active = true; tl.dry = 0;
1773
+ return queuedSeconds();
1774
+ }
1775
+
1776
+ /* Stop streamed speech now — a person cut in. With no argument: everything
1777
+ queued is dropped. With a run id: that run only. Either way the run is
1778
+ remembered as cut, so chunks of it still on the wire are dropped when
1779
+ they land. */
1780
+ function cutAudio(run) {
1781
+ const id = run !== undefined ? run : tl.run;
1782
+ if (id !== undefined && tl.cut.indexOf(id) < 0) { tl.cut.push(id); if (tl.cut.length > 256) tl.cut.shift(); }
1783
+ dropQueued(run);
1784
+ if (run === undefined || run === tl.run) {
1785
+ // the queue now ends where what is left of other runs ends
1786
+ const lastLeft = tl.frames.length ? tl.frames[tl.frames.length - 1] : null;
1787
+ tl.end = lastLeft ? lastLeft.t : -1;
1788
+ tl.ended = false; tl.run = lastLeft ? lastLeft.run : undefined; tl.inRate = 0;
1789
+ }
1790
+ if (tl.spoke && (run === undefined || run === tl.spokeRun)) {
1791
+ tl.spoke = false; tl.prev = null;
1792
+ tl.snapUntil = performance.now() + 400; // sound stopped dead: so does the mouth
1793
+ silenceLips();
1794
+ emit('speechend', { run: tl.spokeRun, reason: 'cut' });
1795
+ }
1796
+ if (tl.head >= tl.frames.length && !tl.spoke) { tl.active = false; tl.prev = null; if (!isPlayingFlag && !ext) silenceLips(); }
1797
+ }
1798
+
1799
+ /* the lips for this moment, from the timeline. Returns true while it owns them. */
1800
+ function updateSpeech(nowP) {
1801
+ if (!tl.active) return false;
1802
+ const t = nowP + tl.lead * 1000;
1803
+ const frames = tl.frames;
1804
+ while (tl.head < frames.length && frames[tl.head].t <= t) tl.prev = frames[tl.head++];
1805
+ if (tl.head > 512) { frames.splice(0, tl.head); tl.head = 0; }
1806
+ const prev = tl.prev, next = frames[tl.head];
1807
+ const fresh = prev && t - prev.t < 2.5 * HOP_MS;
1808
+ let f = LIP_SILENT;
1809
+ if (fresh) {
1810
+ f = prev.v;
1811
+ if (next && next.t - prev.t < 2.5 * HOP_MS) { // between two frames: blend, so any frame rate reads smoothly
1812
+ const a = (t - prev.t) / (next.t - prev.t);
1813
+ for (let i = 0; i < 9; i++) _mix[i] = prev.v[i] + (next.v[i] - prev.v[i]) * a;
1814
+ f = _mix;
1389
1815
  }
1390
1816
  }
1817
+ // Closing into silence. The channels are smoothed, so a mouth told to
1818
+ // close when the sound stops is still open ~200 ms later. The timeline
1819
+ // knows the silence is coming: over the last `release` seconds before
1820
+ // it, the open shapes taper off, and the mouth is shut as the sound ends.
1821
+ if (fresh && f[0] < 0.5 && tl.release > 0) {
1822
+ const R = tl.release * 1000;
1823
+ let toSilence = Infinity, lastT = prev.t;
1824
+ for (let i = tl.head; i < frames.length; i++) {
1825
+ const fr = frames[i];
1826
+ if (fr.t - t > R || fr.t - lastT > 2.5 * HOP_MS) { if (fr.t - lastT > 2.5 * HOP_MS) toSilence = lastT + HOP_MS - t; lastT = -1; break; }
1827
+ if (fr.v[0] >= 0.5) { toSilence = fr.t - t; lastT = -1; break; }
1828
+ lastT = fr.t;
1829
+ }
1830
+ // the queue ends inside the window: silence follows only if the run was flagged as ended
1831
+ if (lastT >= 0 && tl.ended && prev.run === tl.run) toSilence = lastT + HOP_MS - t;
1832
+ if (toSilence < R) {
1833
+ const k = Math.max(0, toSilence / R);
1834
+ if (f !== _mix) { _mix.set(f); f = _mix; }
1835
+ for (let i = 1; i < 9; i++) _mix[i] *= k;
1836
+ }
1837
+ }
1838
+ applyLipFrame(f);
1839
+
1840
+ if (fresh) {
1841
+ tl.dry = 0;
1842
+ if (tl.spoke && prev.run !== tl.spokeRun) { tl.spoke = false; emit('speechend', { run: tl.spokeRun, reason: 'end' }); }
1843
+ if (!tl.spoke && f[0] < 0.5) { tl.spoke = true; tl.spokeRun = prev.run; emit('speechstart', { run: prev.run }); }
1844
+ return true;
1845
+ }
1846
+ if (next) return true; // a gap before audio scheduled later: silent, still ours
1847
+ // nothing left to say
1848
+ if (tl.spoke) {
1849
+ const flagged = tl.ended && tl.spokeRun === tl.run;
1850
+ if (!flagged && !tl.dry) { tl.dry = nowP; emit('underrun', { run: tl.spokeRun }); }
1851
+ if (flagged || nowP - tl.dry > 250) {
1852
+ tl.spoke = false;
1853
+ emit('speechend', { run: tl.spokeRun, reason: flagged ? 'end' : 'dry' });
1854
+ } else return true; // dry, but the run may still be coming
1855
+ }
1856
+ tl.active = false; tl.prev = null;
1857
+ return false;
1858
+ }
1859
+
1860
+ function detachAudio() {
1861
+ cutAudio();
1862
+ if (!ext) return;
1863
+ if (ext.node) { try { ext.node.disconnect(ext.an); } catch (_) {} }
1864
+ if (ext.keep) { try { ext.keep.stop(); ext.keep.disconnect(); } catch (_) {} }
1865
+ try { ext.an.disconnect(); } catch (_) {}
1866
+ try { ext.sink.disconnect(); } catch (_) {}
1867
+ ext = null;
1868
+ if (!isPlayingFlag) silenceLips();
1869
+ }
1870
+
1871
+ function getPlaybackTime() {
1872
+ if (!audioCtx || !audioBuffer) return 0;
1873
+ if (isPlayingFlag) return audioCtx.currentTime - audioStartCtxTime;
1874
+ return pausedAt || 0;
1391
1875
  }
1392
1876
 
1393
1877
  /* ── color application ──
@@ -1449,6 +1933,12 @@
1449
1933
  config.irisColor = hex;
1450
1934
  if (irisMat) irisMat.emissiveColor = BABYLON.Color3.FromHexString(hex);
1451
1935
  }
1936
+ function applyBackgroundColor(hex) {
1937
+ if (!/^#[0-9a-f]{6}$/i.test(hex || '')) return;
1938
+ config.backgroundColor = hex;
1939
+ const c = hex2rgb(hex);
1940
+ scene.clearColor = new BABYLON.Color4(c[0], c[1], c[2], 1);
1941
+ }
1452
1942
 
1453
1943
  /* ── views ── */
1454
1944
  const VIEWS = {
@@ -1463,13 +1953,178 @@
1463
1953
  orbiting = false;
1464
1954
  const v = VIEWS[view];
1465
1955
  if (!v) return;
1956
+ // a fixed view ends any behaviour framing (its dim and mood stay), and
1957
+ // is what a later transient behaviour returns to
1958
+ behGliding = false;
1959
+ behName = null;
1960
+ behBase = null;
1961
+ clearTimeout(behTimer);
1962
+ behTimer = null;
1963
+ behPendingBack = null;
1964
+ camera.target.y = 0;
1466
1965
  camera.alpha = v.alpha;
1467
1966
  camera.beta = v.beta;
1468
1967
  camera.radius = v.radius;
1469
1968
  }
1470
1969
 
1970
+ /* ── behaviours: named framing recipes ──
1971
+ Each instance owns a copy of the recipe table, so one page can give
1972
+ every face its own. The camera stays private: a behaviour is the only
1973
+ way framing is asked for, and the glide is the library's. */
1974
+ const behaviours = {};
1975
+ for (const k of Object.keys(BEHAVIOURS)) behaviours[k] = Object.assign({}, BEHAVIOURS[k]);
1976
+ let behGlide = 0.5; // default seconds to settle (overridable per recipe / call)
1977
+ let behGlideNow = 0.5;
1978
+ let behName = null;
1979
+ let behGliding = false;
1980
+ let behBase = null; // the lasting behaviour a transient one returns to
1981
+ let behTimer = null;
1982
+ let behPendingBack = null; // where the pending transient returns to
1983
+ let behHopAmp = 0, behHopT = 0;
1984
+ let personaMood = activeMood;
1985
+ const POSE_KEYS = ['yaw', 'pitch', 'zoom', 'dim', 'ty'];
1986
+ const pose = { yaw: 0, pitch: 0, zoom: 1, dim: 1, ty: 0 };
1987
+ const poseTarget = { yaw: 0, pitch: 0, zoom: 1, dim: 1, ty: 0 };
1988
+ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
1989
+ const num = (v, d) => (typeof v === 'number' && isFinite(v)) ? v : d;
1990
+
1991
+ function applyMood(name) {
1992
+ if (!MOODS[name]) return;
1993
+ activeMood = name;
1994
+ for (const m of MOOD_NAMES) moodTargetWeights[m] = (m === name) ? 1 : 0;
1995
+ }
1996
+
1997
+ /* brightness: a black foreground layer whose alpha is 1 − dim. In-engine,
1998
+ so the host's canvas styles are left alone. */
1999
+ let dimLayer = null;
2000
+ function applyDim(v) {
2001
+ const a = 1 - clamp(v, 0, 1);
2002
+ if (a < 0.004) { if (dimLayer) dimLayer.isEnabled = false; return; }
2003
+ if (!dimLayer) {
2004
+ dimLayer = new BABYLON.Layer('wfDim', null, scene, false);
2005
+ dimLayer.texture = BABYLON.RawTexture.CreateRGBATexture(
2006
+ new Uint8Array([255, 255, 255, 255]), 1, 1, scene, false, false,
2007
+ BABYLON.Texture.NEAREST_SAMPLINGMODE);
2008
+ dimLayer.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
2009
+ }
2010
+ dimLayer.isEnabled = true;
2011
+ dimLayer.color = new BABYLON.Color4(0, 0, 0, a);
2012
+ }
2013
+
2014
+ /* start every glide from where the camera really is — the user may have
2015
+ dragged it, or setView() may have moved it. */
2016
+ function readCameraPose() {
2017
+ const a = -(camera.alpha + Math.PI / 2);
2018
+ pose.yaw = Math.atan2(Math.sin(a), Math.cos(a));
2019
+ pose.pitch = Math.PI / 2 - camera.beta;
2020
+ pose.zoom = BEHAVIOUR_RADIUS / Math.max(0.01, camera.radius);
2021
+ pose.ty = camera.target.y;
2022
+ }
2023
+
2024
+ function setBehaviour(name, opts, _quiet) {
2025
+ opts = opts || {};
2026
+ // a transient interrupted by another one still returns to the original place
2027
+ const pending = behTimer ? behPendingBack : null;
2028
+ clearTimeout(behTimer);
2029
+ behTimer = null;
2030
+ behPendingBack = null;
2031
+ if (name == null) {
2032
+ // release: brightness and focus return, the camera stays where it is
2033
+ readCameraPose();
2034
+ poseTarget.yaw = pose.yaw; poseTarget.pitch = pose.pitch; poseTarget.zoom = pose.zoom;
2035
+ poseTarget.dim = 1; poseTarget.ty = 0;
2036
+ behGlideNow = num(opts.glide, behGlide);
2037
+ behName = null; behBase = null; behGliding = true;
2038
+ if (!_quiet) emit('behaviour', { name: null });
2039
+ return true;
2040
+ }
2041
+ const r = (typeof name === 'object') ? name : behaviours[name];
2042
+ if (!r) return false;
2043
+ const label = (typeof name === 'string') ? name : '(custom)';
2044
+ const lasts = num(opts.for, num(r.for, 0));
2045
+ // what a transient behaviour comes back to: the lasting one before it,
2046
+ // or — when there was none — the framing and mood it interrupted
2047
+ let back = behBase || pending;
2048
+ readCameraPose();
2049
+ if (!back) back = { recipe: { yaw: pose.yaw, pitch: pose.pitch, zoom: pose.zoom, dim: pose.dim, _ty: pose.ty, mood: activeMood }, opts: {} };
2050
+ if (!(lasts > 0)) behBase = { recipe: name, opts: { side: opts.side, glide: opts.glide } };
2051
+
2052
+ orbiting = false;
2053
+ const side = opts.side < 0 ? -1 : 1;
2054
+ poseTarget.yaw = num(r.yaw, 0) * side;
2055
+ poseTarget.pitch = num(r.pitch, 0);
2056
+ poseTarget.zoom = clamp(num(r.zoom, 1), 0.3, 6);
2057
+ poseTarget.dim = clamp(num(r.dim, 1), 0, 1);
2058
+ poseTarget.ty = num(r._ty, num(FOCUS_Y[r.focus], 0));
2059
+ behGlideNow = num(opts.glide, num(r.glide, behGlide));
2060
+ // the wheel-zoom limits must not clip a close-up or a distant shot
2061
+ const radius = BEHAVIOUR_RADIUS / poseTarget.zoom;
2062
+ camera.lowerRadiusLimit = Math.min(camera.lowerRadiusLimit, radius);
2063
+ camera.upperRadiusLimit = Math.max(camera.upperRadiusLimit, radius);
2064
+ // a hop already in the air is left to land
2065
+ if (num(r.hop, 0)) { behHopAmp = r.hop; behHopT = 0; }
2066
+ if (r.mood) applyMood(r.mood === 'persona' ? personaMood : r.mood);
2067
+ behName = label;
2068
+ behGliding = true;
2069
+ if (lasts > 0) {
2070
+ behPendingBack = back;
2071
+ behTimer = setTimeout(() => {
2072
+ behTimer = null;
2073
+ behPendingBack = null;
2074
+ if (_disposed) return;
2075
+ const keep = behBase;
2076
+ setBehaviour(back.recipe, back.opts, true);
2077
+ behBase = keep;
2078
+ if (!keep) behName = null;
2079
+ emit('behaviour', { name: behName, returned: true });
2080
+ }, lasts * 1000);
2081
+ }
2082
+ if (!_quiet) emit('behaviour', { name: behName });
2083
+ return true;
2084
+ }
2085
+
2086
+ function defineBehaviours(input) {
2087
+ if (!input || typeof input !== 'object') return;
2088
+ const recipes = (input.recipes && typeof input.recipes === 'object') ? input.recipes : input;
2089
+ if (input.recipes && typeof input.glide_s === 'number') behGlide = Math.max(0, input.glide_s);
2090
+ for (const k of Object.keys(recipes)) {
2091
+ const r = recipes[k];
2092
+ if (r && typeof r === 'object') behaviours[k] = Object.assign({}, r);
2093
+ }
2094
+ }
2095
+
2096
+ function updateBehaviour(dt) {
2097
+ if (behHopAmp) {
2098
+ behHopT += dt;
2099
+ if (behHopT > 1.2) { behHopAmp = 0; faceRoot.position.y = 0; }
2100
+ else faceRoot.position.y = behHopAmp * Math.abs(Math.sin(Math.PI * behHopT / 0.3)) * Math.exp(-3.5 * behHopT);
2101
+ }
2102
+ if (!behGliding) return;
2103
+ // exponential approach: ~95% of the way after behGlideNow seconds
2104
+ const k = 1 - Math.exp(-dt / Math.max(0.02, behGlideNow / 3));
2105
+ let rest = 0;
2106
+ for (const key of POSE_KEYS) {
2107
+ const d = poseTarget[key] - pose[key];
2108
+ pose[key] += d * k;
2109
+ rest = Math.max(rest, Math.abs(d));
2110
+ }
2111
+ if (rest < 0.0015) {
2112
+ // settled: stop writing the camera, so pointer drag works again
2113
+ for (const key of POSE_KEYS) pose[key] = poseTarget[key];
2114
+ behGliding = false;
2115
+ }
2116
+ camera.alpha = -Math.PI / 2 - pose.yaw;
2117
+ camera.beta = Math.PI / 2 - pose.pitch;
2118
+ camera.radius = BEHAVIOUR_RADIUS / pose.zoom;
2119
+ camera.target.y = pose.ty;
2120
+ applyDim(pose.dim);
2121
+ }
2122
+
1471
2123
  function applyGlow() {
1472
2124
  glowLayer.intensity = config.glow ? 0.85 : 0;
2125
+ // an effect layer at intensity 0 still renders its passes every frame;
2126
+ // switch it off entirely when the face has no glow
2127
+ glowLayer.isEnabled = !!config.glow;
1473
2128
  }
1474
2129
 
1475
2130
  /* ── initial build ── */
@@ -1485,6 +2140,7 @@
1485
2140
  if (config.noseColor) applyNoseColor(config.noseColor);
1486
2141
  applyPupilColor(config.pupilColor);
1487
2142
  applyIrisColor(config.irisColor);
2143
+ applyBackgroundColor(config.backgroundColor);
1488
2144
  applyMinimalSubVisibility();
1489
2145
  applyGlow();
1490
2146
  setView(config.cameraView);
@@ -1495,13 +2151,19 @@
1495
2151
  engine.runRenderLoop(() => {
1496
2152
  if (_disposed) return;
1497
2153
  const now = performance.now();
1498
- const dt = Math.min(0.05, (now - lastT) / 1000);
2154
+ // Real elapsed time, so glides, hops and lip smoothing keep their pace
2155
+ // on a slow device (every update here is an exponential approach or a
2156
+ // function of time — stable for any step). The cap only swallows the
2157
+ // jump after a hidden tab or a stall. Until v1.2.0 it was 0.05, which
2158
+ // ran everything in slow motion below 20 fps.
2159
+ const dt = Math.min(0.25, (now - lastT) / 1000);
1499
2160
  lastT = now;
1500
2161
  idleAnimate(dt);
1501
- if (isPlayingFlag) analyzeAudioFrame();
2162
+ if (!updateSpeech(now) && (isPlayingFlag || ext)) analyzeAudioFrame();
1502
2163
  updateMoodBlend(dt);
1503
2164
  smoothChannels(dt);
1504
2165
  updateFace();
2166
+ updateBehaviour(dt);
1505
2167
  if (orbiting) camera.alpha += dt * 0.3;
1506
2168
  scene.render();
1507
2169
  });
@@ -1531,7 +2193,13 @@
1531
2193
  rc.noseLineThickness !== undefined ||
1532
2194
  rc.browLineThickness !== undefined;
1533
2195
 
2196
+ const prevBackground = config.backgroundColor;
1534
2197
  Object.assign(config, rc);
2198
+ // an unusable colour must not replace the stored one
2199
+ if (rc.backgroundColor !== undefined) {
2200
+ config.backgroundColor = prevBackground;
2201
+ applyBackgroundColor(rc.backgroundColor);
2202
+ }
1535
2203
  if (p.lineColor) applyLineColor(p.lineColor);
1536
2204
  if (p.pupilColor) applyPupilColor(p.pupilColor);
1537
2205
  if (rc.baseColor) applyBaseColor(rc.baseColor);
@@ -1569,8 +2237,9 @@
1569
2237
  for (const ch of CHANNEL_NAMES) if (p.channelGains[ch] !== undefined) channelGains[ch] = p.channelGains[ch];
1570
2238
  }
1571
2239
  if (p.activeMood && MOODS[p.activeMood]) {
1572
- activeMood = p.activeMood;
1573
- for (const m of MOOD_NAMES) moodTargetWeights[m] = (m === activeMood) ? 1 : 0;
2240
+ // the preset's mood is the face's own ('persona' in a behaviour recipe)
2241
+ personaMood = p.activeMood;
2242
+ applyMood(p.activeMood);
1574
2243
  }
1575
2244
  }
1576
2245
 
@@ -1589,24 +2258,55 @@
1589
2258
  stop() {
1590
2259
  pausedAt = 0;
1591
2260
  stopPlayback();
1592
- for (const v of Object.keys(VISEME_PARAMS)) stateTarget['viseme_' + v] = 0;
1593
- stateTarget.viseme_sil = 1;
1594
- stateTarget.jawOpen = 0;
2261
+ if (!ext && !tl.active) silenceLips();
1595
2262
  },
1596
2263
  setLoop(b) { config.loopAudio = !!b; if (audioSource) audioSource.loop = !!b; },
2264
+ /* muted playback still drives the lips: use it when the same speech is
2265
+ sounded somewhere else (another element, another process). */
2266
+ setMuted(b) { muted = !!b; if (outGain) outGain.gain.value = muted ? 0 : 1; },
2267
+ isMuted() { return muted; },
2268
+ attachAudio,
2269
+ pushAudio,
2270
+ cutAudio,
2271
+ detachAudio,
2272
+ isSpeaking() { return tl.spoke; },
2273
+ on,
1597
2274
  setMood(name) {
1598
2275
  if (!MOODS[name]) return;
1599
- activeMood = name;
1600
- for (const m of MOOD_NAMES) moodTargetWeights[m] = (m === name) ? 1 : 0;
2276
+ personaMood = name;
2277
+ applyMood(name);
2278
+ },
2279
+ setBehaviour,
2280
+ defineBehaviours,
2281
+ getBehaviour() { return behName; },
2282
+ getBehaviourNames() { return Object.keys(behaviours); },
2283
+ getBehaviours() {
2284
+ const out = {};
2285
+ for (const k of Object.keys(behaviours)) out[k] = Object.assign({}, behaviours[k]);
2286
+ return out;
1601
2287
  },
1602
- setChannel(name, value) {
2288
+ /* opts.hold keep the value until releaseChannel(name) (default: ~1.2s)
2289
+ opts.smooth ease to the value with the channel's own smoothing instead
2290
+ of jumping — for values pushed at a low rate */
2291
+ setChannel(name, value, opts) {
1603
2292
  if (!CHANNELS[name]) return;
1604
2293
  const r = CHANNELS[name].range;
1605
2294
  const v = Math.max(r[0], Math.min(r[1], value));
1606
- stateTarget[name] = v; state[name] = v;
2295
+ const smooth = !!(opts && opts.smooth);
2296
+ manualValue[name] = v;
2297
+ manualSmooth[name] = smooth;
2298
+ stateTarget[name] = v;
2299
+ if (!smooth) state[name] = v;
1607
2300
  manualLock[name] = true;
1608
2301
  clearTimeout(manualLock['_t_' + name]);
1609
- manualLock['_t_' + name] = setTimeout(() => { manualLock[name] = false; }, 1200);
2302
+ manualLock['_t_' + name] = (opts && opts.hold)
2303
+ ? null
2304
+ : setTimeout(() => { manualLock[name] = false; }, 1200);
2305
+ },
2306
+ releaseChannel(name) {
2307
+ if (!CHANNELS[name]) return;
2308
+ clearTimeout(manualLock['_t_' + name]);
2309
+ manualLock[name] = false;
1610
2310
  },
1611
2311
  setView,
1612
2312
  loadPreset,
@@ -1615,6 +2315,19 @@
1615
2315
  color pickers) where you change one field per call. */
1616
2316
  setRenderConfig(partial) { loadPreset({ renderConfig: partial }); },
1617
2317
  getRenderConfig() { return Object.assign({}, config); },
2318
+ /* the face's whole design as a preset — the JSON loadPreset() takes.
2319
+ Store it, and load it back to get the same face. */
2320
+ getPreset() {
2321
+ const gains = {};
2322
+ for (const ch of CHANNEL_NAMES) if (channelGains[ch] !== 1) gains[ch] = channelGains[ch];
2323
+ return {
2324
+ version: 'wireface-v010',
2325
+ createdAt: new Date().toISOString(),
2326
+ renderConfig: Object.assign({}, config),
2327
+ channelGains: gains,
2328
+ activeMood: personaMood,
2329
+ };
2330
+ },
1618
2331
  /* live channel introspection — useful for editor channel meters that
1619
2332
  display the smoothed audio-driven values and gain knobs. */
1620
2333
  getChannel(name) { return state[name] !== undefined ? state[name] : 0; },
@@ -1629,6 +2342,9 @@
1629
2342
  getActiveMood() { return activeMood; },
1630
2343
  dispose() {
1631
2344
  _disposed = true;
2345
+ clearTimeout(behTimer);
2346
+ for (const n of CHANNEL_NAMES) clearTimeout(manualLock['_t_' + n]);
2347
+ try { detachAudio(); } catch (_) {}
1632
2348
  try { stopPlayback(); } catch (_) {}
1633
2349
  if (audioCtx) { try { audioCtx.close(); } catch (_) {} audioCtx = null; }
1634
2350
  window.removeEventListener('resize', onResize);