the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Sing: your lyrics sung to a tune picked by mood, and Record video to share (#87)
jamesondh-agents[bot]b6969d5a63d5
diff --git a/AGENTS.md b/AGENTS.mdindex efacd92..899c783 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -23,7 +23,7 @@ and the CLI) under a React UI. See the README.- `crates/chimera/`: the engine (no I/O). `crates/chimera-wasm/`: the browser's C ABI.`crates/chimera-cli/`: `chimera render | compare csd | compare tsp | diagnose | calibrate`.- `src/wasm/`: the UI's facade over the engine. `src/worklet/`: the AudioWorklet. `src/ui/`: React- and the canvas renderers.+ and the canvas renderers. `src/song/`: Sing's tunes, fitting words to them, clip recording.- `tests/`: bun tests on the wasm build. `tools/`: e2e, layout lint, spectrogram, speech judges(`asr/` Whisper, `tsp/` the real speakers' data).- `docs/`: architecture, the engine contract (`rust-engine.md`), the UI look, the singer anddiff --git a/README.md b/README.mdindex ddf9b9a..b0f435c 100644--- a/README.md+++ b/README.md@@ -29,9 +29,12 @@ for tests and the `chimera` CLI.gestures and prosody, with the gestural score and a consonant chart on screen. In IPA mode anotice under the box lists the symbols and marks the voice doesn't say (`chimera render speech`prints the same as warnings).-- **Sing**: a pitch roll with lyrics per note; consonants land before the beat. Lyrics can be- English, Korean (Hangul: one block per note, with Korean sound rules) or Russian; each language- is a front end ([docs/language-front-ends.md](docs/language-front-ends.md)).+- **Sing**: type words and the **Sing** button sings them to a tune picked by its mood, each line+ fitted to a phrase of it (Tempo and Key on the Voice screen); **Record video** sings it again into a+ 9:16 clip to share. The keys sing the same words a syllable at a time, legato or not, onto a+ pitch roll; consonants land before the beat. Lyrics can be English, Korean (Hangul: one block per+ note, with Korean sound rules) or Russian; each language is a front end+ ([docs/language-front-ends.md](docs/language-front-ends.md)).- **Beatbox**: pads and a step sequencer, every drum an articulatory gesture.- **Bestiary**: songbird (two-voice syrinx), seal, alligator and elephant.- **Duet** (`?show=<id>`): two 3D heads replay a pre-rendered song.diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsindex e4dba23..eaa3239 100644--- a/src/audio/AudioEngine.ts+++ b/src/audio/AudioEngine.ts@@ -50,6 +50,18 @@ export class AudioEngine {return this.latest.t.clock + Math.min(0.25, (performance.now() - this.latestAt) / 1000);}+ private tap: MediaStreamAudioDestinationNode | null = null;++ /** What the speakers play, as a media stream (to record a clip); null before start(). */+ recordStream(): MediaStream | null {+ if (!this.ctx || !this.master) return null;+ if (!this.tap) {+ this.tap = this.ctx.createMediaStreamDestination();+ this.master.connect(this.tap);+ }+ return this.tap.stream;+ }+get running(): boolean {return !!this.ctx && this.ctx.state === "running";}@@ -189,6 +201,32 @@ export class AudioEngine {this.send({ type: "stopSpeech" });}+ /** The output's RMS over the fast analyser's window (~40 ms); 0 before start(). */+ level(): number {+ const a = this.analyserFast;+ if (!a) return 0;+ const buf = new Float32Array(a.fftSize);+ a.getFloatTimeDomainData(buf);+ let s = 0;+ for (const x of buf) s += x * x;+ return Math.sqrt(s / buf.length);+ }++ /**+ * Resolves once the output has stayed below `floor` for `hold` s, or after `max` s: a clip+ * mustn't open on the tail of what was sounding (a stopped song keeps ringing for a moment).+ */+ async quiet(floor = 0.003, hold = 0.15, max = 2): Promise<void> {+ const t0 = performance.now();+ let since = t0;+ while (performance.now() - t0 < max * 1000) {+ const t = performance.now();+ if (this.level() >= floor) since = t;+ else if (t - since >= hold * 1000) return;+ await new Promise((r) => setTimeout(r, 20));+ }+ }+onReady(l: () => void): () => void {this.readyListeners.add(l);return () => this.readyListeners.delete(l);diff --git a/src/song/fit.ts b/src/song/fit.tsnew file mode 100644index 0000000..3bdbcaa--- /dev/null+++ b/src/song/fit.ts@@ -0,0 +1,117 @@+/**+ * Anyone's words onto a tune: the lyrics' lines go onto the tune's phrases in turn (round the+ * tune again if there are more lines), and each line is fitted to its phrase's notes without+ * changing the phrase's length in beats:+ * - more syllables than notes: the longest note splits in two (same pitch) until there are enough+ * - fewer: each syllable takes a run of notes, its vowel held from one pitch to the next (a+ * melisma, as "-" does in Sing), the extra notes going to the line's last syllables; with less+ * than half a note's worth of syllables, the shortest neighbouring notes merge first+ * A line too long for one phrase splits at a word end; a line of a word or two joins the next.+ */+import type { Syllable, SungNote } from "../wasm/types.ts";+import type { Tune } from "./tunes.ts";++/** the tune's typical phrase, in notes: the line length the lyrics are cut to */+export function phraseSize(tune: Tune): number {+ return Math.max(1, Math.round(tune.phrases.reduce((n, p) => n + p.length, 0) / tune.phrases.length));+}++/** The lyrics' syllables in lines of about `size` (as indices into `syls`). */+export function lines(syls: Syllable[], size: number): number[][] {+ const raw: number[][] = [];+ let cur: number[] = [];+ for (let i = 0; i < syls.length; i++) {+ cur.push(i);+ if (syls[i].phraseEnd) {+ raw.push(cur);+ cur = [];+ }+ }+ if (cur.length) raw.push(cur);+ const short = (p: number[]) => p.length < size / 3;+ const fits = (a: number[], b: number[]) => a.length + b.length <= 1.5 * size;+ // "Oh, yeah, baby": a line of a word or two joins the next one (the last joins the one before)+ const merged: number[][] = [];+ for (const p of raw) {+ const prev = merged[merged.length - 1];+ if (prev && short(prev) && fits(prev, p)) prev.push(...p);+ else merged.push([...p]);+ }+ if (merged.length > 1) {+ const last = merged[merged.length - 1], prev = merged[merged.length - 2];+ if (short(last) && fits(prev, last)) prev.push(...merged.pop()!);+ }+ // a long line: cut at the word ends nearest equal parts (never before a held vowel)+ const out: number[][] = [];+ for (const p of merged) {+ if (p.length <= 1.5 * size) {+ out.push(p);+ continue;+ }+ const k = Math.ceil(p.length / size);+ let start = 0;+ for (let c = 1; c < k; c++) {+ const target = Math.round((c * p.length) / k);+ let cut = -1;+ for (let i = start + 1; i < p.length; i++) if (syls[p[i - 1]].wordEnd && !syls[p[i]].melisma && (cut < 0 || Math.abs(i - target) < Math.abs(cut - target))) cut = i;+ if (cut < 0) break;+ out.push(p.slice(start, cut));+ start = cut;+ }+ out.push(p.slice(start));+ }+ return out;+}++/**+ * One line onto one phrase's notes (see the file's comment). The last note ends the phrase, and+ * only it. `from[k]` is the line's syllable note k sings (a held vowel: the syllable it holds).+ */+export function fitLine(line: Syllable[], phrase: readonly [number, number][]): { notes: SungNote[]; from: number[] } {+ const n = line.length;+ if (!n) return { notes: [], from: [] };+ const notes = phrase.map(([midi, beats]) => ({ midi, beats }));+ while (notes.length < n) {+ let k = 0;+ for (let i = 1; i < notes.length; i++) if (notes[i].beats > notes[k].beats) k = i;+ const half = notes[k].beats / 2;+ notes.splice(k, 1, { midi: notes[k].midi, beats: half }, { midi: notes[k].midi, beats: half });+ }+ // merge the shortest neighbours, keeping the first's pitch (the phrase's last note keeps its own)+ while (notes.length > 2 * n) {+ let k = 0;+ const last = notes.length > 2 ? notes.length - 2 : notes.length - 1;+ for (let i = 1; i < last; i++) if (notes[i].beats + notes[i + 1].beats < notes[k].beats + notes[k + 1].beats) k = i;+ notes.splice(k, 2, { midi: notes[k].midi, beats: notes[k].beats + notes[k + 1].beats });+ }+ const m = notes.length;+ // note j sings syllable at(j); counted from the end, so spare notes go to the last syllables+ const at = (j: number) => n - 1 - Math.floor(((m - 1 - j) * n) / m);+ const out = notes.map((note, j) => {+ const s = line[at(j)];+ const held = j > 0 && at(j - 1) === at(j);+ const syl: Syllable = held ? { text: "~", onset: [], nucleus: s.nucleus, coda: [], melisma: true, wordEnd: s.wordEnd, phraseEnd: false } : { ...s, phraseEnd: false };+ if (j === m - 1) syl.phraseEnd = true;+ return { midi: note.midi, beats: note.beats, syl };+ });+ return { notes: out, from: notes.map((_, j) => at(j)) };+}++/**+ * The whole song: every line on its phrase, `shift` semitones from the tune's pitch. `from[k]` is+ * the index in `syls` of the syllable note k sings.+ */+export function fitSong(tune: Tune, syls: Syllable[], shift = 0): { notes: SungNote[]; from: number[] } {+ const notes: SungNote[] = [], from: number[] = [];+ lines(syls, phraseSize(tune)).forEach((line, k) => {+ const f = fitLine(line.map((i) => syls[i]), tune.phrases[k % tune.phrases.length]);+ for (const n of f.notes) notes.push({ ...n, midi: n.midi + shift });+ for (const j of f.from) from.push(line[j]);+ });+ return { notes, from };+}++/** The words a tune is sung on when none are given: "la" on every note. */+export function la(tune: Tune): string {+ return tune.phrases.map((p) => p.map(() => "la").join(" ")).join("\n");+}diff --git a/src/song/record.ts b/src/song/record.tsnew file mode 100644index 0000000..6357aa2--- /dev/null+++ b/src/song/record.ts@@ -0,0 +1,120 @@+/**+ * A video of the head singing: the face screen's canvas copied each frame into a 9:16 frame (black+ * above and below, which the vector look already is) with the wordmark at the foot, and the voice+ * from the audio graph, through the browser's MediaRecorder. MP4 where the browser records it+ * (Safari, recent Chrome: what Instagram and TikTok take), else WebM. While a clip records, the+ * face screens leave out their measurements (`recording`), so what you see is what you get.+ */+import { label } from "../ui/render/vector.ts";+import { V } from "../ui/colors.ts";++const W = 720, H = 1280;+/** the band at the foot that holds the wordmark */+const FOOT = 150;+const TYPES = ["video/mp4;codecs=avc1.42E01E,mp4a.40.2", "video/mp4", "video/webm;codecs=vp9,opus", "video/webm;codecs=vp8,opus", "video/webm"];++function pickType(): string | null {+ if (typeof MediaRecorder === "undefined" || typeof HTMLCanvasElement === "undefined" || !("captureStream" in HTMLCanvasElement.prototype)) return null;+ return TYPES.find((t) => MediaRecorder.isTypeSupported(t)) ?? null;+}++/**+ * A clip is recording: the face screens draw the head without readouts or measurements. Owned by+ * the clip that set it, so an earlier clip finishing late can't clear a newer one's.+ */+export const recording = {+ owner: null as Clip | null,+ get on(): boolean {+ return this.owner !== null;+ },+};++/** whether this browser can record a clip at all */+export const canRecord = (): boolean => pickType() !== null;++export class Clip {+ private frame = document.createElement("canvas");+ private rec!: MediaRecorder;+ private chunks: Blob[] = [];+ private raf = 0;+ private type: string;+ /** the frame's capture track: ours to stop (the audio track is the engine's, shared) */+ private video: MediaStreamTrack[] = [];+ /** settles once the recorder has stopped, however it stopped (stop(), cancel(), or a failure) */+ private ended!: Promise<void>;+ /** the recorder reported an error: what it holds isn't a whole clip */+ private failed = false;++ /**+ * Starts recording `source()`, read every frame (the face's canvas changes when 2D/3D is+ * toggled); throws (having let go of everything it took) if the browser can't.+ */+ constructor(source: () => HTMLCanvasElement | null, audio: MediaStream) {+ this.type = pickType()!;+ recording.owner = this;+ try {+ this.begin(source, audio);+ } catch (e) {+ this.release();+ throw e;+ }+ }++ private begin(source: () => HTMLCanvasElement | null, audio: MediaStream): void {+ this.frame.width = W;+ this.frame.height = H;+ const ctx = this.frame.getContext("2d")!;+ const draw = () => {+ ctx.globalCompositeOperation = "source-over";+ ctx.globalAlpha = 1;+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, W, H);+ const src = source();+ const sw = src?.width ?? 0, sh = src?.height ?? 0;+ if (src && sw > 0 && sh > 0) {+ const k = Math.min(W / sw, (H - FOOT) / sh);+ ctx.drawImage(src, (W - sw * k) / 2, (H - FOOT - sh * k) / 2, sw * k, sh * k);+ }+ label(ctx, "CHIMERA", W / 2, H - FOOT / 2, { size: 30, color: V.blue, weight: "m", ls: 0.34, align: "center" });+ this.raf = requestAnimationFrame(draw);+ };+ draw();+ this.video = this.frame.captureStream(30).getVideoTracks();+ this.rec = new MediaRecorder(new MediaStream([...this.video, ...audio.getAudioTracks()]), { mimeType: this.type, videoBitsPerSecond: 5_000_000 });+ this.rec.ondataavailable = (e) => e.data.size && this.chunks.push(e.data);+ // a recorder can also stop by itself (an encoder or resource failure): it lets go of the+ // capture and shows the measurements again then, not when the song ends+ this.rec.onerror = () => (this.failed = true);+ this.ended = new Promise((resolve) => {+ this.rec.onstop = () => {+ this.release();+ resolve();+ };+ });+ this.rec.start(500);+ }++ /** Finish: the clip as a file named `name` (the extension is added); rejects if the recorder failed. */+ async stop(name: string): Promise<File> {+ cancelAnimationFrame(this.raf);+ // the face screens show their measurements again now, not when the browser hands the file over+ if (recording.owner === this) recording.owner = null;+ if (this.rec.state !== "inactive") this.rec.stop();+ await this.ended;+ if (this.failed || !this.chunks.length) throw new Error("the recording failed");+ const type = this.type.split(";")[0];+ return new File(this.chunks, `${name}.${type === "video/mp4" ? "mp4" : "webm"}`, { type });+ }++ /** Throw it away. */+ cancel(): void {+ if (this.rec.state !== "inactive") this.rec.stop();+ this.release();+ }++ private release(): void {+ if (recording.owner === this) recording.owner = null;+ cancelAnimationFrame(this.raf);+ for (const t of this.video) t.stop();+ }+}diff --git a/src/song/tunes.ts b/src/song/tunes.tsnew file mode 100644index 0000000..1d84f94--- /dev/null+++ b/src/song/tunes.ts@@ -0,0 +1,81 @@+/**+ * Sing's tunes, named for how they sound: melodies anyone's words are fitted to (fit.ts). All are+ * written for this instrument except Twinkle (traditional). Each phrase is one line of lyrics; a song longer than the tune goes round again.+ * Notes are [midi, beats], at the female voice's pitch; `octave` shifts the other bodies, as the+ * demo songs do. Phrases end on a long note: the breath before the next line comes out of it.+ */+import { DEMO_SONGS } from "../wasm/engine.ts";++export interface Tune {+ id: string;+ name: string;+ bpm: number;+ octave: { male: number; female: number; child: number };+ phrases: [number, number][][];+}++/** a demo song's melody (the engine's catalog, shared with `chimera render song`) cut into phrases of `sizes` notes */+function fromDemo(id: string, name: string, demo: string, sizes: number[]): Tune {+ const d = DEMO_SONGS.find((s) => s.name === demo)!;+ let at = 0;+ const phrases = sizes.map((n) => d.notes.slice(at, (at += n)).map(([m, b]): [number, number] => [m, b]));+ return { id, name, bpm: d.bpm, octave: d.octave, phrases };+}++export const TUNES: readonly Tune[] = [+ // "Made of air", the instrument's own: minor, unhurried+ fromDemo("dreamy", "Dreamy", "Made of air", [9, 10]),+ {+ // major, bright, climbing+ id: "joyful",+ name: "Joyful",+ bpm: 104,+ octave: { male: -1, female: 0, child: 0 },+ phrases: [+ [[64, 1], [64, 1], [67, 1], [69, 1], [67, 1.5], [64, 0.5], [62, 2]],+ [[60, 1], [62, 1], [64, 1], [67, 1], [64, 1.5], [62, 0.5], [60, 2]],+ [[69, 1], [69, 1], [72, 1], [69, 1], [67, 1.5], [64, 0.5], [67, 2]],+ [[65, 1], [64, 1], [62, 1], [64, 1], [62, 1], [59, 1], [60, 2]],+ ],+ },+ {+ // minor, slow, falling back home+ id: "somber",+ name: "Somber",+ bpm: 76,+ octave: { male: -1, female: 0, child: 0 },+ phrases: [+ [[57, 1], [60, 1], [64, 1.5], [62, 0.5], [60, 1], [59, 1], [57, 2]],+ [[57, 1], [60, 1], [64, 1], [67, 1], [65, 1.5], [64, 0.5], [64, 2]],+ [[65, 1], [64, 1], [62, 1], [60, 1], [62, 1.5], [60, 0.5], [59, 2]],+ [[57, 1], [59, 1], [60, 1], [62, 1], [64, 1], [59, 1], [57, 2]],+ ],+ },+ {+ // quick, short notes, room for many words+ id: "playful",+ name: "Playful",+ bpm: 120,+ octave: { male: -1, female: 0, child: 0 },+ phrases: [+ [[67, 0.5], [67, 0.5], [64, 0.5], [67, 0.5], [69, 1], [67, 1], [64, 0.5], [62, 0.5], [60, 1], [62, 2]],+ [[60, 0.5], [60, 0.5], [62, 0.5], [64, 0.5], [67, 1], [64, 1], [62, 0.5], [60, 0.5], [62, 1], [64, 2]],+ [[67, 0.5], [67, 0.5], [69, 0.5], [71, 0.5], [72, 1], [71, 1], [69, 0.5], [67, 0.5], [64, 1], [67, 2]],+ [[69, 0.5], [67, 0.5], [64, 0.5], [62, 0.5], [60, 1], [62, 1], [64, 0.5], [62, 0.5], [60, 1], [60, 2]],+ ],+ },+ {+ // a slow waltz, long notes+ id: "gentle",+ name: "Gentle",+ bpm: 96,+ octave: { male: -1, female: 0, child: 0 },+ phrases: [+ [[65, 2], [69, 1], [72, 2], [69, 1], [67, 2], [65, 1], [67, 3]],+ [[65, 2], [69, 1], [72, 2], [74, 1], [72, 2], [69, 1], [67, 3]],+ [[70, 2], [69, 1], [67, 2], [65, 1], [64, 2], [65, 1], [67, 3]],+ [[65, 2], [69, 1], [67, 2], [64, 1], [62, 2], [64, 1], [65, 3]],+ ],+ },+ fromDemo("twinkle", "Twinkle, twinkle", "Twinkle, twinkle", [7, 7]),+];diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsxindex afe715c..3d902dd 100644--- a/src/ui/components/AnatomyView.tsx+++ b/src/ui/components/AnatomyView.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState } from "react";+import { recording } from "../../song/record.ts";import { AnatomyRenderer, type FaceView, type HandleId, type Slot } from "../render/anatomy.ts";import { Glow } from "../render/vector.ts";import { engine } from "../../audio/AudioEngine.ts";@@ -102,12 +103,15 @@ export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormantconst f = m.frame(a);if (++fTick % 4 === 0 || formants.length === 0) formants = m.transfer(a).formants;const info = infoRef.current(m, f, tele);+ // recording a clip: the head without the measurements+ const clean = recording.on;ctx.setTransform(1, 0, 0, 1, 0, 0);ctx.globalCompositeOperation = "source-over";ctx.fillStyle = "#000";ctx.fillRect(0, 0, canvas.width, canvas.height);ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- r.draw(ctx, m, f, a, tele, st.view, { hover: hoverRef.current, drag: dragRef.current?.id ?? null, dt, formants: formantsRef.current ? formants : [], slots: slotsRef.current(m, a, f, formants, tele), info: info.map((s) => s.toUpperCase()) });+ const view = clean ? { ...st.view, calipers: false, grid: false } : st.view;+ r.draw(ctx, m, f, a, tele, view, { hover: hoverRef.current, drag: dragRef.current?.id ?? null, dt, formants: formantsRef.current && !clean ? formants : [], slots: clean ? [] : slotsRef.current(m, a, f, formants, tele), info: clean ? [] : info.map((s) => s.toUpperCase()) });overlayRef.current?.(ctx, r, m, f, a, { w, h, dt });glow.apply(canvas, ctx, dpr);}diff --git a/src/ui/components/AnatomyView3D.tsx b/src/ui/components/AnatomyView3D.tsxindex 2f3469c..fbcb2cc 100644--- a/src/ui/components/AnatomyView3D.tsx+++ b/src/ui/components/AnatomyView3D.tsx@@ -11,6 +11,7 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js";import { Anatomy3D } from "../render/anatomy3d.ts";import { Petting } from "../render/petting.ts";import { drawReadouts } from "../render/readouts.ts";+import { recording } from "../../song/record.ts";import { Glow, label } from "../render/vector.ts";import { engine } from "../../audio/AudioEngine.ts";import { sameBody } from "../body.ts";@@ -40,9 +41,12 @@ export interface HeadFeed {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; feed?: HeadFeed; readouts?: boolean }) {+export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showFormants?: boolean; overlay?: OverlayFn; feed?: HeadFeed; readouts?: boolean; view?: ViewFlags }) {const feedRef = useRef<HeadFeed | undefined>(props.feed);feedRef.current = props.feed;+ // the live head's view flags, when not the face screen's toggles (the Song page's fixed look)+ const viewRef = useRef<ViewFlags | undefined>(props.view);+ viewRef.current = props.view;const readoutsRef = useRef(props.readouts ?? true);readoutsRef.current = props.readouts ?? true;const overlayRef = useRef<OverlayFn | undefined>(props.overlay);@@ -188,7 +192,9 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showFormatele = 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;+ // recording a clip: the head without the measurements+ const clean = !feed && recording.on;+ const view = feed ? feed.view : clean ? { ...st.view, calipers: false, grid: false } : (viewRef.current ?? st.view);r.face.content = pet.content;r.face.update(tele, elapsed);const m = feed ? feed.model : model.current;@@ -216,7 +222,7 @@ export function AnatomyView3D(props: { slots?: SlotsFn; info?: InfoFn; showFormastepTween(dt);controls.update(dt);const f = m.frame(a);- const readouts = readoutsRef.current;+ const readouts = readoutsRef.current && !clean;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);diff --git a/src/ui/components/PianoRoll.tsx b/src/ui/components/PianoRoll.tsxindex 95bcab9..402d9dd 100644--- a/src/ui/components/PianoRoll.tsx+++ b/src/ui/components/PianoRoll.tsx@@ -4,7 +4,7 @@ import { engine } from "../../audio/AudioEngine.ts";import { useStore } from "../store.ts";import { roll, tickSinging } from "../singing.ts";import { TEXT, V } from "../colors.ts";-import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";+import { beam, beamPts, label, labelWidth, seg, type Pt } from "../render/vector.ts";import { nearestBody } from "../body.ts";/** pixels per second of voice time */@@ -69,7 +69,8 @@ export function PianoRoll() {}if (pc === 0) {seg(ctx, left, yc + rowH / 2, w, yc + rowH / 2, V.frame, 1);- label(ctx, `${NAMES[pc]}${Math.floor(m / 12) - 1}`, 6, yc + 3, { size: 9, color: TEXT.secondary, ls: 0.1 });+ // a C row at the very foot of the roll would be cut by its edge: its name waits until it's in+ if (yc + 5 <= h) label(ctx, `${NAMES[pc]}${Math.floor(m / 12) - 1}`, 6, yc + 3, { size: 9, color: TEXT.secondary, ls: 0.1 });}}beam(ctx, dotted, V.frame, 1, { dash: [1, 5] });@@ -93,7 +94,12 @@ export function PianoRoll() {ctx.restore();}beam(ctx, r, V.green, live ? 1.6 : 1.2, { alpha: live ? 1 : future ? 0.38 : 0.62, hot: live });- if (n.text && n.text !== "~") label(ctx, n.text.toUpperCase(), x0 + 1, yc - barH / 2 - 4, { size: 10, color: live ? V.white : TEXT.secondary, ls: 0.12, alpha: future ? 0.6 : 1 });+ if (n.text && n.text !== "~") {+ const text = n.text.toUpperCase();+ const o = { size: 10, color: live ? V.white : TEXT.secondary, ls: 0.12, alpha: future ? 0.6 : 1 };+ // a tune's coming syllables scroll in from the right edge, cut by it until they're in+ label(ctx, text, x0 + 1, yc - barH / 2 - 4, { ...o, moving: x0 + 1 + labelWidth(ctx, text, o) > w });+ }}// the pitch actually sungdiff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsxindex 576435b..7e24c51 100644--- a/src/ui/components/SingPanel.tsx+++ b/src/ui/components/SingPanel.tsx@@ -1,6 +1,8 @@import { useEffect, useRef, useState } from "react";import { useStore } from "../store.ts";-import { useSing, playDemo, stopSinging, soundingSyllable, sungNow, DEMO_SONGS, ensureDictionary } from "../singing.ts";+import { useSing, playTune, stopSinging, soundingSyllable, sungNow, TUNES, ensureDictionary } from "../singing.ts";+import { engine } from "../../audio/AudioEngine.ts";+import { canRecord, Clip } from "../../song/record.ts";import { mouthWords } from "../mouthWords.ts";import { V } from "../colors.ts";import { Keys, MidiButton } from "./Keys.tsx";@@ -16,10 +18,10 @@ import type { InfoFn } from "./AnatomyView.tsx";/** epilarynx narrowing for the singer's ring (measured: +3 to +12 dB at 2.4–3.6 kHz, adult male) */const RING = 0.85;-/** the syllable being sung now: the demo's, or the one the held key is singing */+/** the syllable being sung now: the tune's, or the one the held key is singing */function syllableNow(): string | null {const s = useSing.getState();- if (s.demo) return s.syllables[s.demoAt]?.text ?? null;+ if (s.playing) return s.syllables[s.at]?.text ?? null;return soundingSyllable();}@@ -40,22 +42,22 @@ function Lyrics() {const lyrics = useSing((s) => s.lyrics);const syllables = useSing((s) => s.syllables);const cursor = useSing((s) => s.cursor);- const demo = useSing((s) => s.demo);- const demoAt = useSing((s) => s.demoAt);+ const demo = useSing((s) => s.playing);+ const sungAt = useSing((s) => s.at);const setLyrics = useSing((s) => s.setLyrics);const setCursor = useSing((s) => s.setCursor);- const at = demo ? demoAt : -1;- const done = demo ? demoAt : cursor;+ const at = demo ? sungAt : -1;+ const done = demo ? sungAt : cursor;return (<div className="lyrics"><textareavalue={lyrics}onChange={(e) => setLyrics(e.target.value)}onKeyDown={(e) => e.stopPropagation()}- rows={1}+ rows={Math.min(4, lyrics.split("\n").length)}aria-label="Lyrics to sing"placeholder="Type the words to sing"- title="Each note sings the next syllable. Hold a key while you press the next one to sing legato. A lone “-” between words holds a vowel over several notes; hyphens split a word your way (“ti-ger”)."+ title="Sing sings these words to the tune, a line to each of its phrases. Each key sings the next syllable; hold a key while you press the next one to sing legato. A lone “-” between words holds a vowel over several notes; hyphens split a word your way (“ti-ger”)."/><div className="syllables" role="group" aria-label="Syllables. Each note sings the marked one; choose another to start there.">{syllables.map((s, i) => (@@ -91,6 +93,10 @@ function SongControls() {const setArtic = useStore((s) => s.setArtic);const vibrato = useSing((s) => s.vibrato);const setVibrato = useSing((s) => s.setVibrato);+ const tempo = useSing((s) => s.tempo);+ const setTempo = useSing((s) => s.setTempo);+ const key = useSing((s) => s.key);+ const setKey = useSing((s) => s.setKey);return (<EncoderPageslabel="Song voice"@@ -105,6 +111,14 @@ function SongControls() {{ label: "Ring", value: epilarynx, min: 0, max: 1, onChange: (v) => setArtic({ epilarynx: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) },],},+ {+ // the tune's speed and key, from the next time Sing is pressed+ name: "Tune",+ encoders: [+ { label: "Tempo", value: tempo, min: 0.5, max: 1.5, onChange: (v) => setTempo(Math.round(v * 20) / 20), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) },+ { label: "Key", value: key, min: -12, max: 12, onChange: (v) => setKey(Math.round(v)), format: (v) => ({ value: (v > 0.5 ? "+" : "") + String(Math.round(v)), unit: "semitones" }) },+ ],+ },{name: "Tone",encoders: [{ label: "Bright", value: source.brightness, min: 0, max: 1, onChange: (v) => setSource({ brightness: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) }],@@ -115,48 +129,119 @@ function SongControls() {}/**- * Sing's main button: sing the chosen song (its own words), or stop it. A song getting ready- * (audio starting, the dictionary loading) counts as playing: Stop cancels it, and choosing- * another song replaces it.+ * Sing's main button: sing the lyrics to the chosen tune, or stop. A song getting ready (audio+ * starting, the dictionary loading) counts as playing: Stop cancels it, and choosing another tune+ * replaces it. Record video sings it again into a clip of the face screen (Share and Save once it's done).*/function SingActions() {const start = useStore((s) => s.start);- const demo = useSing((s) => s.demo);- const [song, setSong] = useState(DEMO_SONGS[0].name);+ const playing = useSing((s) => s.playing);+ const tune = useSing((s) => s.tune);+ const setTune = useSing((s) => s.setTune);const [pending, setPending] = useState(false);+ const [recording, setRecording] = useState(false);+ const [clip, setClip] = useState<{ file: File; url: string } | null>(null);+ /** bumped by every start and stop: a start still waiting no longer counts */const request = useRef(0);+ /** bumped by every Record video: a clip still being finished for an earlier one isn't offered */+ const take = useRef(0);+ /** the clip recording now, if any (one at a time) */+ const recorder = useRef<Clip | null>(null);// the audio must be running: if it failed to start, nothing is planned and the error showsconst ready = async () => {await start();if (!useStore.getState().started) throw new Error("no audio");};- // playDemo waits for `ready` itself, so a stop meanwhile (body, mode, another song) cancels it- const sing = (name: string) => {+ const drop = () => {+ recorder.current?.cancel();+ recorder.current = null;+ setRecording(false);+ };+ // the clip's life is the tune's run: it starts as the tune is sent (never for a start that was+ // cancelled), is saved when it's sung to the end, and goes when it's stopped from anywhere+ const sing = (id: string, record = false) => {const n = ++request.current;+ const k = record ? ++take.current : take.current;+ drop();setPending(true);- playDemo(name, useStore.getState().body, ready)+ let mine: Clip | null = null;+ const hooks = !record+ ? {}+ : {+ onStart: () => {+ const face = () => document.querySelector<HTMLCanvasElement>(".screen.left canvas");+ const audio = engine.recordStream();+ if (n !== request.current || !face() || !audio) throw new Error("not recording");+ mine = recorder.current = new Clip(face, audio);+ setRecording(true);+ setClip(null);+ },+ onEnd: () => {+ const c = mine;+ if (!c || recorder.current !== c) return;+ recorder.current = null;+ setRecording(false);+ c.stop(`chimera-${id}`)+ .then((file) => take.current === k && setClip({ file, url: URL.createObjectURL(file) }))+ .catch((e) => console.warn("Record video:", e));+ },+ onStop: () => {+ if (mine && recorder.current === mine) drop();+ },+ };+ // a clip waits for the last sound (the song this one replaces) to die away, or it opens on its tail+ const go = record ? async () => (await ready(), await engine.quiet()) : ready;+ playTune(id, useStore.getState().body, go, hooks).catch(() => {}).finally(() => request.current === n && setPending(false));};const stop = () => {request.current++; // the song getting ready, if any, no longer countssetPending(false);- stopSinging();+ stopSinging(); // its run's onStop drops the clip+ drop();};- const press = () => (demo || pending ? stop() : sing(song));+ useEffect(() => () => void (clip && URL.revokeObjectURL(clip.url)), [clip]);+ // leaving Sing: nothing still starting may begin a clip, and one recording goes+ useEffect(+ () => () => {+ request.current++;+ take.current++;+ recorder.current?.cancel();+ recorder.current = null;+ },+ [],+ );+ const press = () => (playing || pending ? stop() : sing(tune));+ const share = clip && typeof navigator.canShare === "function" && navigator.canShare({ files: [clip.file] });return (<ActionBar label="Song" onSpace={press}>- <PrimaryButton label="Sing" playing={!!demo || pending} onClick={press} />+ <PrimaryButton label="Sing" playing={(!!playing || pending) && !recording} busy={recording ? "Recording…" : null} onClick={press} /><Menu- label="Song"+ label="Tune"icon="note"- value={demo ?? song}- options={DEMO_SONGS.map((s) => ({ value: s.name, label: s.name }))}- onChange={(name) => {- setSong(name);- if (demo || pending) sing(name);+ value={tune}+ options={TUNES.map((t) => ({ value: t.id, label: t.name }))}+ onChange={(id) => {+ setTune(id);+ if ((playing || pending) && !recording) sing(id);}}/>+ {canRecord() && (+ <Chip toggle={false} onClick={() => (recording ? stop() : sing(tune, true))} title="Sing it again and record the face into a video">+ {recording ? "Cancel" : "Record video"}+ </Chip>+ )}+ {clip && share && (+ <Chip toggle={false} tone="amber" onClick={() => void navigator.share({ files: [clip.file] }).catch(() => {})}>+ Share+ </Chip>+ )}+ {clip && (+ <a className="chip" href={clip.url} download={clip.file.name}>+ Save+ </a>+ )}</ActionBar>);}@@ -167,7 +252,7 @@ export function SingRight() {// opens on Sing without oneuseEffect(ensureDictionary, []);const ring = useStore((s) => s.artic.epilarynx >= RING - 0.05);- const next = useSing((s) => (s.demo ? null : (s.syllables[s.cursor]?.text ?? null)));+ const next = useSing((s) => (s.playing ? null : (s.syllables[s.cursor]?.text ?? null)));return (<div className="right right-sing"><SingActions />diff --git a/src/ui/components/SpectrumView.tsx b/src/ui/components/SpectrumView.tsxindex 2f35064..962a1af 100644--- a/src/ui/components/SpectrumView.tsx+++ b/src/ui/components/SpectrumView.tsx@@ -6,7 +6,7 @@ import { useStore } from "../store.ts";import { useModel } from "../useModel.ts";import { VoiceModel } from "../analysis.ts";import { TEXT, V } from "../colors.ts";-import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";+import { beam, beamPts, label, labelWidth, seg, type Pt } from "../render/vector.ts";const FMIN = 60, FMAX = 8000;const RANGE = 62; // dB shown@@ -31,9 +31,12 @@ export function SpectrumView(props: { ring?: boolean }) {const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const f0 = tele && tele.t.voicing > 0.3 ? tele.t.f0 : 0;+ // the F0 label is written to the left of its marker: a frequency label under it gives way+ const f0Text = `F0 ${Math.round(f0)}`;+ const f0Left = f0 ? fx(f0) - 9 - labelWidth(ctx, f0Text, { size: 9, ls: 0.12 }) : 0;for (const f of [100, 200, 500, 1000, 2000, 5000]) {seg(ctx, fx(f), top, fx(f), bot, V.frame, 1);- if (!(f0 && Math.abs(fx(f) - fx(f0)) < 40)) label(ctx, f >= 1000 ? `${f / 1000}K` : String(f), fx(f), h - 6, { size: 9, color: TEXT.secondary, align: "center", ls: 0.1 });+ if (!(f0 && fx(f) + 12 > f0Left && fx(f) - 12 < fx(f0) + 6)) label(ctx, f >= 1000 ? `${f / 1000}K` : String(f), fx(f), h - 6, { size: 9, color: TEXT.secondary, align: "center", ls: 0.1 });}for (const db of [-20, -40]) {seg(ctx, left, dbY(db), right, dbY(db), V.frame, 1, { dash: [2, 4] });@@ -111,7 +114,7 @@ export function SpectrumView(props: { ring?: boolean }) {tri.lineTo(x, bot + 1);tri.closePath();beam(ctx, tri, V.green, 1.2);- label(ctx, `F0 ${Math.round(f0)}`, x - 9, bot + 13, { size: 9, color: V.green, align: "right", ls: 0.12 });+ label(ctx, f0Text, x - 9, bot + 13, { size: 9, color: V.green, align: "right", ls: 0.12 });}});return <canvas ref={ref} className="instrument-canvas" aria-label="Output spectrum: harmonics, the vocal tract's resonances and its formants" role="img" />;diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.tsindex d61da2e..0677e53 100644--- a/src/ui/render/anatomy.ts+++ b/src/ui/render/anatomy.ts@@ -454,8 +454,12 @@ export class AnatomyRenderer {seg(ctx, x0, y0, x1, y1, V.white, 1.4, { hot: true });const nx = -(y1 - y0), ny = x1 - x0, nl = Math.hypot(nx, ny) || 1;for (const [x, y] of [[x0, y0], [x1, y1]]) seg(ctx, x - (nx / nl) * 4, y - (ny / nl) * 4, x + (nx / nl) * 4, y + (ny / nl) * 4, V.white, 1.2);- const lx = Math.max(x0, x1) + 10, ly = Math.min(y0, y1) - 4;- label(ctx, ma <= 0.0005 ? "CLOSED" : `${ma.toFixed(2)} CM²`, lx, ly, { size: 11, color: V.white, ls: 0.12 });+ // at the lips, in front of them is where Sing and Speak write the words: the label goes behind+ const end = f.grid[f.grid.length - 1];+ const lipsX = Math.max(this.P(end.inner)[0], this.P(end.outer)[0]);+ const atLips = lipsX - Math.max(x0, x1) < 1.5 * this.pxPerCm;+ const lx = atLips ? Math.min(x0, x1) - 10 : Math.max(x0, x1) + 10, ly = Math.min(y0, y1) - 4;+ label(ctx, ma <= 0.0005 ? "CLOSED" : `${ma.toFixed(2)} CM²`, lx, ly, { size: 11, color: V.white, ls: 0.12, align: atLips ? "right" : "left" });}private drawHandles(ctx: CanvasRenderingContext2D, model: VoiceModel, f: HumanFrame, a: HumanArtic, hover: HandleId | null, drag: HandleId | null): void {diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex 77e2c1b..472aa3a 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -4,7 +4,8 @@* (the previous syllable's coda runs straight into the next onset); a "-" in the lyrics holds* the vowel onto a new pitch (melisma). Releasing the sounding key while another is still down* glides back to that key on the same vowel. Key velocity sets the breath.- * Demo songs are planned whole (planSong) and sent as one score.+ * Sing sings the same words to a tune (src/song): fitted to its phrases, planned whole (planSong)+ * and sent as one score. The words, tune, tempo and key are kept on the device.*/import { create } from "zustand";import { engine } from "../audio/AudioEngine.ts";@@ -12,9 +13,10 @@ import { g2p } from "./speech.ts";import { lyricsToSyllables, type Syllable } from "../wasm/engine.ts";import { planSong, planNoteOn, planNoteOff, planMelisma } from "../wasm/engine.ts";import { EXHALE_LABEL } from "../wasm/engine.ts";-import { DEMO_SONGS } from "../wasm/engine.ts";import type { Gesture } from "../wasm/types.ts";import { nearestBody, type BodyMix } from "./body.ts";+import { TUNES } from "../song/tunes.ts";+import { fitSong, la } from "../song/fit.ts";/** A note on the piano roll, on the voice clock (s); t1 is null while it is held. */export interface RollNote {@@ -40,30 +42,75 @@ interface SingState {cursor: number;/** vibrato depth on held vowels (cents) */vibrato: number;- /** the demo song playing, if any */- demo: string | null;- /** index of the demo syllable being sung (−1: none yet) */- demoAt: number;+ /** the tune Sing sings the words to (a TUNES id) */+ tune: string;+ /** the tune's tempo, as a multiple of its own */+ tempo: number;+ /** semitones up or down from the tune's own key (after the body's octave) */+ key: number;+ /** the tune being sung, if any */+ playing: string | null;+ /** index in `syllables` of the one the tune is singing (−1: none, or the tune sings "la") */+ at: number;setLyrics: (text: string) => void;setCursor: (i: number) => void;setVibrato: (cents: number) => void;+ setTune: (id: string) => void;+ setTempo: (x: number) => void;+ setKey: (semitones: number) => void;}+const KEPT = "chimera-sing";++/** the last session's words, tune, tempo and key (anything missing or odd: the defaults) */+function kept(): { lyrics: string; tune: string; tempo: number; key: number } {+ const d = { lyrics: DEFAULT_LYRICS, tune: TUNES[0].id, tempo: 1, key: 0 };+ try {+ const k = JSON.parse(localStorage.getItem(KEPT) ?? "null") as Record<string, unknown> | null;+ if (!k) return d;+ return {+ lyrics: typeof k.lyrics === "string" ? k.lyrics : d.lyrics,+ tune: TUNES.some((t) => t.id === k.tune) ? (k.tune as string) : d.tune,+ tempo: typeof k.tempo === "number" && k.tempo >= 0.5 && k.tempo <= 1.5 ? k.tempo : d.tempo,+ key: typeof k.key === "number" && Math.abs(k.key) <= 12 ? Math.round(k.key) : d.key,+ };+ } catch {+ return d; // no storage here (a private window): start fresh+ }+}++const atLoad = kept();+export const useSing = create<SingState>((set, get) => ({- lyrics: DEFAULT_LYRICS,- syllables: lyricsToSyllables(DEFAULT_LYRICS),+ lyrics: atLoad.lyrics,+ syllables: lyricsToSyllables(atLoad.lyrics),cursor: 0,vibrato: 35,- demo: null,- demoAt: -1,+ tune: atLoad.tune,+ tempo: atLoad.tempo,+ key: atLoad.key,+ playing: null,+ at: -1,setLyrics: (text) => {stopDemo();set({ lyrics: text, syllables: lyricsToSyllables(text), cursor: 0 });},setCursor: (i) => set({ cursor: Math.max(0, Math.min(i, Math.max(0, get().syllables.length - 1))) }),setVibrato: (cents) => set({ vibrato: cents }),+ setTune: (id) => set({ tune: id }),+ setTempo: (x) => set({ tempo: x }),+ setKey: (semitones) => set({ key: semitones }),}));+useSing.subscribe((s, p) => {+ if (s.lyrics === p.lyrics && s.tune === p.tune && s.tempo === p.tempo && s.key === p.key) return;+ try {+ localStorage.setItem(KEPT, JSON.stringify({ lyrics: s.lyrics, tune: s.tune, tempo: s.tempo, key: s.key }));+ } catch {+ // not kept: the session still works+ }+});+/** Load the pronouncing dictionary, then re-read the lyrics with it (the cursor stays). */export function ensureDictionary(): void {if (g2p.loaded) return;@@ -212,9 +259,9 @@ export function singNoteOff(midi: number, body: BodyMix): void {exhalesLive = true;}-// ---- demo songs+// ---- tunes-interface DemoRun {+interface TuneRun {id: number;/** note start/end times in plan time (s) */times: [number, number][];@@ -223,27 +270,31 @@ interface DemoRun {/** what the mouth shows per note, and the note whose syllable it is (a melisma's parent) */shown: string[];parent: number[];+ /** each note's syllable in the lyrics (−1: the tune sings "la") */+ from: number[];end: number;/** voice clock of plan time 0, once the worklet has it */offset: number | null;+ hooks: TuneHooks;}-let demoRun: DemoRun | null = null;-/** bumped by every stop: a demo still waiting for audio or the dictionary then gives up */+/** What a caller (Record video) does as a tune's run begins, ends or is stopped. */+export interface TuneHooks {+ /** just before it's sent to the voice, after every wait (a throw: it isn't sung) */+ onStart?: () => void;+ /** sung to the end */+ onEnd?: () => void;+ /** stopped before the end, from anywhere (Stop, another tune, the mode or body changing) */+ onStop?: () => void;+}++let demoRun: TuneRun | null = null;+/** bumped by every stop: a tune still waiting for audio or the dictionary then gives up */let demoToken = 0;-/**- * The player's own lyrics and cursor while a demo shows the song's words: given back when the- * demo ends or stops, so a demo never costs anyone the words they typed.- */-let ownWords: { lyrics: string; cursor: number } | null = null;function endDemo(): void {demoRun = null;- const w = ownWords;- ownWords = null;- if (!w) return void useSing.setState({ demo: null, demoAt: -1 });- const syllables = lyricsToSyllables(w.lyrics);- useSing.setState({ demo: null, demoAt: -1, lyrics: w.lyrics, syllables, cursor: Math.min(w.cursor, Math.max(0, syllables.length - 1)) });+ useSing.setState({ playing: null, at: -1 });}engine.onPlanned((m) => {@@ -254,12 +305,13 @@ engine.onPlanned((m) => {});/**- * Sing a demo song (after `ready`, e.g. audio startup, resolves; unless stopped meanwhile). The- * lyrics show the song's words while it plays; the player's own come back when it ends or stops.+ * Sing the lyrics to tune `id` (after `ready`, e.g. audio startup, resolves; unless stopped+ * meanwhile), at the chosen tempo and key; empty lyrics sing it on "la". Resolves whether it is+ * singing. `hooks` follow the run: onStart only once nothing can cancel it before it's sent.*/-export async function playDemo(name: string, body: BodyMix, ready?: () => Promise<void>): Promise<void> {- const song = DEMO_SONGS.find((s) => s.name === name);- if (!song) return;+export async function playTune(id: string, body: BodyMix, ready?: () => Promise<void>, hooks: TuneHooks = {}): Promise<boolean> {+ const tune = TUNES.find((t) => t.id === id);+ if (!tune) return false;stopSinging();const token = demoToken;await ready?.();@@ -268,28 +320,31 @@ export async function playDemo(name: string, body: BodyMix, ready?: () => Promis} catch {// letter-to-sound rules}- if (token !== demoToken) return;- const syl = lyricsToSyllables(song.lyrics);- if (!syl.length) return;- const shift = song.octave[nearestBody(body)] * 12;- const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));+ if (token !== demoToken) return false;+ const st = useSing.getState();+ // read again: the dictionary may have arrived since the words were typed+ const own = lyricsToSyllables(st.lyrics);+ const words = own.length ? own : lyricsToSyllables(la(tune));+ const { notes, from } = fitSong(tune, words, tune.octave[nearestBody(body)] * 12 + st.key);+ if (!notes.length) return false;+ const bpm = tune.bpm * st.tempo;const t0 = 0.35;- const plan = planSong(notes, { body, bpm: song.bpm, t0, vibrato: useSing.getState().vibrato });- const beat = 60 / song.bpm;+ const plan = planSong(notes, { body, bpm, t0, vibrato: st.vibrato });+ hooks.onStart?.();+ const beat = 60 / bpm;let t = t0;const times = notes.map((n): [number, number] => {const a = t;t += n.beats * beat;return [a, t];});- const id = engine.schedule({ gestures: plan.gestures, segments: plan.segments, end: plan.end });+ const planId = engine.schedule({ gestures: plan.gestures, segments: plan.segments, end: plan.end });const parent: number[] = [];notes.forEach((n, i) => parent.push(n.syl.melisma && i > 0 ? parent[i - 1] : i));const shown = parent.map((p) => written(notes[p].syl));- demoRun = { id, times, midi: notes.map((n) => n.midi), text: notes.map((n) => n.syl.text), shown, parent, end: plan.end, offset: null };- const s = useSing.getState();- ownWords ??= { lyrics: s.lyrics, cursor: s.cursor };- useSing.setState({ lyrics: song.lyrics, syllables: syl, cursor: 0, demo: song.name, demoAt: -1 });+ demoRun = { id: planId, times, midi: notes.map((n) => n.midi), text: notes.map((n) => n.syl.text), shown, parent, from: own.length ? from : from.map(() => -1), end: plan.end, offset: null, hooks };+ useSing.setState({ syllables: own, cursor: Math.min(st.cursor, Math.max(0, own.length - 1)), playing: tune.id, at: -1 });+ return true;}function stopDemo(): void {@@ -302,17 +357,23 @@ function stopDemo(): void {roll.notes = roll.notes.filter((n) => !(n.demo && n.t0 > t));for (const n of roll.notes) if (n.demo && n.t1 !== null && n.t1 > t) n.t1 = t;endDemo();+ d.hooks.onStop?.();}-/** Called every frame while Sing mode is shown: follow the demo's progress. */+/** Call every frame while Sing mode is shown: follow the tune's progress. */export function tickSinging(): void {const d = demoRun;if (!d || d.offset === null) return;const t = now() - d.offset;- if (t > d.end + 0.4) return endDemo();+ if (t > d.end + 0.4) {+ endDemo();+ d.hooks.onEnd?.();+ return;+ }let k = -1;while (k + 1 < d.times.length && d.times[k + 1][0] <= t) k++;- if (k !== useSing.getState().demoAt) useSing.setState({ demoAt: k });+ const at = k < 0 ? -1 : d.from[k];+ if (at !== useSing.getState().at) useSing.setState({ at });}/** Stop everything sung (leaving Sing mode, changing body): demo, notes and endings. */@@ -333,4 +394,4 @@ export function stopSinging(): void {keys = [];}-export { DEMO_SONGS };+export { TUNES };diff --git a/src/ui/styles.css b/src/ui/styles.cssindex 65c14d4..3e0b5d9 100644--- a/src/ui/styles.css+++ b/src/ui/styles.css@@ -2057,12 +2057,13 @@ input[type="range"]::-moz-range-thumb {}/* ---------- Sing */-/* the pitch roll only shows what was sung: a smaller share than it had, so the song's button- above it fits a 1280 x 800 window and the keys keep their room */+/* the words right under the button that sings them; the pitch roll only shows what was sung: a+ smaller share than it had, so the song's button fits a 1280 x 800 window and the keys keep+ their room */.right-sing {grid-template-columns: minmax(0, 342fr) minmax(0, 342fr);- grid-template-rows: auto minmax(min-content, 240fr) auto auto minmax(min-content, 172fr);- grid-template-areas: "act act" "roll roll" "lyrics lyrics" "spec voice" "keys keys";+ grid-template-rows: auto auto minmax(min-content, 240fr) auto minmax(min-content, 172fr);+ grid-template-areas: "act act" "lyrics lyrics" "roll roll" "spec voice" "keys keys";}.s-roll { grid-area: roll; }@@ -2084,8 +2085,10 @@ input[type="range"]::-moz-range-thumb {min-height: 0;}+/* a row per line of the song (up to four) */.lyrics textarea {- height: 30px;+ height: auto;+ min-height: 30px;resize: none;padding: 5px 10px;font-size: 13px;@@ -2166,7 +2169,7 @@ input[type="range"]::-moz-range-thumb {@media (max-width: 1100px) {.right-sing {grid-template-rows: none;- grid-template-areas: "act act" "roll roll" "lyrics lyrics" "spec voice" "keys keys";+ grid-template-areas: "act act" "lyrics lyrics" "roll roll" "spec voice" "keys keys";}.right-sing .screen-body {min-height: 190px;@@ -2182,7 +2185,11 @@ input[type="range"]::-moz-range-thumb {@media (max-width: 640px) {.right-sing {grid-template-columns: minmax(0, 1fr);- grid-template-areas: "act" "roll" "lyrics" "spec" "voice" "keys";+ grid-template-areas: "act" "lyrics" "roll" "spec" "voice" "keys";+ }+ /* 16 px: iOS zooms the page into any smaller field it focuses */+ .lyrics textarea {+ font-size: 16px;}}diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex 64a9207..1198b0f 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -42,7 +42,7 @@ const engineStub = new Proxy({ get: (t, k) => (k in t ? t[k as string] : () => {}), set: (t, k, v) => ((t[k as string] = v), true) },);mock.module("../src/audio/AudioEngine.ts", () => ({ engine: engineStub }));-const { useSing, singNoteOn, singNoteOff, playDemo, stopSinging, tickSinging } = await import("../src/ui/singing.ts");+const { useSing, singNoteOn, singNoteOff, playTune, stopSinging, tickSinging } = await import("../src/ui/singing.ts");const gesturesOf = () => voice.score();/** breath the score is giving now (strength-weighted activation of breath gestures) */const breathNow = () => {@@ -141,57 +141,95 @@ describe("Sing mode, live keys", () => {expect(hard.rms / soft.rms).toBeGreaterThan(1.6); // > 4 dB});- test("a demo still waiting for audio or the dictionary is cancelled by a stop", async () => {+ test("a tune still waiting for audio or the dictionary is cancelled by a stop", async () => {voice = new WasmVoice(FS);let scheduled = 0;const schedule = engineStub.schedule as typeof fakeEngine.schedule;engineStub.schedule = (plan: { gestures: Gesture[] }) => (scheduled++, schedule(plan));let go!: () => void;- const waiting = playDemo("Made of air", MALE, () => new Promise<void>((r) => (go = r)));+ const waiting = playTune("dreamy", MALE, () => new Promise<void>((r) => (go = r)));stopSinging(); // e.g. the mode changed while audio was startinggo();- await waiting;+ expect(await waiting).toBe(false);expect(scheduled).toBe(0);- expect(useSing.getState().demo).toBeNull();- await playDemo("Made of air", MALE, () => Promise.resolve());+ expect(useSing.getState().playing).toBeNull();+ expect(await playTune("dreamy", MALE, () => Promise.resolve())).toBe(true);expect(scheduled).toBe(1);- expect(useSing.getState().demo).toBe("Made of air");+ expect(useSing.getState().playing).toBe("dreamy");stopSinging();engineStub.schedule = schedule;});- test("a demo shows the song's words while it plays, then gives the player's own back", async () => {+ test("a tune sings the player's own words and leaves them as they are; the end is reported once", async () => {voice = new WasmVoice(FS);const sing = useSing.getState;sing().setLyrics("my own words to sing");sing().setCursor(2);- // stopped (a song chip pressed again, the mode or body changed)- await playDemo("Made of air", MALE, () => Promise.resolve());- expect(sing().demo).toBe("Made of air");- expect(sing().lyrics).not.toBe("my own words to sing");- stopSinging();+ let ended = 0;+ await playTune("joyful", MALE, () => Promise.resolve(), { onEnd: () => ended++ });+ expect(sing().playing).toBe("joyful");expect(sing().lyrics).toBe("my own words to sing");expect(sing().syllables.map((s) => s.text)).toEqual(["my", "own", "words", "to", "sing"]);expect(sing().cursor).toBe(2);- // played to the end- await playDemo("Made of air", MALE, () => Promise.resolve());+ // the syllable being sung, in the player's lyrics: the first, a little after the first beat+ planned({ type: "planned", id: 1, t0: voice.clock - 0.5, end: 0 });+ tickSinging();+ expect(sing().at).toBe(0);+ // sung to the endplanned({ type: "planned", id: 1, t0: voice.clock - 1000, end: 0 });tickSinging();- expect(sing().demo).toBeNull();- expect(sing().lyrics).toBe("my own words to sing");- expect(sing().cursor).toBe(2);- // a second song started while the first plays gives back the player's words, not the first song's- await playDemo("Made of air", MALE, () => Promise.resolve());- await playDemo("Made of air", MALE, () => Promise.resolve());+ tickSinging();+ expect(sing().playing).toBeNull();+ expect(ended).toBe(1);+ // stopped: not reported as ended+ await playTune("joyful", MALE, () => Promise.resolve(), { onEnd: () => ended++ });stopSinging();- expect(sing().lyrics).toBe("my own words to sing");- // words typed during a demo are the player's from then on- await playDemo("Made of air", MALE, () => Promise.resolve());+ expect(ended).toBe(1);+ // words typed during a tune stop it+ await playTune("joyful", MALE, () => Promise.resolve());sing().setLyrics("typed during the song");- expect(sing().demo).toBeNull();+ expect(sing().playing).toBeNull();expect(sing().lyrics).toBe("typed during the song");});+ test("a run's hooks: no start for a run stopped while starting; a stop from anywhere is reported", async () => {+ // Video's clip lives in these: it once began recording for a start that had been cancelled+ voice = new WasmVoice(FS);+ const log: string[] = [];+ const hooks = { onStart: () => log.push("start"), onEnd: () => log.push("end"), onStop: () => log.push("stop") };+ let go!: () => void;+ const waiting = playTune("joyful", MALE, () => new Promise<void>((r) => (go = r)), hooks);+ stopSinging(); // the mode or body changed while audio was starting+ go();+ expect(await waiting).toBe(false);+ expect(log).toEqual([]);+ await playTune("joyful", MALE, () => Promise.resolve(), hooks);+ expect(log).toEqual(["start"]);+ stopSinging();+ expect(log).toEqual(["start", "stop"]);+ // a start that throws (the browser can't record): nothing is sung+ let scheduled = 0;+ const schedule = engineStub.schedule as typeof fakeEngine.schedule;+ engineStub.schedule = (plan: { gestures: Gesture[] }) => (scheduled++, schedule(plan));+ const failed = await playTune("joyful", MALE, () => Promise.resolve(), { onStart: () => { throw new Error("no recorder"); } }).catch(() => "threw");+ expect(failed).toBe("threw");+ expect(scheduled).toBe(0);+ expect(useSing.getState().playing).toBeNull();+ engineStub.schedule = schedule;+ });++ test("empty lyrics sing the tune on la, highlighting nothing", async () => {+ voice = new WasmVoice(FS);+ const sing = useSing.getState;+ sing().setLyrics("");+ expect(await playTune("somber", MALE, () => Promise.resolve())).toBe(true);+ planned({ type: "planned", id: 1, t0: voice.clock - 0.5, end: 0 });+ tickSinging();+ expect(sing().at).toBe(-1);+ stopSinging();+ sing().setLyrics("Hello there");+ });+test("a quick next note drops the last one's breath-out; leaving Sing cancels a pending ending", () => {voice = new WasmVoice(FS);useSing.getState().setVibrato(0);diff --git a/tests/song-fit.test.ts b/tests/song-fit.test.tsnew file mode 100644index 0000000..fde5094--- /dev/null+++ b/tests/song-fit.test.ts@@ -0,0 +1,112 @@+/**+ * The Song page's tunes and fitting anyone's words to them: every syllable sung once and in order,+ * each phrase keeping its length in beats, and lines cut where words end.+ */+import { describe, expect, test } from "bun:test";+import { initEngine } from "./harness.ts";++await initEngine();+const { lyricsToSyllables } = await import("../src/wasm/engine.ts");+const { TUNES } = await import("../src/song/tunes.ts");+const { fitLine, fitSong, lines, phraseSize, la } = await import("../src/song/fit.ts");+type SungNote = import("../src/wasm/types.ts").SungNote;+type Syllable = import("../src/wasm/types.ts").Syllable;++const beats = (ns: { beats: number }[]) => ns.reduce((s, n) => s + n.beats, 0);+/** the syllables a fitted line sings, in order (a held vowel isn't a new one) */+const sung = (ns: SungNote[]) => ns.filter((n) => !n.syl.melisma).map((n) => n.syl.text);+const texts = (s: Syllable[]) => s.map((x) => x.text);++describe("tunes", () => {+ test("every phrase of a tune is as long as the others, and ends on a held note (room for the breath)", () => {+ for (const t of TUNES) {+ const lens = t.phrases.map((p) => beats(p.map(([, b]) => ({ beats: b }))));+ expect(new Set(lens).size).toBe(1);+ for (const p of t.phrases) expect(p[p.length - 1][1]).toBeGreaterThanOrEqual(1.5);+ }+ });+ test("ids are unique", () => {+ expect(new Set(TUNES.map((t) => t.id)).size).toBe(TUNES.length);+ });+});++describe("fitting a line to a phrase", () => {+ const phrase = TUNES.find((t) => t.id === "joyful")!.phrases[0]; // 7 notes, 8 beats+ const check = (words: string) => {+ const line = lyricsToSyllables(words);+ const { notes: ns, from } = fitLine(line, phrase);+ // each note knows the syllable it sings (a held vowel: the one it holds)+ expect(from.map((i) => line[i].nucleus.ipa)).toEqual(ns.map((n) => n.syl.nucleus.ipa));+ expect(beats(ns)).toBeCloseTo(8, 9);+ expect(sung(ns)).toEqual(texts(line.filter((s) => !s.melisma)));+ expect(ns.map((n) => n.syl.phraseEnd)).toEqual(ns.map((_, i) => i === ns.length - 1));+ return ns;+ };+ test("as many syllables as notes: one each, the tune unchanged", () => {+ const ns = check("one two three four five six sev");+ expect(ns.map((n) => [n.midi, n.beats])).toEqual(phrase);+ });+ test("more syllables: long notes split, same pitches", () => {+ const ns = check("this line has a lot more syllables than notes");+ expect(ns.length).toBe(lyricsToSyllables("this line has a lot more syllables than notes").length);+ expect(new Set(ns.map((n) => n.midi))).toEqual(new Set(phrase.map(([m]) => m)));+ });+ test("fewer syllables: vowels held across notes, the spare notes on the last syllables", () => {+ const ns = check("hello my friend");+ expect(ns.length).toBe(phrase.length);+ expect(ns[ns.length - 1].syl.melisma).toBe(true);+ expect(ns[0].syl.melisma).toBeFalsy();+ });+ test("a single word: neighbouring notes merge first, the last note keeps its pitch", () => {+ const ns = check("cat");+ expect(ns.length).toBeLessThanOrEqual(2);+ expect(ns[ns.length - 1].midi).toBe(phrase[phrase.length - 1][0]);+ });+});++describe("lyrics into lines", () => {+ test("a long line is cut where a word ends, into lines near the tune's phrase", () => {+ const syls = lyricsToSyllables("the quick brown fox jumps over the lazy dog and runs away into the dark green wood");+ const ls = lines(syls, 7);+ expect(ls.length).toBeGreaterThan(1);+ for (const l of ls) {+ expect(syls[l[l.length - 1]].wordEnd).toBe(true);+ expect(l.length).toBeLessThanOrEqual(11);+ }+ expect(ls.flat()).toEqual(syls.map((_, i) => i));+ });+ test("a word or two on its own joins the next line", () => {+ const ls = lines(lyricsToSyllables("Oh,\nI will sing this line for you"), 7);+ expect(ls.length).toBe(1);+ });+ test("only each line's last note ends a phrase", () => {+ const syls = lyricsToSyllables("one, two three four five six seven.\neight nine ten eleven twelve");+ const { notes } = fitSong(TUNES[1], syls);+ const ends = notes.filter((n) => n.syl.phraseEnd).length;+ expect(ends).toBe(lines(syls, phraseSize(TUNES[1])).length);+ expect(notes[notes.length - 1].syl.phraseEnd).toBe(true);+ });+});++describe("a whole song", () => {+ test("every tune sings its own la-la exactly, note for note", () => {+ for (const t of TUNES) {+ const { notes: ns, from } = fitSong(t, lyricsToSyllables(la(t)));+ expect(from).toEqual(ns.map((_, i) => i));+ expect(ns.map((n) => [n.midi, n.beats])).toEqual(t.phrases.flat());+ expect(ns.every((n) => !n.syl.melisma)).toBe(true);+ }+ });+ test("more lines than phrases go round the tune again, shifted by the body's octave", () => {+ const t = TUNES[1];+ const words = Array.from({ length: 6 }, () => "la ".repeat(phraseSize(t)).trim()).join("\n");+ const { notes: ns } = fitSong(t, lyricsToSyllables(words), -12);+ expect(ns.length).toBe(6 * phraseSize(t));+ expect(ns[4 * phraseSize(t)].midi).toBe(t.phrases[0][0][0] - 12);+ });+ test("a user's own held vowel (-) stays a held vowel", () => {+ const { notes: ns } = fitSong(TUNES[1], lyricsToSyllables("oh - my darling one two three"));+ expect(ns[1].syl.melisma).toBe(true);+ expect(ns[1].syl.nucleus.ipa).toBe(ns[0].syl.nucleus.ipa);+ });+});diff --git a/tools/e2e.ts b/tools/e2e.tsindex fc67c8c..5ea2616 100644--- a/tools/e2e.ts+++ b/tools/e2e.ts@@ -169,12 +169,12 @@ async function run(viewport: { width: number; height: number }, tag: string) {if (!(after < 1e-3)) errors.push(`[${tag}] voice still sounding after the sung notes: ${after}`);if (sylBefore === sylAfter) errors.push(`[${tag}] the syllable cursor did not move (${sylBefore})`);// a menu isn't an instrument: a letter typed in it picks an entry, it doesn't play a note- await page.getByRole("combobox", { name: "Song" }).focus();+ await page.getByRole("combobox", { name: "Tune" }).focus();await page.keyboard.down("d");const menuNotes = await page.locator(".keys .key.down").count();await page.keyboard.up("d");- if (menuNotes) errors.push(`[${tag}] a key typed in the song menu played a note`);- await page.getByRole("combobox", { name: "Song" }).selectOption("Made of air");+ if (menuNotes) errors.push(`[${tag}] a key typed in the tune menu played a note`);+ await page.getByRole("combobox", { name: "Tune" }).selectOption({ label: "Dreamy" });await page.getByRole("button", { name: /^Sing$/ }).click();await page.waitForTimeout(2200);const demoRms = await rms();@@ -183,9 +183,9 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.getByRole("button", { name: /^Stop$/ }).click();await page.waitForTimeout(700);const demoStopped = await rms();- logs.push(`[${tag}] sing demo: rms ${demoRms.toFixed(4)} on "${demoNow}", after stop ${demoStopped.toFixed(4)}`);- if (!(demoRms > 0.01) || !demoNow) errors.push(`[${tag}] demo song not singing (rms ${demoRms}, syllable ${demoNow})`);- if (!(demoStopped < 1e-3)) errors.push(`[${tag}] demo still sounding after stop: ${demoStopped}`);+ logs.push(`[${tag}] sing a tune: rms ${demoRms.toFixed(4)} on "${demoNow}", after stop ${demoStopped.toFixed(4)}`);+ if (!(demoRms > 0.01) || !demoNow) errors.push(`[${tag}] the tune is not singing the lyrics (rms ${demoRms}, syllable ${demoNow})`);+ if (!(demoStopped < 1e-3)) errors.push(`[${tag}] the tune still sounding after stop: ${demoStopped}`);// bestiary: every creature, its first call, a key in held-voice mode, and the sustain toggleawait page.getByRole("radio", { name: "Bestiary" }).click();await page.waitForTimeout(300);@@ -347,6 +347,209 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.close();}+// Sing's Record video: sings the lyrics to the tune again into a clip to save; the face screen leaves out+// its readouts while it records+{+ const page = await browser.newPage({ viewport: { width: 390, height: 844 }, acceptDownloads: true });+ page.on("console", (m) => m.type() === "error" && errors.push(`[video] ${m.text()}`));+ page.on("pageerror", (e) => errors.push(`[video] pageerror: ${e.message}`));+ await page.goto(url, { waitUntil: "networkidle" });+ await page.locator(".lyrics textarea").fill("one two three");+ await page.getByRole("combobox", { name: "Tune" }).selectOption({ label: "Playful" });+ await page.getByRole("button", { name: /^Record video$/ }).click();+ await page.getByRole("button", { name: /^Cancel$/ }).waitFor({ timeout: 10000 });+ await page.waitForTimeout(800);+ await page.screenshot({ path: `${outDir}/video-recording.png` });+ const save = page.getByRole("link", { name: /^Save$/ });+ const saved = await save.waitFor({ timeout: 20000 }).then(() => true, () => false);+ if (!saved) errors.push("[video] Record video never offered a clip to save");+ else {+ const [dl] = await Promise.all([page.waitForEvent("download"), save.click()]);+ const size = (await (await dl.createReadStream()).toArray()).reduce((n, b: Buffer) => n + b.length, 0);+ logs.push(`[video] clip ${dl.suggestedFilename()}: ${size} bytes`);+ if (size < 10000) errors.push(`[video] the clip is nearly empty (${size} bytes)`);+ }+ // the words and the tune come back on reload+ await page.reload({ waitUntil: "networkidle" });+ const words = await page.locator(".lyrics textarea").inputValue();+ const tune = await page.getByRole("combobox", { name: "Tune" }).inputValue();+ if (words !== "one two three" || tune !== "playful") errors.push(`[video] the song didn't come back on reload: "${words}" to ${tune}`);+ await page.close();+}++// two taps on Record video while the audio is still starting make one clip: the first start gives way (it+// used to leave a second recorder running that Cancel couldn't reach)+{+ const page = await browser.newPage({ viewport: { width: 390, height: 844 } });+ page.on("pageerror", (e) => errors.push(`[video-twice] pageerror: ${e.message}`));+ await page.addInitScript(() => {+ const Rec = window.MediaRecorder;+ const w = window as unknown as { __recorders: number };+ w.__recorders = 0;+ window.MediaRecorder = class extends Rec {+ constructor(...a: ConstructorParameters<typeof Rec>) {+ super(...a);+ w.__recorders++;+ }+ };+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.locator(".lyrics textarea").fill("one two");+ // both taps land before the first has started the audio (a second Playwright click would wait,+ // and then find Cancel)+ await page.evaluate(() => {+ const b = [...document.querySelectorAll<HTMLButtonElement>(".action-bar button")].find((x) => x.textContent === "Record video")!;+ b.click();+ b.click();+ });+ await page.getByRole("link", { name: /^Save$/ }).waitFor({ timeout: 20000 }).catch(() => errors.push("[video-twice] no clip after two taps"));+ const recorders = await page.evaluate(() => (window as unknown as { __recorders: number }).__recorders);+ logs.push(`[video-twice] two taps on Record video: ${recorders} recorder(s)`);+ if (recorders !== 1) errors.push(`[video-twice] two taps on Record video made ${recorders} recorders (want 1)`);+ await page.close();+}++// Record video pressed while a song is singing: the clip starts once that song has died away (it+// used to open on the stopped song's tail)+{+ const page = await browser.newPage({ viewport: { width: 390, height: 844 } });+ page.on("pageerror", (e) => errors.push(`[video-tail] pageerror: ${e.message}`));+ await page.addInitScript(() => {+ const w = window as unknown as { __startLevel: number | null; __chimeraEngine?: { level(): number } };+ w.__startLevel = null;+ const start = MediaRecorder.prototype.start;+ MediaRecorder.prototype.start = function (this: MediaRecorder, ...a: [number?]) {+ w.__startLevel = w.__chimeraEngine?.level() ?? null;+ return start.apply(this, a);+ };+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.locator(".lyrics textarea").fill("one two three four five six seven eight");+ await page.getByRole("button", { name: /^Sing$/ }).click();+ await page.waitForTimeout(2500);+ const singing = await page.evaluate(() => (window as unknown as { __chimeraEngine: { level(): number } }).__chimeraEngine.level());+ await page.getByRole("button", { name: /^Record video$/ }).click();+ await page.getByRole("button", { name: /^Cancel$/ }).waitFor({ timeout: 10000 });+ const atStart = await page.evaluate(() => (window as unknown as { __startLevel: number | null }).__startLevel);+ logs.push(`[video-tail] output rms while singing ${singing.toFixed(4)}, as the clip starts ${atStart?.toFixed(4)}`);+ if (singing < 0.005) errors.push(`[video-tail] the song wasn't sounding when Record video was pressed (rms ${singing})`);+ if (atStart === null || atStart >= 0.003) errors.push(`[video-tail] the clip started on the last song's tail (rms ${atStart})`);+ await page.close();+}++// a recorder that fails partway (an encoder or resource failure): it lets go of the capture and the+// face's measurements come back then, no clip is offered, and nothing throws unhandled (the clip used+// to wait for the song's end, then reject, leaving its capture track running)+{+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });+ page.on("pageerror", (e) => errors.push(`[video-breaks] pageerror: ${e.message}`));+ await page.addInitScript(() => {+ const w = window as unknown as { __unhandled: number; __tracks: MediaStreamTrack[]; __texts: string[] };+ w.__unhandled = 0;+ w.__tracks = [];+ w.__texts = [];+ window.addEventListener("unhandledrejection", () => w.__unhandled++);+ const start = MediaRecorder.prototype.start;+ MediaRecorder.prototype.start = function (this: MediaRecorder, ...a: [number?]) {+ w.__tracks.push(...this.stream.getVideoTracks());+ start.apply(this, a);+ setTimeout(() => {+ this.dispatchEvent(new Event("error"));+ if (this.state !== "inactive") this.stop();+ }, 800);+ };+ const fill = CanvasRenderingContext2D.prototype.fillText;+ CanvasRenderingContext2D.prototype.fillText = function (this: CanvasRenderingContext2D, t: string, ...a: [number, number]) {+ if (w.__texts.length < 5000) w.__texts.push(t);+ return fill.call(this, t, ...a);+ };+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.locator(".lyrics textarea").fill("one two three four five six seven eight nine ten");+ await page.getByRole("button", { name: /^Record video$/ }).click();+ await page.getByRole("button", { name: /^Cancel$/ }).waitFor({ timeout: 10000 });+ await page.waitForTimeout(1500); // the recorder has failed; the song is still singing+ await page.evaluate(() => ((window as unknown as { __texts: string[] }).__texts = []));+ await page.waitForTimeout(500);+ const mid = await page.evaluate(() => {+ const w = window as unknown as { __tracks: MediaStreamTrack[]; __texts: string[] };+ return { live: w.__tracks.filter((t) => t.readyState === "live").length, readouts: w.__texts.some((t) => /^RING O/.test(t)) };+ });+ await page.getByRole("button", { name: /^Record video$/ }).waitFor({ timeout: 30000 });+ await page.waitForTimeout(500);+ const save = await page.getByRole("link", { name: /^Save$/ }).count();+ const unhandled = await page.evaluate(() => (window as unknown as { __unhandled: number }).__unhandled);+ logs.push(`[video-breaks] recorder failed mid-song: capture tracks live ${mid.live}, readouts back ${mid.readouts}; after the song Save ${save}, unhandled rejections ${unhandled}`);+ if (mid.live) errors.push(`[video-breaks] the capture kept running after the recorder failed (${mid.live} live track(s))`);+ if (!mid.readouts) errors.push("[video-breaks] the face kept hiding its measurements after the recorder failed");+ if (save) errors.push("[video-breaks] a failed recording was offered to save");+ if (unhandled) errors.push(`[video-breaks] ${unhandled} unhandled rejection(s)`);+ await page.close();+}++// switching 2D/3D while recording: the clip follows the face that's showing (it kept copying the+// replaced canvas, so the video froze at the switch while the sound went on)+{+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });+ page.on("pageerror", (e) => errors.push(`[video-3d] pageerror: ${e.message}`));+ await page.addInitScript(() => {+ const w = window as unknown as { __draws: boolean[] };+ w.__draws = [];+ const draw = CanvasRenderingContext2D.prototype.drawImage as (...a: unknown[]) => void;+ CanvasRenderingContext2D.prototype.drawImage = function (this: CanvasRenderingContext2D, ...a: unknown[]) {+ // the clip's frame is 720x1280: note whether what it copies is still on the page+ if (this.canvas.width === 720 && this.canvas.height === 1280 && a[0] instanceof HTMLCanvasElement) w.__draws.push(a[0].isConnected);+ return draw.apply(this, a);+ } as typeof CanvasRenderingContext2D.prototype.drawImage;+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.locator(".lyrics textarea").fill("one two three four five six seven eight nine ten");+ await page.getByRole("button", { name: /^Record video$/ }).click();+ await page.getByRole("button", { name: /^Cancel$/ }).waitFor({ timeout: 10000 });+ await page.waitForTimeout(500);+ await page.getByRole("checkbox", { name: "3D" }).check();+ await page.waitForTimeout(1000);+ await page.evaluate(() => ((window as unknown as { __draws: boolean[] }).__draws = []));+ await page.waitForTimeout(500);+ const draws = await page.evaluate(() => (window as unknown as { __draws: boolean[] }).__draws);+ const detached = draws.filter((c) => !c).length;+ logs.push(`[video-3d] after switching to 3D mid-clip: ${draws.length} frames, ${detached} from a canvas no longer on the page`);+ if (!draws.length) errors.push("[video-3d] the clip drew no frames after switching to 3D");+ if (detached) errors.push(`[video-3d] the clip kept copying the replaced 2D canvas (${detached} of ${draws.length} frames)`);+ await page.getByRole("button", { name: /^Cancel$/ }).click();+ await page.close();+}++// a recorder that fails to start (a type the browser claims but can't record): no clip, the Sing+// button comes back, and the face shows its readouts again (the clean view used to stay on)+{+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });+ page.on("pageerror", (e) => errors.push(`[video-fails] pageerror: ${e.message}`));+ await page.addInitScript(() => {+ MediaRecorder.prototype.start = () => {+ throw new Error("start refused by the test");+ };+ const w = window as unknown as { __texts: string[] };+ w.__texts = [];+ const fill = CanvasRenderingContext2D.prototype.fillText;+ CanvasRenderingContext2D.prototype.fillText = function (this: CanvasRenderingContext2D, t: string, ...a: [number, number]) {+ if (w.__texts.length < 5000) w.__texts.push(t);+ return fill.call(this, t, ...a);+ };+ });+ await page.goto(url, { waitUntil: "networkidle" });+ await page.getByRole("button", { name: /^Record video$/ }).click();+ await page.waitForTimeout(2500);+ await page.evaluate(() => ((window as unknown as { __texts: string[] }).__texts = []));+ await page.waitForTimeout(500);+ const readouts = await page.evaluate(() => (window as unknown as { __texts: string[] }).__texts.some((t) => /^RING O/.test(t)));+ const sing = await page.getByRole("button", { name: /^(Sing|Stop)$/ }).count();+ logs.push(`[video-fails] after a recorder that won't start: readouts ${readouts}, Sing button ${sing}`);+ if (!readouts) errors.push("[video-fails] the face kept hiding its readouts after a recording failed to start");+ if (!sing) errors.push("[video-fails] the Sing button didn't come back after a recording failed to start");+ await page.close();+}+/*** Play before any audio (upstream issue 89): grabbing the tongue starts the audio and breathes, and* the engine keeps the tongue in the mouth. Since 704ed2c took away the start overlay over the face,@@ -396,6 +599,6 @@ await run({ width: 1440, height: 980 }, "desktop");await run({ width: 390, height: 844 }, "mobile");await browser.close();console.log("console errors:", errors.length ? "\n" + errors.join("\n") : "none");-console.log(logs.filter((l) => /load|rate|warn|transcription|example|creature|held|back to|beatbox|silence|sing|octave|retry|tongue/i.test(l)).slice(0, 52).join("\n"));+console.log(logs.filter((l) => /load|rate|warn|transcription|example|creature|held|back to|beatbox|silence|sing|octave|retry|tongue|song|video/i.test(l)).slice(0, 52).join("\n"));// a run that collected errors fails, so CI and agents can't read it as a passif (errors.length) process.exit(1);diff --git a/tools/layout-lint.ts b/tools/layout-lint.tsindex 2d6d821..e2fec87 100644--- a/tools/layout-lint.ts+++ b/tools/layout-lint.ts@@ -1,8 +1,9 @@/*** 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 the duet page (`?show=`, with a short- * duet it renders first), and fails on mistakes screenshot reviews kept missing:+ * every creature, the 3D face, a phrase being spoken, Sing's tune and a recorded clip) 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)@@ -345,6 +346,23 @@ async function main() {await check("play (running), 3D", 2500);await page.locator(".view-toggles .toggle", { hasText: "3D" }).click();}+ if (m === "sing") {+ // a tune singing the lyrics, then a recorded clip offered to save+ await page.locator(".lyrics textarea").fill("a line of words long enough to keep on singing\nand a second line to be sure");+ await page.getByRole("button", { name: /^Sing$/ }).click();+ await check("sing (running), a tune", 1500);+ // a slow machine may have sung it to the end meanwhile+ const stop = page.getByRole("button", { name: /^Stop$/ });+ if (await stop.count()) await stop.click();+ await page.locator(".lyrics textarea").fill("one two");+ const video = page.getByRole("button", { name: /^Video$/ });+ if (await video.count()) {+ await video.click();+ // a whole song, recorded in real time on a CPU-drawn WebGL: slow when the machine is busy+ await page.getByRole("link", { name: /^Save$/ }).waitFor({ timeout: 90000 });+ await check("sing (running), a clip to save");+ }+ }if (m === "speak") {// the gestural score with a phrase in it, mid-utteranceawait page.getByRole("button", { name: /^Speak$/ }).click();