Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Duet page: two 3D heads replay a pre-rendered song

Jameson Hodge968cda2b809a
diff --git a/.gitignore b/.gitignore
index 7f61610..d7d4616 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,6 @@ out
.DS_Store
target/
src/wasm/chimera.wasm
+
+# duet shows (?show=<id>) are made locally and are never published: often covers of songs we have no rights to
+public/shows/
diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rs
index c81342d..cbf1b9b 100644
--- a/crates/chimera-cli/src/main.rs
+++ b/crates/chimera-cli/src/main.rs
@@ -10,7 +10,7 @@ mod js;
mod render;
mod wav;
-use chimera::anatomy::human::{BODY_CHILD, BODY_FEMALE, BODY_MALE, HumanBody};
+use chimera::anatomy::human::{BODY_CHILD, BODY_FEMALE, BODY_MALE, BodyMix, HumanBody};
use std::process::ExitCode;
const USAGE: &str = "\
@@ -19,7 +19,7 @@ usage: chimera <command> [args] [--float]
render speech <out> [\"ipa / ipa\"] [male|female|child]
render text <out> [\"English text.\"] [male|female|child]
render song [outdir] [male|female|child]
- render notes <in.json> <out> [male|female|child] [--artic tracks.json]
+ render notes <in.json> <out> [male|female|child] [--artic tracks.json] [--tele voice.tele]
(melody file; midi <= 0 is a rest; --artic also writes the articulators at 100 Hz)
render beatbox [outdir] [preset name | pattern] [male|female|child] [bpm] [bars]
render creature [creatureId] [outdir]
@@ -63,6 +63,16 @@ pub fn body(name: &str) -> Result<HumanBody, String> {
}
}
+/// The app's body mix for a body preset (female 0..1, child 0..1), as `src/ui/body.ts` PRESETS.
+pub fn body_mix(name: &str) -> Result<BodyMix, String> {
+ match name {
+ "male" => Ok(BodyMix::new(0.0, 0.0)),
+ "female" => Ok(BodyMix::new(1.0, 0.0)),
+ "child" => Ok(BodyMix::new(0.0, 1.0)),
+ _ => Err(format!("unknown body {name:?}; have male, female, child")),
+ }
+}
+
/// `<out>.wav` for an output stem (a trailing `.wav` is accepted too).
pub fn wav_name(stem: &str) -> String {
format!("{}.wav", stem.strip_suffix(".wav").unwrap_or(stem))
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rs
index 67c2feb..e02badb 100644
--- a/crates/chimera-cli/src/render.rs
+++ b/crates/chimera-cli/src/render.rs
@@ -1,9 +1,9 @@
//! `chimera render …`: ports of `tools/render-{speech,text,song,beatbox,creature,vowels}.ts`.
use crate::js::{fixed, num, pad_end, pad_start};
-use crate::{Ctx, FS, arg, body, peak, repo_path, wav_name};
+use crate::{Ctx, FS, arg, body, body_mix, peak, repo_path, wav_name};
use chimera::analysis::lpc::{FormantOpts, estimate_formants};
-use chimera::anatomy::human::ArticKey;
+use chimera::anatomy::human::{ArticKey, BodyMix, N_ARTIC};
use chimera::analysis::pitch::{YinOpts, yin_pitch};
use chimera::control::beat_player::BeatPlayer;
use chimera::control::score::Gesture;
@@ -24,7 +24,7 @@ use chimera::phonetics::sing::{
use chimera::phonetics::songs::DEMO_SONGS;
use chimera::phonetics::syllables::lyrics_to_syllables;
use chimera::phonetics::{Intonation, Syllable};
-use chimera::voice::human_voice::{HumanVoice, SourcePatch};
+use chimera::voice::human_voice::{HumanVoice, SCOPE_POINTS, SourcePatch, VoiceTelemetry};
use std::io::Read;
use std::time::Instant;
@@ -342,37 +342,145 @@ pub fn song(ctx: &Ctx, a: &[String]) -> Result<(), String> {
/// Articulator tracks are sampled at this rate (Hz): 480 samples at 48 kHz.
const ARTIC_RATE: usize = 100;
-/// Render like `render_blocks`, and record the articulators at `ARTIC_RATE`: frame i is the state
-/// at i / ARTIC_RATE s. The voice runs sample by sample, so the sound is the same either way.
-fn render_tracked(v: &mut HumanVoice, out: &mut [f32]) -> Vec<Vec<f64>> {
- let hop = FS as usize / ARTIC_RATE;
+/// Telemetry frames (`--tele`) are taken every `TELE_HOP` samples: the live app's cadence (the
+/// worklet posts one every 6 render quanta of 128), so each frame's RMS levels cover as long.
+pub const TELE_HOP: usize = 768;
+/// Points kept of the 256-point glottal scope in a telemetry frame (every 8th).
+pub const TELE_SCOPE: usize = 32;
+/// `--tele` file version (see `TeleRecorder`).
+pub const TELE_VERSION: u32 = 1;
+
+/// The voice's telemetry over time, for replaying a render in the app (two heads singing a duet).
+///
+/// File layout, little-endian: `b"CHTL"`, then u32 version, sampleRate, hop, frames, frameLen,
+/// nArtic, nPh, nOr, nScope, then f32 bodyFemale, bodyChild (48 bytes in all); then `frames`
+/// frames of `frameLen` f32s. A frame is the wasm telemetry block's fields in its order
+/// (crates/chimera-wasm `engine_telemetry`): phLen, orLen, velumPort, f0, voicing, pLung, outRms,
+/// noiseLevel, noiseNode, gate, clock, then artic, phAreas, orAreas, pressureRms (nPh+nOr),
+/// flow (nPh+nOr), glottalArea (nScope), glottalFlow (nScope); no gesture labels.
+/// Frame i is the state at sample i·hop (frame 0 before any sound); its RMS levels cover the hop
+/// before it. A last partial hop gets no frame.
+struct TeleRecorder {
+ t: VoiceTelemetry,
+ data: Vec<f32>,
+ frames: u32,
+ n_ph: usize,
+ n_or: usize,
+}
+
+impl TeleRecorder {
+ fn new(v: &mut HumanVoice) -> Self {
+ let mut r = TeleRecorder { t: VoiceTelemetry::default(), data: Vec::new(), frames: 0, n_ph: 0, n_or: 0 };
+ v.telemetry(&mut r.t);
+ r.n_ph = r.t.ph_areas.len();
+ r.n_or = r.t.or_areas.len();
+ r.push_current();
+ r
+ }
+
+ fn frame_len(&self) -> usize {
+ 11 + N_ARTIC + 3 * (self.n_ph + self.n_or) + 2 * TELE_SCOPE
+ }
+
+ fn snap(&mut self, v: &mut HumanVoice) -> Result<(), String> {
+ v.telemetry(&mut self.t);
+ if self.t.ph_areas.len() != self.n_ph || self.t.or_areas.len() != self.n_or {
+ return Err("the airway's section count changed during the render".into());
+ }
+ self.push_current();
+ Ok(())
+ }
+
+ fn push_current(&mut self) {
+ let t = &self.t;
+ let d = &mut self.data;
+ d.extend([t.ph_len, t.or_len, t.velum_port, t.f0, t.voicing, t.p_lung, t.out_rms, t.noise_level, t.noise_node as f64, t.gate, t.clock].map(|x| x as f32));
+ for arr in [&t.artic, &t.ph_areas, &t.or_areas, &t.pressure_rms, &t.flow] {
+ d.extend_from_slice(arr);
+ }
+ let step = SCOPE_POINTS / TELE_SCOPE;
+ for arr in [&t.glottal_area, &t.glottal_flow] {
+ d.extend((0..TELE_SCOPE).map(|i| arr[i * step]));
+ }
+ self.frames += 1;
+ debug_assert_eq!(self.data.len(), self.frames as usize * self.frame_len());
+ }
+
+ fn bytes(&self, body: BodyMix) -> Vec<u8> {
+ let mut b = Vec::with_capacity(48 + 4 * self.data.len());
+ b.extend_from_slice(b"CHTL");
+ for x in [TELE_VERSION, FS as u32, TELE_HOP as u32, self.frames, self.frame_len() as u32, N_ARTIC as u32, self.n_ph as u32, self.n_or as u32, TELE_SCOPE as u32] {
+ b.extend_from_slice(&x.to_le_bytes());
+ }
+ for x in [body.female as f32, body.child as f32] {
+ b.extend_from_slice(&x.to_le_bytes());
+ }
+ for x in &self.data {
+ b.extend_from_slice(&x.to_le_bytes());
+ }
+ b
+ }
+}
+
+/// Render like `render_blocks`, recording the articulators every `ARTIC_RATE`th of a second
+/// (`artic`: frame i is the state at i / ARTIC_RATE s, plus one at the end) and/or the telemetry
+/// every `TELE_HOP` samples (`tele`). The two cadences are independent; taking telemetry is the
+/// only thing that resets its RMS levels. The voice runs sample by sample, so the sound is the
+/// same either way.
+fn render_tracked(v: &mut HumanVoice, out: &mut [f32], artic: bool, tele: bool) -> Result<(Vec<Vec<f64>>, Option<TeleRecorder>), String> {
+ let a_hop = FS as usize / ARTIC_RATE;
let frame = |v: &HumanVoice| ArticKey::ALL.iter().map(|k| js_round(v.artic.x.get(*k) * 1e4) / 1e4).collect();
- let mut frames = vec![frame(v)];
- for chunk in out.chunks_mut(hop) {
- render_blocks(v, chunk);
- frames.push(frame(v));
+ let mut frames = if artic { vec![frame(v)] } else { Vec::new() };
+ let mut rec = if tele { Some(TeleRecorder::new(v)) } else { None };
+ let n = out.len();
+ let (mut pos, mut next_a, mut next_t) = (0usize, a_hop, TELE_HOP);
+ while pos < n {
+ let mut end = n;
+ if artic {
+ end = end.min(next_a);
+ }
+ if tele {
+ end = end.min(next_t);
+ }
+ render_blocks(v, &mut out[pos..end]);
+ pos = end;
+ if artic && (pos == next_a || pos == n) {
+ frames.push(frame(v));
+ next_a += a_hop;
+ }
+ if let Some(r) = rec.as_mut()
+ && pos == next_t
+ {
+ r.snap(v)?;
+ next_t += TELE_HOP;
+ }
}
- frames
+ Ok((frames, rec))
}
/// A melody from a JSON file: `{"bpm", "lyrics", "notes": [[midi, beats], ...], "vibrato"?}`.
/// One lyric syllable per sounding note; a note with midi <= 0 is a rest, which splits the
/// melody into phrases planned separately on one voice.
-/// `render notes <in.json> <out> [body] [--artic tracks.json]`: `--artic` also writes the
-/// articulators over time (`{"rate", "body", "keys", "frames"}`), to animate a face in sync.
+/// `render notes <in.json> <out> [body] [--artic tracks.json] [--tele voice.tele]`: `--artic` also
+/// writes the articulators over time (`{"rate", "body", "keys", "frames"}`), to animate a face in
+/// sync; `--tele` writes the voice's whole telemetry over time (see `TeleRecorder`), which the
+/// app's duet page replays on a 3D head.
pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
let mut artic_out: Option<String> = None;
+ let mut tele_out: Option<String> = None;
let mut rest = Vec::new();
let mut it = a.iter();
while let Some(x) = it.next() {
if x == "--artic" {
artic_out = Some(it.next().ok_or("--artic needs a file")?.clone());
+ } else if x == "--tele" {
+ tele_out = Some(it.next().ok_or("--tele needs a file")?.clone());
} else {
rest.push(x.clone());
}
}
let a = &rest[..];
- let input = a.first().ok_or("render notes <in.json> <out> [male|female|child] [--artic tracks.json]")?;
+ let input = a.first().ok_or("render notes <in.json> <out> [male|female|child] [--artic tracks.json] [--tele voice.tele]")?;
let out_name = wav_name(arg(a, 1, "out/notes"));
let body_name = arg(a, 2, "male");
let b = body(body_name)?;
@@ -426,12 +534,11 @@ pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
flush(&mut phrase, start, &mut v, &mut end);
let n = js_round(FS * (end + 0.4)) as usize;
let mut out = vec![0f32; n];
- let frames = match &artic_out {
- Some(_) => render_tracked(&mut v, &mut out),
- None => {
- render_blocks(&mut v, &mut out);
- Vec::new()
- }
+ let (frames, rec) = if artic_out.is_some() || tele_out.is_some() {
+ render_tracked(&mut v, &mut out, artic_out.is_some(), tele_out.is_some())?
+ } else {
+ render_blocks(&mut v, &mut out);
+ (Vec::new(), None)
};
ctx.write_wav(&out_name, &out)?;
println!("{out_name}: {} s, peak {}, {} notes", fixed(n as f64 / FS, 2), fixed(peak(&out), 3), sounding);
@@ -440,6 +547,10 @@ pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {
std::fs::write(path, j.to_string()).map_err(|e| format!("{path}: {e}"))?;
println!("{path}: {} frames at {ARTIC_RATE} Hz", frames.len());
}
+ if let (Some(path), Some(r)) = (&tele_out, rec) {
+ std::fs::write(path, r.bytes(body_mix(body_name)?)).map_err(|e| format!("{path}: {e}"))?;
+ println!("{path}: {} telemetry frames every {TELE_HOP} samples", r.frames);
+ }
Ok(())
}
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
index 1ae73a6..1264486 100644
--- a/crates/chimera-cli/tests/cli.rs
+++ b/crates/chimera-cli/tests/cli.rs
@@ -376,3 +376,55 @@ fn render_notes_artic_tracks_follow_the_sound_without_changing_it() {
let open = (105..125).map(ap).fold(f64::MIN, f64::max);
assert!(closed < 0.1 && open > 0.5, "lipAp closed {closed}, open {open}");
}
+
+#[test]
+fn render_notes_tele_records_the_live_telemetry_without_changing_the_sound() {
+ let melody = tmp("tele-melody.json");
+ std::fs::write(
+ &melody,
+ r#"{"bpm": 120, "t0": 0, "lyrics": "Take my hand", "notes": [[0, 1], [67, 1], [63, 0.5], [60, 1.5]]}"#,
+ )
+ .unwrap();
+ let (plain, tracked, tele, tracks) = (tmp("tele-plain"), tmp("tele-tracked"), tmp("voice.tele"), tmp("tele-artic.json"));
+ chimera(&["render", "notes", &melody, &plain, "female"]);
+ // both recordings at once: each keeps its own cadence
+ let stdout = chimera(&["render", "notes", &melody, &tracked, "female", "--tele", &tele, "--artic", &tracks]);
+ let a = std::fs::read(format!("{plain}.wav")).unwrap();
+ let b = std::fs::read(format!("{tracked}.wav")).unwrap();
+ assert!(a == b, "--tele changed the sound");
+ let samples = (a.len() - 44) / 2;
+ let artic: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tracks).unwrap()).unwrap();
+ assert_eq!(artic["frames"].as_array().unwrap().len(), 1 + samples.div_ceil(480));
+
+ let t = std::fs::read(&tele).unwrap();
+ assert_eq!(&t[..4], b"CHTL");
+ let u = |i: usize| u32::from_le_bytes(t[4 + 4 * i..8 + 4 * i].try_into().unwrap()) as usize;
+ let f = |o: usize| f32::from_le_bytes(t[o..o + 4].try_into().unwrap());
+ let (version, rate, hop, frames, len, n_artic, n_ph, n_or, n_scope) = (u(0), u(1), u(2), u(3), u(4), u(5), u(6), u(7), u(8));
+ assert_eq!((version, rate, hop, n_artic, n_scope), (1, 48000, 768, 17, 32));
+ assert_eq!((f(40), f(44)), (1.0, 0.0), "body mix: female");
+ // the female airway at 48 kHz, two times oversampled
+ assert_eq!((n_ph, n_or), (15, 16));
+ assert_eq!(len, 11 + n_artic + 3 * (n_ph + n_or) + 2 * n_scope);
+ // frame 0 before any sound, then one per whole hop
+ assert_eq!(frames, 1 + samples / hop, "{stdout}");
+ assert_eq!(t.len(), 48 + 4 * frames * len);
+ let at = |i: usize, k: usize| f(48 + 4 * (i * len + k));
+ // the clock (field 10) is the frame's time
+ for i in [0, 1, frames / 2, frames - 1] {
+ assert!((at(i, 10) as f64 - (i * hop) as f64 / 48000.0).abs() < 1e-4, "frame {i} clock {}", at(i, 10));
+ }
+ // silent before the first note (a beat's rest: it starts at 0.5 s), then "Take" voiced on
+ // G4 (392 Hz): frames 38-53 are 0.61-0.85 s
+ let out_rms = |i: usize| at(i, 6);
+ assert!((1..20).all(|i| out_rms(i) < 1e-4), "noise before the first note");
+ let sung = 38..54;
+ assert!(sung.clone().all(|i| out_rms(i) > 1e-2 && at(i, 4) > 0.5), "not voiced while singing");
+ let f0 = sung.map(|i| at(i, 3)).sum::<f32>() / 16.0;
+ assert!((f0 - 392.0).abs() < 12.0, "f0 {f0}");
+ // the articulators agree with --artic's (lipAp at 1.0 s: artic frame 100, tele frame 62.5)
+ let keys: Vec<&str> = artic["keys"].as_array().unwrap().iter().map(|k| k.as_str().unwrap()).collect();
+ let lip = keys.iter().position(|k| *k == "lipAp").unwrap();
+ let a_lip = artic["frames"][96][lip].as_f64().unwrap(); // 0.96 s = 60 tele hops
+ assert!((at(60, 11 + lip) as f64 - a_lip).abs() < 1e-3, "lipAp {} vs {a_lip}", at(60, 11 + lip));
+}
diff --git a/src/show/tele.ts b/src/show/tele.ts
new file mode 100644
index 0000000..64762bb
--- /dev/null
+++ b/src/show/tele.ts
@@ -0,0 +1,89 @@
+/**
+ * A voice's recorded telemetry (`chimera render notes … --tele voice.tele`), replayed as the live
+ * worklet's telemetry messages, so a 3D head moves exactly as the engine did for the sound.
+ *
+ * File layout (little-endian; crates/chimera-cli/src/render.rs `TeleRecorder`): "CHTL", u32
+ * version, sampleRate, hop, frames, frameLen, nArtic, nPh, nOr, nScope, f32 bodyFemale,
+ * bodyChild; then `frames` × `frameLen` f32. A frame: phLen, orLen, velumPort, f0, voicing, pLung,
+ * outRms, noiseLevel, noiseNode, gate, clock, then artic, phAreas, orAreas, pressureRms, flow,
+ * glottalArea, glottalFlow. Frame i is the state at sample i·hop.
+ */
+import type { TelemetryMessage } from "../worklet/protocol.ts";
+import type { BodyMix } from "../wasm/types.ts";
+
+export const TELE_VERSION = 1;
+const HEADER_BYTES = 48;
+const SCALARS = 11;
+
+export class TeleTrack {
+ readonly sampleRate: number;
+ readonly hop: number;
+ readonly frames: number;
+ readonly body: BodyMix;
+ readonly nPh: number;
+ readonly nOr: number;
+ private readonly nArtic: number;
+ private readonly nScope: number;
+ private readonly len: number;
+ private readonly data: Float32Array;
+
+ constructor(buf: ArrayBuffer) {
+ if (buf.byteLength < HEADER_BYTES) throw new Error("telemetry file is too short for its header");
+ const magic = new TextDecoder().decode(new Uint8Array(buf, 0, 4));
+ if (magic !== "CHTL") throw new Error("not a CHIMERA telemetry file");
+ const u = new DataView(buf);
+ const at = (i: number) => u.getUint32(4 + 4 * i, true);
+ const version = at(0);
+ if (version !== TELE_VERSION) throw new Error(`telemetry file version ${version}; this app reads ${TELE_VERSION}`);
+ this.sampleRate = at(1);
+ this.hop = at(2);
+ this.frames = at(3);
+ this.len = at(4);
+ this.nArtic = at(5);
+ this.nPh = at(6);
+ this.nOr = at(7);
+ this.nScope = at(8);
+ this.body = { female: u.getFloat32(40, true), child: u.getFloat32(44, true) };
+ const want = SCALARS + this.nArtic + 3 * (this.nPh + this.nOr) + 2 * this.nScope;
+ if (this.len !== want || this.frames < 1 || this.hop < 1 || this.sampleRate < 1) throw new Error("telemetry file header is inconsistent");
+ if (buf.byteLength !== HEADER_BYTES + 4 * this.frames * this.len)
+ throw new Error(`telemetry file is ${buf.byteLength} bytes; its header says ${HEADER_BYTES + 4 * this.frames * this.len}`);
+ this.data = new Float32Array(buf, HEADER_BYTES, this.frames * this.len);
+ }
+
+ /** frames per second */
+ get rate(): number {
+ return this.sampleRate / this.hop;
+ }
+
+ /** seconds the recording covers */
+ get duration(): number {
+ return ((this.frames - 1) * this.hop) / this.sampleRate;
+ }
+
+ /** the frame at time t (s) on the recording's clock, clamped to the recording */
+ indexAt(t: number): number {
+ const i = Math.floor((t * this.sampleRate) / this.hop + 1e-6);
+ return Math.min(this.frames - 1, Math.max(0, Number.isFinite(i) ? i : 0));
+ }
+
+ /** frame i as the worklet's telemetry message (arrays are views into the recording) */
+ message(i: number, beatStep = -1): TelemetryMessage {
+ const o0 = i * this.len;
+ const d = this.data;
+ let o = o0 + SCALARS;
+ const take = (n: number) => d.subarray(o, (o += n));
+ const nT = this.nPh + this.nOr;
+ const artic = take(this.nArtic), phAreas = take(this.nPh), orAreas = take(this.nOr), pressureRms = take(nT), flow = take(nT), glottalArea = take(this.nScope), glottalFlow = take(this.nScope);
+ const s = (k: number) => d[o0 + k];
+ return {
+ type: "telemetry",
+ t: { phLen: s(0), orLen: s(1), velumPort: s(2), f0: s(3), voicing: s(4), pLung: s(5), outRms: s(6), noiseLevel: s(7), noiseNode: s(8), gate: s(9), clock: s(10), artic, phAreas, orAreas, pressureRms, flow, glottalArea, glottalFlow, active: [] },
+ load: 0,
+ body: this.body,
+ nPh: this.nPh,
+ nOr: this.nOr,
+ beatStep,
+ };
+ }
+}
diff --git a/src/show/transport.ts b/src/show/transport.ts
new file mode 100644
index 0000000..8d16e31
--- /dev/null
+++ b/src/show/transport.ts
@@ -0,0 +1,139 @@
+/**
+ * Plays one decoded track and keeps the one playhead every head reads: what the listener hears
+ * now, in seconds into the track. Its own AudioContext (the voice engine doesn't run here).
+ *
+ * Paused, the playhead is the saved position. Playing, it is that position plus the audible time
+ * since the source started: the context's output timestamp where the browser has one (it already
+ * allows for output latency), else currentTime less the reported latency. A seek bumps `epoch`
+ * (so animation history can be reset) and restarts a fresh source. The context leaving "running"
+ * (an iOS interruption, the page going to the background) pauses the transport where it was.
+ */
+export type TransportState = { playing: boolean; time: number; duration: number; epoch: number };
+
+export class Transport {
+ readonly ctx: AudioContext;
+ private buffer: AudioBuffer | null = null;
+ private src: AudioBufferSourceNode | null = null;
+ private offset = 0;
+ private startedAt = 0;
+ private playing = false;
+ private wasRunning = false;
+ epoch = 0;
+ private readonly listeners = new Set<() => void>();
+
+ constructor() {
+ this.ctx = new AudioContext({ latencyHint: "playback" });
+ this.ctx.onstatechange = () => {
+ const running = this.ctx.state === "running";
+ if (this.wasRunning && !running && this.playing) this.pause();
+ this.wasRunning = running;
+ };
+ }
+
+ async load(data: ArrayBuffer): Promise<void> {
+ this.buffer = await this.ctx.decodeAudioData(data);
+ this.emit();
+ }
+
+ get duration(): number {
+ return this.buffer?.duration ?? 0;
+ }
+
+ get isPlaying(): boolean {
+ return this.playing;
+ }
+
+ get state(): TransportState {
+ return { playing: this.playing, time: this.time(), duration: this.duration, epoch: this.epoch };
+ }
+
+ subscribe(f: () => void): () => void {
+ this.listeners.add(f);
+ return () => this.listeners.delete(f);
+ }
+
+ private emit(): void {
+ for (const f of this.listeners) f();
+ }
+
+ /** Call from the tap itself: iOS only lets a user gesture start audio. */
+ play(): void {
+ if (!this.buffer || this.playing) return;
+ void this.ctx.resume();
+ if (this.offset >= this.duration - 0.05) this.offset = 0;
+ this.startSource();
+ this.playing = true;
+ this.emit();
+ }
+
+ pause(): void {
+ if (!this.playing) return;
+ this.offset = this.time();
+ this.stopSource();
+ this.playing = false;
+ this.emit();
+ }
+
+ seek(t: number): void {
+ this.offset = Math.min(this.duration, Math.max(0, t));
+ this.epoch++;
+ if (this.playing) {
+ this.stopSource();
+ this.startSource();
+ }
+ this.emit();
+ }
+
+ /** the audible playhead (s) */
+ time(): number {
+ if (!this.playing) return this.offset;
+ return Math.min(this.duration, Math.max(0, this.offset + this.audibleNow() - this.startedAt));
+ }
+
+ dispose(): void {
+ this.stopSource();
+ this.listeners.clear();
+ void this.ctx.close();
+ }
+
+ private startSource(): void {
+ const src = this.ctx.createBufferSource();
+ src.buffer = this.buffer;
+ src.connect(this.ctx.destination);
+ src.onended = () => {
+ if (this.src !== src) return;
+ this.src = null;
+ this.offset = this.duration;
+ this.playing = false;
+ this.emit();
+ };
+ this.src = src;
+ this.startedAt = this.ctx.currentTime;
+ src.start(this.startedAt, this.offset);
+ }
+
+ private stopSource(): void {
+ const src = this.src;
+ this.src = null;
+ if (!src) return;
+ src.onended = null;
+ try {
+ src.stop();
+ } catch {
+ // never started (the context was closed)
+ }
+ src.disconnect();
+ }
+
+ /** the context time being heard now */
+ private audibleNow(): number {
+ const c = this.ctx;
+ const ts = typeof c.getOutputTimestamp === "function" ? c.getOutputTimestamp() : null;
+ if (ts && ts.contextTime !== undefined && ts.performanceTime !== undefined && ts.contextTime > 0) {
+ // the stamp is a moment ago; carry it to now, but never ahead of what has been rendered
+ const t = ts.contextTime + Math.max(0, (performance.now() - ts.performanceTime) / 1000);
+ return Math.min(t, c.currentTime);
+ }
+ return c.currentTime - (c.outputLatency || c.baseLatency || 0);
+ }
+}
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 2ed8389..3be617e 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -24,6 +24,14 @@ import { bodyLabel, presetOf, PRESETS } from "./body.ts";
// three.js only loads when the 3D view is first shown
const AnatomyView3D = lazy(() => import("./components/AnatomyView3D.tsx").then((m) => ({ default: m.AnatomyView3D })));
+// the duet page (`?show=<id>`): two 3D heads replaying a pre-rendered song
+const DuetPage = lazy(() => import("./components/DuetPage.tsx").then((m) => ({ default: m.DuetPage })));
+
+/** the show to play, from `?show=<id>` (a plain folder name under public/shows) */
+function showId(): string | null {
+ const id = new URLSearchParams(window.location.search).get("show");
+ return id && /^[\w-]+$/.test(id) ? id : null;
+}
function TopBar() {
const started = useStore((s) => s.started);
@@ -199,6 +207,17 @@ function PlayRight() {
}
export function App() {
+ const show = showId();
+ if (show)
+ return (
+ <Suspense fallback={null}>
+ <DuetPage id={show} />
+ </Suspense>
+ );
+ return <Wall />;
+}
+
+function Wall() {
const mode = useStore((s) => s.mode);
return (
<div className={`app mode-${mode}`}>
diff --git a/src/ui/components/AnatomyView3D.tsx b/src/ui/components/AnatomyView3D.tsx
index ecd501e..31c0e13 100644
--- a/src/ui/components/AnatomyView3D.tsx
+++ b/src/ui/components/AnatomyView3D.tsx
@@ -18,10 +18,32 @@ import { VoiceModel } from "../analysis.ts";
import { useModel } from "../useModel.ts";
import { V } from "../colors.ts";
import { articulatorSlots, tractInfo, type InfoFn, type OverlayFn, type SlotsFn } from "./AnatomyView.tsx";
+import type { ViewFlags } from "../render/anatomy.ts";
+import type { HumanArtic } from "../../wasm/engine.ts";
+import type { TelemetryMessage } from "../../worklet/protocol.ts";
+
+/**
+ * A head driven by something other than the live engine (the duet page's recordings): its own
+ * body's model and view flags, and each frame's telemetry. `tele` null holds the head in `artic`
+ * with the voice at rest; a new `epoch` (a seek) drops the face's and the airflow's history.
+ */
+export interface HeadFeed {
+ model: VoiceModel;
+ view: ViewFlags;
+ frame(): { tele: TelemetryMessage | null; artic: HumanArtic; epoch: number };
+ /** cap on the device pixel ratio (two heads on a phone draw half the pixels at 1.5) */
+ maxDpr?: number;
+ /** which way the head turns to show its face (see Anatomy3D.facing) */
+ facing?: 1 | -1;
+}
const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
-export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showFormants?: boolean; overlay?: OverlayFn }) {
+export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showFormants?: boolean; overlay?: OverlayFn; feed?: HeadFeed; readouts?: boolean }) {
+ const feedRef = useRef<HeadFeed | undefined>(props.feed);
+ feedRef.current = props.feed;
+ const readoutsRef = useRef(props.readouts ?? true);
+ readoutsRef.current = props.readouts ?? true;
const overlayRef = useRef<OverlayFn | undefined>(props.overlay);
overlayRef.current = props.overlay;
const formantsRef = useRef(props.showFormants ?? true);
@@ -51,6 +73,8 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
gl.outputColorSpace = THREE.LinearSRGBColorSpace;
gl.setClearColor(0x000000, 1);
const r = new Anatomy3D();
+ r.centred = !readoutsRef.current;
+ r.facing = feedRef.current?.facing ?? 1;
const glow = new Glow();
const camera = r.camera;
const controls = new OrbitControls(camera, canvas);
@@ -92,7 +116,7 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
/** the head centre the camera was placed for (a new body moves the view with it) */
const posedTarget = new THREE.Vector3();
const home = () => {
- const m = model.current;
+ const m = feedRef.current?.model ?? model.current;
if (m) {
const p = r.poses(m);
moveTo(p.home, p.target, 0.9);
@@ -101,9 +125,13 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
canvas.addEventListener("dblclick", home);
let w = 0, h = 0, dpr = 1;
+ const maxDpr = () => Math.min(feedRef.current?.maxDpr ?? 2, window.devicePixelRatio || 1);
+ /** a fed head (no settings of its own to keep) goes back to its framing when its pane changes shape */
+ let refit = false;
const fit = () => {
const b = wrap.getBoundingClientRect();
- dpr = Math.min(2, window.devicePixelRatio || 1);
+ dpr = maxDpr();
+ refit = !!feedRef.current && (b.width !== w || b.height !== h);
w = b.width;
h = b.height;
canvas.width = Math.max(1, Math.round(w * dpr));
@@ -118,17 +146,31 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
let last = performance.now();
let fTick = 0;
let formants: number[] = [];
+ let epoch = -1;
const loop = (now: number) => {
const dt = Math.min(0.05, (now - last) / 1000);
// the face's expression keeps real time (a held note lasts as long at a low frame rate)
const elapsed = Math.min(0.5, (now - last) / 1000);
last = now;
- if (Math.min(2, window.devicePixelRatio || 1) !== dpr) fit();
+ if (maxDpr() !== dpr) fit();
const st = useStore.getState();
- const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;
- const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;
+ const feed = feedRef.current;
+ let tele: TelemetryMessage | null, a: HumanArtic;
+ if (feed) {
+ const fr = feed.frame();
+ if (fr.epoch !== epoch) {
+ epoch = fr.epoch;
+ r.resetMotion();
+ }
+ tele = fr.tele;
+ a = tele ? VoiceModel.articFromArray(tele.t.artic) : fr.artic;
+ } else {
+ tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;
+ a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;
+ }
+ const view = feed ? feed.view : st.view;
r.face.update(tele, elapsed);
- const m = model.current;
+ const m = feed ? feed.model : model.current;
if (m && w > 0 && h > 0) {
if (posed !== m) {
const p = r.poses(m);
@@ -145,12 +187,17 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
}
posedTarget.copy(p.target);
posed = m;
+ } else if (refit) {
+ const p = r.poses(m);
+ moveTo(p.home, p.target, 0.4);
}
+ refit = false;
stepTween(dt);
controls.update(dt);
const f = m.frame(a);
- if (++fTick % 4 === 0 || formants.length === 0) formants = m.transfer(a).formants;
- r.update(m, f, a, tele, st.view, dt);
+ const readouts = readoutsRef.current;
+ if (readouts && (++fTick % 4 === 0 || formants.length === 0)) formants = m.transfer(a).formants;
+ r.update(m, f, a, tele, view, dt);
gl.render(r.scene, camera);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalCompositeOperation = "source-over";
@@ -162,9 +209,11 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showForma
const [cx, cy] = r.project(r.caliper.x, r.caliper.y, r.caliper.z);
label(ctx, r.caliper.area <= 0.0005 ? "CLOSED" : `${r.caliper.area.toFixed(2)} CM²`, cx + 10, cy - 6, { size: 11, color: V.white, ls: 0.12 });
}
- const info = infoRef.current(m, f, tele).map((s) => s.toUpperCase());
- const slots = slotsRef.current(m, a, f, formants, tele);
- drawReadouts(ctx, { w, h, compact: r.compact, slotX: w - Math.min(340, w * 0.42), slotY: h - Math.min(236, h * 0.3) }, formantsRef.current ? formants : [], info, slots);
+ if (readouts) {
+ const info = infoRef.current(m, f, tele).map((s) => s.toUpperCase());
+ const slots = slotsRef.current(m, a, f, formants, tele);
+ drawReadouts(ctx, { w, h, compact: r.compact, slotX: w - Math.min(340, w * 0.42), slotY: h - Math.min(236, h * 0.3) }, formantsRef.current ? formants : [], info, slots);
+ }
overlayRef.current?.(ctx, r.faceView(m, f, a), m, f, a, { w, h, dt });
glow.apply(canvas, ctx, dpr);
}
diff --git a/src/ui/components/DuetPage.tsx b/src/ui/components/DuetPage.tsx
new file mode 100644
index 0000000..289f303
--- /dev/null
+++ b/src/ui/components/DuetPage.tsx
@@ -0,0 +1,162 @@
+/**
+ * The duet page (`?show=<id>`): a pre-rendered song with two (or more) voices, each on its own 3D
+ * head, side by side, moving exactly as the engine did when it sang. Nothing is synthesized here:
+ * the page plays the mixed track and replays each voice's recorded telemetry at the playhead.
+ *
+ * A show is a folder `public/shows/<id>/` (gitignored: shows are made locally, often of songs that
+ * mustn't be published) holding `show.json`, the mix and one `.tele` per voice from
+ * `chimera render notes … --tele`. The voices' renders and the mix must share sample 0.
+ *
+ * { "title": "…", "audio": "mix.mp3", "bpm": 103, "downbeat": 0,
+ * "voices": [{ "name": "Lower", "tele": "male.tele" }, { "name": "Upper", "tele": "female.tele" }] }
+ *
+ * `bpm` and `downbeat` (s, a bar's first beat) are optional: with them the heads nod on the beat.
+ */
+import { useEffect, useRef, useState } from "react";
+import { AnatomyView3D, type HeadFeed } from "./AnatomyView3D.tsx";
+import { Screen } from "./Screen.tsx";
+import { TeleTrack } from "../../show/tele.ts";
+import { Transport } from "../../show/transport.ts";
+import { getModel } from "../useModel.ts";
+import { VoiceModel } from "../analysis.ts";
+import { bodyLabel } from "../body.ts";
+import type { ViewFlags } from "../render/anatomy.ts";
+
+interface ShowFile {
+ title: string;
+ audio: string;
+ bpm?: number;
+ downbeat?: number;
+ voices: { name: string; tele: string }[];
+}
+
+interface Loaded {
+ show: ShowFile;
+ voices: { name: string; track: TeleTrack }[];
+}
+
+/** the heads as the face screen shows them by default, less the measurement labels */
+const VIEW: ViewFlags = { pressure: true, particles: true, grid: false, calipers: false };
+
+async function fetchOk(url: string): Promise<Response> {
+ const r = await fetch(url);
+ if (!r.ok) throw new Error(`${url}: ${r.status} ${r.statusText}`);
+ return r;
+}
+
+const clock = (t: number) => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, "0")}`;
+
+export function DuetPage(props: { id: string }) {
+ const base = `${import.meta.env.BASE_URL}shows/${props.id}/`;
+ // one transport per mount (its context closes on unmount)
+ const [transport, setTransport] = useState<Transport | null>(null);
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [, setTick] = useState(0);
+
+ useEffect(() => {
+ const t = new Transport();
+ setTransport(t);
+ return () => t.dispose();
+ }, []);
+
+ useEffect(() => {
+ if (!transport) return;
+ let live = true;
+ setLoaded(null);
+ (async () => {
+ const show = (await (await fetchOk(base + "show.json")).json()) as ShowFile;
+ if (!show.voices?.length || !show.audio) throw new Error("show.json needs audio and voices");
+ const [audio, ...teles] = await Promise.all([fetchOk(base + show.audio).then((r) => r.arrayBuffer()), ...show.voices.map((v) => fetchOk(base + v.tele).then((r) => r.arrayBuffer()))]);
+ const voices = show.voices.map((v, i) => ({ name: v.name, track: new TeleTrack(teles[i]) }));
+ await transport.load(audio);
+ if (live) setLoaded({ show, voices });
+ })().catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
+ return () => {
+ live = false;
+ };
+ }, [base, transport]);
+
+ // the readouts follow the transport: at once on a change, and a few times a second while it plays
+ useEffect(() => {
+ if (!transport) return;
+ const off = transport.subscribe(() => setTick((n) => n + 1));
+ const id = setInterval(() => transport.isPlaying && setTick((n) => n + 1), 250);
+ return () => {
+ off();
+ clearInterval(id);
+ };
+ }, [transport]);
+
+ if (error)
+ return (
+ <div className="duet">
+ <p className="duet-msg error">This show could not load: {error}</p>
+ </div>
+ );
+ const st = transport?.state ?? { playing: false, time: 0, duration: 0, epoch: 0 };
+ const title = loaded?.show.title ?? "Loading…";
+ return (
+ <div className="duet">
+ <header className="duet-top">
+ <span className="wordmark">Chimera</span>
+ <span className="duet-title">{title}</span>
+ </header>
+ <main className="duet-heads" style={{ "--voices": loaded?.voices.length ?? 2 } as React.CSSProperties}>
+ {loaded && transport ? loaded.voices.map((v, i) => <Head key={i} name={v.name} track={v.track} show={loaded.show} transport={transport} facing={i > 0 && i === loaded.voices.length - 1 ? -1 : 1} />) : <p className="duet-msg">Loading the song…</p>}
+ </main>
+ <footer className="duet-bar">
+ <button className="primary large" disabled={!loaded} onClick={() => (st.playing ? transport?.pause() : transport?.play())}>
+ {st.playing ? "Pause" : st.duration > 0 && st.time >= st.duration - 0.05 ? "Again" : "Play"}
+ </button>
+ <span className="duet-time">
+ {clock(st.time)} / {clock(st.duration)}
+ </span>
+ <input
+ type="range"
+ aria-label="Position in the song"
+ min={0}
+ max={st.duration || 1}
+ step={0.1}
+ value={st.time}
+ disabled={!loaded}
+ onChange={(e) => transport?.seek(Number(e.target.value))}
+ style={{ "--pos": `${st.duration ? (100 * st.time) / st.duration : 0}%` } as React.CSSProperties}
+ />
+ </footer>
+ </div>
+ );
+}
+
+/** one voice's head; the last of several turns to face the others */
+function Head(props: { name: string; track: TeleTrack; show: ShowFile; transport: Transport; facing: 1 | -1 }) {
+ const { track, show, transport } = props;
+ const feedRef = useRef<HeadFeed | null>(null);
+ if (!feedRef.current) {
+ const model = getModel(track.body, track.sampleRate);
+ const beatStep = (t: number) => {
+ if (!show.bpm) return -1;
+ const s = Math.floor(((t - (show.downbeat ?? 0)) * show.bpm * 4) / 60);
+ return s < 0 ? -1 : s % 16;
+ };
+ feedRef.current = {
+ model,
+ view: VIEW,
+ maxDpr: 1.5,
+ facing: props.facing,
+ frame: () => {
+ const t = transport.time();
+ const i = track.indexAt(t);
+ const msg = track.message(i, beatStep(t));
+ // paused: the head keeps its shape, the voice and the face come to rest
+ if (!transport.isPlaying) return { tele: null, artic: VoiceModel.articFromArray(msg.t.artic), epoch: transport.epoch };
+ return { tele: msg, artic: VoiceModel.articFromArray(msg.t.artic), epoch: transport.epoch };
+ },
+ };
+ }
+ return (
+ <Screen className="duet-head" focus title={props.name} sub={bodyLabel(track.body)} label={`${props.name} voice, ${bodyLabel(track.body)}, in 3D`}>
+ <AnatomyView3D feed={feedRef.current} readouts={false} />
+ </Screen>
+ );
+}
diff --git a/src/ui/render/anatomy3d.ts b/src/ui/render/anatomy3d.ts
index bae6e7c..81f71b4 100644
--- a/src/ui/render/anatomy3d.ts
+++ b/src/ui/render/anatomy3d.ts
@@ -639,10 +639,15 @@ export class Anatomy3D {
private h = 1;
/** a narrow screen: readouts above and below the head (as the 2D view) */
compact = false;
+ /** no readouts beside the head: keep it in the middle of a wide screen too */
+ centred = false;
+ /** which way the turned home view shows the face: 1 to the right, −1 to the left (a duet's
+ * second head, so the two sing towards each other) */
+ facing: 1 | -1 = 1;
private clock = 0;
private readonly gaze = new Gaze();
/** brows, lids, cheeks and the head's nods, from the voice (the view updates it) */
- readonly face = new Expression();
+ face = new Expression();
/** the camera in the head's own frame (the head nods and sways under it) */
private readonly eye = new THREE.Vector3();
private readonly turn = new THREE.Quaternion();
@@ -671,13 +676,23 @@ export class Anatomy3D {
this.beams.dispose();
}
+ /** forget the motion so far (a replay jumped): the face's springs and held-note time, the
+ * outline echoes, the airflow's particle trails and the vocal folds' strobe phase */
+ resetMotion(): void {
+ this.face = new Expression();
+ this.echoes = [];
+ this.lastEcho = -1;
+ this.strobe = 0;
+ for (const p of this.particles) p.px = NaN;
+ }
+
resize(w: number, h: number): void {
this.w = w;
this.h = h;
this.compact = w < 560;
this.camera.aspect = w / h;
// on a wide screen the head sits left of centre, leaving the right for the readouts
- if (this.compact) this.camera.clearViewOffset();
+ if (this.compact || this.centred) this.camera.clearViewOffset();
else this.camera.setViewOffset(w, h, 0.1 * w, 0, w, h);
this.camera.updateProjectionMatrix();
this.beams.setResolution(w, h);
@@ -691,11 +706,12 @@ export class Anatomy3D {
// fit the head's height (and its width in a narrow screen) at a male's size, so bodies compare
const d = 1.1 * Math.max(15.2 / half, 11 / (half * Math.max(0.3, this.camera.aspect)));
const target = r.center.clone();
- const az = 0.62, el = 0.2;
+ // facing left: the same three-quarter view from the head's other side
+ const az = this.facing > 0 ? 0.62 : Math.PI - 0.62, el = 0.2;
return {
target,
home: target.clone().add(new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(d)),
- side: target.clone().add(new THREE.Vector3(0, 0, d)),
+ side: target.clone().add(new THREE.Vector3(0, 0, this.facing * d)),
};
}
diff --git a/src/ui/styles.css b/src/ui/styles.css
index dc46d2f..d9b7087 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -2761,3 +2761,89 @@ input[type="range"]::-moz-range-thumb {
min-height: 300px;
}
}
+
+/* ---------- the duet page (?show=<id>): heads side by side over the transport */
+.duet {
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr) auto;
+ gap: 8px;
+ height: 100vh;
+ height: 100dvh;
+ padding: 6px 16px max(10px, env(safe-area-inset-bottom));
+}
+
+.duet-top {
+ display: flex;
+ align-items: baseline;
+ gap: 18px;
+ min-width: 0;
+ padding: 4px 2px;
+}
+
+.duet-title {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ letter-spacing: 0.2em;
+ text-transform: uppercase;
+ color: var(--blue-mid);
+}
+
+.duet-heads {
+ display: grid;
+ grid-template-columns: repeat(var(--voices, 2), minmax(0, 1fr));
+ gap: 8px;
+ min-height: 0;
+}
+
+.duet-head .screen-body {
+ min-height: 180px;
+}
+
+.duet-bar {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ min-width: 0;
+}
+
+.duet-bar button.primary.large {
+ flex: none;
+ min-width: 96px;
+}
+
+.duet-time {
+ flex: none;
+ font-variant-numeric: tabular-nums;
+ color: var(--blue-mid);
+}
+
+.duet-bar input[type="range"] {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.duet-msg {
+ margin: auto;
+ padding: 24px;
+ text-align: center;
+ color: var(--blue-mid);
+}
+
+.duet-msg.error {
+ color: var(--amber);
+}
+
+@media (max-width: 720px) {
+ .duet {
+ padding: 4px 8px max(8px, env(safe-area-inset-bottom));
+ }
+ .duet-heads {
+ gap: 6px;
+ }
+ .duet-head .screen-head {
+ padding: 7px 8px 0;
+ }
+}
diff --git a/tests/tele.test.ts b/tests/tele.test.ts
new file mode 100644
index 0000000..2a86c62
--- /dev/null
+++ b/tests/tele.test.ts
@@ -0,0 +1,67 @@
+/**
+ * The duet page's recordings (`chimera render notes … --tele`): a file built by hand in the CLI's
+ * layout decodes into the worklet's telemetry messages at the right times, and damaged files are
+ * refused rather than replayed as garbage.
+ */
+import { describe, expect, test } from "bun:test";
+import { TeleTrack } from "../src/show/tele.ts";
+
+const [nArtic, nPh, nOr, nScope] = [17, 3, 2, 32];
+const LEN = 11 + nArtic + 3 * (nPh + nOr) + 2 * nScope;
+
+/** a file of `frames` frames: frame i has f0 = 100 + i, clock = i·768/48000 and artic[k] = i + k/100 */
+function file(frames: number, o: { version?: number; cut?: number } = {}): ArrayBuffer {
+ const buf = new ArrayBuffer(48 + 4 * frames * LEN);
+ const d = new DataView(buf);
+ new Uint8Array(buf).set(new TextEncoder().encode("CHTL"));
+ [o.version ?? 1, 48000, 768, frames, LEN, nArtic, nPh, nOr, nScope].forEach((x, i) => d.setUint32(4 + 4 * i, x, true));
+ d.setFloat32(40, 1, true); // female
+ d.setFloat32(44, 0, true);
+ const f = new Float32Array(buf, 48);
+ for (let i = 0; i < frames; i++) {
+ f[i * LEN + 3] = 100 + i;
+ f[i * LEN + 10] = (i * 768) / 48000;
+ for (let k = 0; k < nArtic; k++) f[i * LEN + 11 + k] = i + k / 100;
+ f[i * LEN + 11 + nArtic + 3 * (nPh + nOr)] = 0.5; // glottalArea[0]
+ }
+ return o.cut ? buf.slice(0, buf.byteLength - o.cut) : buf;
+}
+
+describe("TeleTrack", () => {
+ test("reads the header and each frame as a telemetry message", () => {
+ const t = new TeleTrack(file(10));
+ expect([t.sampleRate, t.hop, t.frames, t.nPh, t.nOr]).toEqual([48000, 768, 10, nPh, nOr]);
+ expect(t.body).toEqual({ female: 1, child: 0 });
+ expect(t.rate).toBe(62.5);
+ const m = t.message(4, 7);
+ expect(m.t.f0).toBe(104);
+ expect(m.t.clock).toBeCloseTo(0.064, 6);
+ expect(m.t.artic.length).toBe(nArtic);
+ expect(m.t.artic[2]).toBeCloseTo(4.02, 5);
+ expect([m.t.phAreas.length, m.t.orAreas.length, m.t.pressureRms.length, m.t.flow.length]).toEqual([nPh, nOr, nPh + nOr, nPh + nOr]);
+ expect(m.t.glottalArea.length).toBe(nScope);
+ expect(m.t.glottalArea[0]).toBe(0.5);
+ expect([m.nPh, m.nOr, m.beatStep]).toEqual([nPh, nOr, 7]);
+ });
+
+ test("the frame at a time is the last one recorded by then, clamped to the recording", () => {
+ const t = new TeleTrack(file(10));
+ expect(t.indexAt(0)).toBe(0);
+ expect(t.indexAt(0.016)).toBe(1); // exactly frame 1's time
+ expect(t.indexAt(0.0159)).toBe(0);
+ expect(t.indexAt(0.1)).toBe(6);
+ expect(t.indexAt(-1)).toBe(0);
+ expect(t.indexAt(99)).toBe(9);
+ expect(t.indexAt(NaN)).toBe(0);
+ expect(t.duration).toBeCloseTo(0.144, 6);
+ });
+
+ test("refuses a truncated file, another version or another format", () => {
+ expect(() => new TeleTrack(file(10, { cut: 4 }))).toThrow(/bytes/);
+ expect(() => new TeleTrack(file(10).slice(0, 20))).toThrow(/too short/);
+ expect(() => new TeleTrack(file(10, { version: 2 }))).toThrow(/version 2/);
+ const other = file(2);
+ new Uint8Array(other).set(new TextEncoder().encode("RIFF"));
+ expect(() => new TeleTrack(other)).toThrow(/not a CHIMERA/);
+ });
+});
diff --git a/tools/layout-lint.ts b/tools/layout-lint.ts
index fff318b..0982f21 100644
--- a/tools/layout-lint.ts
+++ b/tools/layout-lint.ts
@@ -1,8 +1,8 @@
/**
* Layout lint: a smoke test of the layout. Loads every mode at phone, tablet and desktop sizes in
* headless Chromium, before and after audio starts, then some alternate states (every encoder page,
- * every creature, the 3D face, a phrase being spoken), and fails on mistakes screenshot reviews
- * kept missing:
+ * every creature, the 3D face, a phrase being spoken) and the duet page (`?show=`, with a short
+ * duet it renders first), and fails on mistakes screenshot reviews kept missing:
*
* - overlap two pieces of text or controls drawn over each other (DOM text, buttons, inputs,
* dials, and text drawn on canvases, which the page reports by wrapping fillText)
@@ -24,12 +24,13 @@
* - label(..., { moving: true }) on canvas text in flight (a word flying off the lips)
* Text truncated with an ellipsis or a line clamp is reported as a warning, not an error.
*
- * Usage: bun tools/layout-lint.ts [--url http://...] [--out out/layout] [--only 1440x900] [--mode play]
+ * Usage: bun tools/layout-lint.ts [--url http://...] [--out out/layout] [--only 1440x900] [--mode play|duet]
* Without --url it starts its own Vite dev server (build the wasm first: bun run wasm).
* Screenshots of every failing view are saved under --out.
*/
import { chromium } from "playwright-core";
-import { mkdirSync, rmSync } from "node:fs";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { basename } from "node:path";
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
@@ -238,6 +239,22 @@ function hookCanvasText() {
};
}
+/** A two-voice show for the duet page, rendered by the CLI now (shows are never kept in git). The
+ * lint serves it at shows/lint-duet/ itself, so it needs no files under public/. */
+function makeDuet(dir: string): void {
+ mkdirSync(dir, { recursive: true });
+ const melody = (notes: number[][]) => JSON.stringify({ bpm: 120, t0: 0, lyrics: "la la la la", notes });
+ writeFileSync(`${dir}/low.json`, melody([[0, 1], [55, 1], [57, 1], [59, 1], [60, 2]]));
+ writeFileSync(`${dir}/high.json`, melody([[0, 1], [64, 1], [65, 1], [67, 1], [67, 2]]));
+ for (const [v, body] of [["low", "male"], ["high", "female"]]) {
+ const r = Bun.spawnSync(["cargo", "run", "--quiet", "--release", "-p", "chimera-cli", "--", "render", "notes", `${dir}/${v}.json`, `${dir}/${v}`, body, "--tele", `${dir}/${v}.tele`]);
+ if (r.exitCode) throw new Error(`rendering the lint duet: ${r.stderr.toString()}`);
+ }
+ // a long title, to see it trimmed on a phone
+ const voices = [{ name: "Lower", tele: "low.tele" }, { name: "Upper", tele: "high.tele" }];
+ writeFileSync(`${dir}/show.json`, JSON.stringify({ title: "A duet with a title long enough to need trimming", audio: "low.wav", bpm: 120, voices }));
+}
+
async function main() {
const out = arg("out") ?? "out/layout";
rmSync(out, { recursive: true, force: true });
@@ -254,7 +271,10 @@ async function main() {
const only = arg("only");
const onlyMode = arg("mode");
const viewports = only ? VIEWPORTS.filter((v) => `${v.w}x${v.h}` === only).concat(VIEWPORTS.some((v) => `${v.w}x${v.h}` === only) ? [] : [{ w: +only.split("x")[0], h: +only.split("x")[1] }]) : VIEWPORTS;
- const modes = onlyMode ? [onlyMode] : MODES;
+ const duet = !onlyMode || onlyMode === "duet";
+ const modes = onlyMode ? (onlyMode === "duet" ? [] : [onlyMode]) : MODES;
+ const duetDir = `${out}/duet-show`;
+ if (duet) makeDuet(duetDir);
// WebGL through SwiftShader, for the 3D face
const browser = await chromium.launch({ headless: true, args: ["--autoplay-policy=no-user-gesture-required", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
@@ -289,6 +309,19 @@ async function main() {
}
if (await tabs.count()) await tabs.first().click();
};
+ if (duet) {
+ // the duet page: two 3D heads, loaded and then playing
+ await page.route("**/shows/lint-duet/*", (route) => route.fulfill({ path: `${duetDir}/${basename(new URL(route.request().url()).pathname)}` }));
+ await page.goto(new URL("?show=lint-duet", url).href, { waitUntil: "networkidle" });
+ await page.waitForSelector(".duet-head canvas", { timeout: 15000 });
+ await check("duet", 2000);
+ await page.locator(".duet-bar button.primary").click();
+ await check("duet, playing", 1200);
+ }
+ if (!modes.length) {
+ await page.close();
+ continue;
+ }
await page.goto(url, { waitUntil: "networkidle" });
for (const m of modes) {
await mode(m);