Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
18237c4817 soundscape-grammar: repoint Mimir harvest link to Ratatoskr main 39c99240 (#59) 2026-11-14 08:11:36 +00:00
966b34891d soundscape-grammar 4.1: harvest repointed to post-#160 (#58) 2026-11-14 01:57:58 +00:00
e95a3a0943 soundscape-grammar 4.1: mark unsourced Mimir claims (#57) 2026-11-14 01:52:41 +00:00
9913f76c00 soundscape-grammar: section 2 against projection v2's five fields; human subset still proposed (#56)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 00:41:37 +00:00
15e5a104ae soundscape-grammar: reconcile section 4 with the Mimir harvest (Kiko-corrected) (#55)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 00:39:00 +00:00
99539cb801 PatchScript: TryIpaDescriptor doc comment back on its method (PR #48 Soul Low) (#54)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 00:36:46 +00:00
a9e2ce5841 voice-source-1: glottal pulse and noise-colour listening kit, unheard (#53)
Merged as head maintainer after Soul pass 1 (aqua-body:verdict:cut-voice-source-kit.s1, 4 Medium 4 Low, fixed in a29cad3..e343d2b). Unheard.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 00:36:35 +00:00
ca6af1d678 Tract: coarticulation fixes for the tract-weak-spots-1 listening verdict (#52)
Merged as head maintainer after Soul passes 2 and 3 (aqua-body:verdict:cut-tract-coarticulation-pr52.s2, ...fix2.s3). Unheard: every clip is a measurement, not a listening.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:54:17 +00:00
71cf9caeb6 aqua-listen: autosave keyed on kit id and clip ids, not the content hash (#51) 2026-11-13 12:17:32 +00:00
92d4282546 Tract stops /t/ /k/ /d/ /l/, burst at the closure site, listen kits with clip images (#48) 2026-11-13 07:14:34 +00:00
a4faad999f aqua-listen: export panel with copy, textarea, share (Android Chrome fix) (#50) 2026-11-12 23:44:13 +00:00
6e92e47115 Sample-rate pass-through, #18/#19 and #47 Lows (#49)
Shipped by Aqua (Self, steward) after Soul PASS-WITH-FINDINGS (cut-samplerate-passthrough.s1 and siblings).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 18:42:44 +00:00
af0e44f9b6 Tract: burst gain no longer leaks past its plosive; 14-clip listening kit (#47)
Shipped by Aqua (Self) after Soul PASS (aqua-body:follow_up:soul-pr47-verdict-20261112; two Low findings). UNHEARD.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:49:16 +00:00
c0e6b980fe Merge pull request 'Dings migration step 5a: neutral fallback id tied to the catalog; steps 2, 3, 5b recorded STOPPED' (#46) from aqua/dings-migration-step5a into main 2026-11-12 11:02:38 +00:00
Aqua
7458fbd93c Dings migration: step 5a ties the neutral fallback id to the catalog mirror; steps 2, 3, 5b recorded as STOPPED with their unblockers
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:00:00 +00:00
e188424244 Merge pull request 'Dings: one play validation gate, Host enforces; bridge check deprecated (step 4)' (#45) from aqua/dings-migration-step4 into main 2026-11-12 10:57:20 +00:00
Aqua
3bd2698d59 Dings step 4 fixes: exact-shape Host gate source check; refresh doc citations and double-validation text
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:53:44 +00:00
1394b49ad1 Merge pull request 'aqua-trial: isolate the noise-slider kill; LF-normalised DSP hash' (#44) from aqua/trial-noise-knob-crlf into main 2026-11-12 10:48:36 +00:00
Aqua
d427f046b5 aqua-trial: isolate the noise-slider kill; LF-normalise the DSP hash on both sides
- test.mjs: a failing test no longer aborts the run, so a mutation shows every test that kills it.
- New test: the noise slider is live (noise 20 vs 100 differ, rasp-band ratio 0.2 at rpm 4800) while noise 100 stays identical to thruster.dsp.
- logic.js dspHash (CRLF folded to LF, then sha-256) is the one normalisation; the page export and analyze.mjs both use it. LF text hashes as before, so old exports stay valid.
- Tests: CRLF == LF hash, LF == plain sha-256, analyze CLI raises no foreign-DSP warning for a CRLF checkout.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:46:57 +00:00
Aqua
e3d1a7eeba Dings: one play validation gate (DingCatalog.PlayRejection), Host enforces; bridge check deprecated (migration step 4)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:46:34 +00:00
2e28f5699e Merge pull request 'Dings: DingCatalog.Identity owns patch identity derivation (step 1) + migration plan' (#42) from aqua/dingcatalog-owner-step1 into main 2026-11-12 10:41:57 +00:00
Aqua
ea500d1327 Dings authority doc: post-step-1 state, re-verified citations, one migration list; caller source-check test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:40:04 +00:00
ae453a4e3d Merge pull request 'docs: cause of the dx7-algorithm-32 -79.5 dB native-vs-wasm diff' (#43) from aqua/dx7-32-diff-cause into main 2026-11-12 10:38:01 +00:00
Aqua
fd604b8ebb dx7-32 cause note: 1176 Hz rounds the same, name the lag figures' unit (Soul nits)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:37:59 +00:00
Aqua
f846dcbeae docs: cause of the dx7-algorithm-32 -79.5 dB native-vs-wasm diff (phasor increment rounding + si.smoo text)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:33:54 +00:00
Aqua
0f0de0dd8e Dings: DingCatalog.Identity owns PatchId/FaustName/revision derivation (step 1); record owner as ruled, migration plan
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:33:48 +00:00
965dfe8576 Merge pull request 'aqua-trial / native-diff: DSP hash in exports, noise% fix, knob + limit tests' (#41) from aqua/trial-v5-review-gaps into main 2026-11-12 10:25:56 +00:00
Aqua
bae610237d native-diff test: centroid edge in literal numbers (0.9 % passes, 1.1 % trips); doc says LIMITS live in native-compare.js
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:23:17 +00:00
Aqua
a877001616 native-diff: LIMITS and the per-source comparison move to native-compare.js; native-diff.test.mjs trips each limit with a known perturbation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:12:37 +00:00
0f6ad2bb1d Merge pull request 'docs: Dings patch identity authority map' (#40) from aqua/dings-authority-map into main 2026-11-12 09:55:17 +00:00
Aqua
f944c05278 docs: cite SampleAsync compile call correctly
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:54:16 +00:00
Aqua
fb881a971a docs: correct Dings authority map citations and store claims
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:54:08 +00:00
Aqua
8c61b76e16 aqua-trial: exports carry the DSP sha-256; analyze rejects hashless exports and keeps v5 out of the noise% context; tests pin the noise knob and mix identity at rpm 300-4800
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:53:30 +00:00
Aqua
6159cfcea9 docs: Dings patch identity authority map and host pipe protocol
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:50:55 +00:00
bbd800a11c Merge pull request 'Docs: soundscape grammar follows creature-projection-v2 (lands 72 lines main lacks)' (#39) from aqua/docs-soundscape-grammar-land into main 2026-11-12 09:49:38 +00:00
Aqua
196497578a Docs: neutral also strips size; unknown human kind clamps to Idle
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:48:12 +00:00
Aqua
69028cdbf2 Docs: soundscape grammar human kind subset, neutral strips kind/energy, fix A3
Nothing here was rendered or listened to.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:48:12 +00:00
Aqua
6f6f8002a4 Docs: soundscape grammar follows creature-projection-v2 (O1 no orbit/voice, estate, size)
Neutral participant draws and sounds nothing (no neutral pose). Add estate
(human|mind|persona): humans coarse only, Minds/Personas the 7x4 set. Three
size buckets with a separate neutral flag; scales not fixed. Cites
heimdall-body:follow_up:ratatoskr-creature-projection-v2 (still unreadable
from aqua; reconcile owed). Docs only, nothing listened to.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:48:12 +00:00
c0fe4eef33 PackageBoundaryTests: fix pack hang; trigger+repeat composition tests (#38) 2026-11-11 12:07:07 +00:00
e9de895c39 Lowering: patch repeat restarts pitch and arpeggio, not the envelope; README store-kind rollback note (#37) 2026-11-11 09:27:29 +00:00
5c49f2ae86 Pin CultLib abd1a92e; [CultRole] audit; ElementId on every list element type (#35) 2026-11-11 08:31:22 +00:00
0b73d5d608 sfxr explosion + abstract golf: patch repeat no longer cuts the envelope; waivers removed (#36) 2026-11-11 07:30:59 +00:00
9f24e0b42b aqua-feel sync: --shape ramp for slow-swell visuals (measures, never gives a verdict) (#34) 2026-11-11 06:24:43 +00:00
84aa12d36d aqua-feel sync: read a browser capture's frame rate and stalls from its frame times (#33) 2026-11-11 02:59:52 +00:00
47dfc540f6 aqua-feel sync: audio-visual onset lag against perceptual windows (#32) 2026-11-10 23:42:58 +00:00
3d9a245717 Merge pull request 'Pages: no horizontal overflow at 360px; trial hint names the play-both rule' (#31) from aqua/browser-verify-layout into main 2026-11-10 22:12:36 +00:00
140 changed files with 5669 additions and 399 deletions

View file

@ -2,8 +2,8 @@
<PropertyGroup>
<CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot>
<!-- CultLib 2.0.0: tag cultlib-unity-v2.0.0. -->
<CultLibRevision>42dce3611a81adc5c5fac54cadbaa5637d6022d3</CultLibRevision>
<!-- CultLib abd1a92e (#91; floor 7760219b for [CultIndex] uniqueness and [CultElementId]). -->
<CultLibRevision>abd1a92eb24e1af3fc7cdd1bf98a88dbdebc2938</CultLibRevision>
<GitExecutable Condition="'$(GitExecutable)' == '' and Exists('C:\Program Files\Git\cmd\git.exe')">C:\Program Files\Git\cmd\git.exe</GitExecutable>
<GitExecutable Condition="'$(GitExecutable)' == ''">git</GitExecutable>
</PropertyGroup>

View file

@ -156,11 +156,18 @@ handoff state lives in [`state/spine.yaml`](state/spine.yaml).
## Building against CultLib
Builds are pinned to CultLib 2.0.0 (tag `cultlib-unity-v2.0.0`, revision `42dce3611a81adc5c5fac54cadbaa5637d6022d3`); the build fails if the CultLib checkout differs or is dirty. Create a pinned worktree and point the build at it:
Builds are pinned to CultLib revision `abd1a92eb24e1af3fc7cdd1bf98a88dbdebc2938` (#91); the build fails if the CultLib checkout differs or is dirty. Create a pinned worktree and point the build at it:
```powershell
git -C <CultLib> worktree add --detach <path> cultlib-unity-v2.0.0
git -C <CultLib> worktree add --detach <path> abd1a92eb24e1af3fc7cdd1bf98a88dbdebc2938
dotnet build -p:CultLibRoot=<path> # or set CULTLIB_ROOT=<path>
```
Without an override the sibling `..\CultLib` checkout is used and must itself be at that tag.
Without an override the sibling `..\CultLib` checkout is used and must itself be at that revision.
**Stores are one-way, and rolling back can lose data.** Since the pin move (#35) list elements carry ids, and a store holding any element id is stamped with a newer header. What an older build does with it depends on the store kind:
- **Single-file stores** (header v3 with ids): the patch catalog (`patches/aquasynth-patch-cultcache.cc`), the speech training store and the daemon store. Pins before `cultlib-unity-v2.0.0` / `caching-unity-v2.0.0`, including NuGet `cultlib-v1.0.32`, read these without complaint, silently drop the ids, and can rewrite elements without them. Only v2.0.0 and later refuse by name.
- **Directory stores** (header v5 with ids): the IPA trial results store (`ipa-trial-results.cc`, `UseDirectoryStore`). These are refused by name from `cultlib-unity-v1.0.57` / `caching-unity-v1.2.0`.
So: take a copy of any store before the upgrade and restore from it if you roll back, never write with the new pin and then read with an old one, and upgrade every reader before any writer. Stores written before the move still open; ids are minted on load.

View file

@ -0,0 +1,357 @@
# Dings patch identity: authority map
**Status (2026-11-12).** Done: step 1 (identity from the catalog, `2e28f56`), step 4 (one validation gate, `e188424`), step 5a (neutral fallback id tied to the catalog mirror, this change). Stopped, with the unblock for each in the Migration plan: step 2 (needs the MCP caller-identity fact and a listening), step 3 (needs a ruling that breaks the byte-identity rule), step 5b (needs a generated file, an owner's decision on drifted values and an ear check).
Serves follow-up `aqua-body:follow_up:aquasynth-dings-authority-map`. Claims are from
source at `c0fe4ee` (origin/main). Nothing was built or run; the one place behaviour is
inferred rather than read is marked. Paths are repo-relative; `Host` =
`tools/AquaSynthDingsHost`, `Mcp` = `tools/AquaSynthDingsMcp`.
Companion to `docs/research/dings-playback-and-ogg-export.md`, which describes the
playback path and an export sketch. This note asks a narrower question: in the Dings
path, what decides which sound "this patch" is, and how many places decide it.
## What I counted
The follow-up says four owners. The source supports four places that *decide* a
voice's identity, plus one place that names the same thing a second time without
deciding, and one generated mirror:
| # | Owner | Decides | Section |
|---|---|---|---|
| 1 | `DingCatalog` | the instrument id and the script that defines its sound | A |
| 2 | Host and daemon derivation | the daemon `patchId`, `faustName`, `revision`, session id and store file names | B |
| 3 | MCP `AgentInstrumentRegistry` | which instrument an agent session gets | C |
| 4 | `tools/dings-voices` | which voice a sender (agent localpart) gets, in a separate synth | D |
| - | Earcon Workshop `IDENTITIES` | reuses catalog instrument ids with its own parameters | E |
| - | `tools/aqua-feel/lowered-dings` | checked-in copy of #1, guarded by a test | E |
The follow-up does not list its four, so this grouping is my reading. Someone who
counted differently (for example splitting the daemon's session id from the store file
name, or counting Earcon Workshop as a fifth) would get a different number from the same
code. The grouping above follows who writes the key.
## A. `DingCatalog` instrument id and script
- Where: `src/AquaSynth.Dings/DingCatalog.cs:39-45` (four instruments), built by the
private `Instrument(...)` at `:56-57`, which writes the `Script` string (an AquaSynth patch script, `param path=...; voice wave=...`, that `FaustEmitter.EmitScript` lowers to Faust; not Faust source) and
fixes `RootFrequency = 261.6256f` for all four.
- Keys on: the instrument `Id` string (`warm-bell`, `glass-chime`, `soft-triangle`,
`muted-pluck`), case-insensitive dictionary (`:35`). Events are a separate keyed
dictionary (`:16-27`, nine ids) and are not voice identity.
- Lifetime: compiled in. Changing an entry means a new build of every consumer.
- Writer: whoever edits the file. `ValidateCuration` (`:47-64`) is the only gate.
- Readers: `Host/DingsPlaybackHost.cs:66-68` (via `DingCatalog.PlayRejection`, `DingCatalog.cs:17-24`), `Mcp/DingService.cs:12-13`,
`Mcp/AgentInstrumentRegistry.cs:11`, `Mcp/DingTools.cs:28,31,49`,
`tools/AquaLower/Program.cs:17`, and the tests `DingCatalogTests`.
- Content hash: none. The id is a label; the script is the content. Nothing here says
"this script, at this version".
## B. Host and daemon derivation of the patch
The Host does not pass the catalog id through. It sends the daemon identity fields
derived from it by `DingCatalog.Identity` (`DingCatalog.cs:12-14`, added in step 1; before
it, at `965dfe8` (origin/main before this change), `AquaDaemonClient.cs:20` composed the strings inline), and the daemon
builds more keys from them.
- `Host/AquaDaemonClient.cs:20-21` per note: `var identity = DingCatalog.Identity(instrument)`
gives `patchId = "dings." + id`, `faustName = "dings_" + id with - as _`, `revision = 1`
(a literal inside `Identity`); the same envelope sets `durationSeconds = 1.5f` and
`controls["/ding/frequency"]`.
- `src/AquaSynth.Faust/NativeFaustRuntime.cs:596-599`: the compile key is SHA-256 of
`"{revision}\n{faustName}\n{script}"`. `patchId` is not in it. So two ids with the same
name and script share a compile key; one id with an edited script gets a new key even
though `revision` stays 1.
- `src/AquaSynth.Faust/AquaSynthDaemonService.cs:1136`: session id =
`StoreFileName.From(patchId) + "-" + compileKey[..12]`. A recompile with the same
session id disposes the old session (`:366-376`).
- `src/AquaSynth.Core/StoreFileName.cs:26-54`: the mapping from any id to a file name
(ASCII letters, digits, `-`, `_`, `.` pass unchanged unless the id has an uppercase letter, a device stem, a trailing dot, is over 100 characters or already ends in a hash shape; anything else gets a 16-hex SHA-256 suffix, `StoreFileName.cs:37,59-67`).
`dings.warm-bell` is a fixed point (pinned by `StoreFileNameTests`).
- Keyed by patch: the session document. `WriteReceiptAsync("sessions", sessionId, session)`
(`:407`) runs on every compile, and `SampleAsync` compiles on every note
(`:622-635`), so the store holds `sessions/<StoreFileName(sessionId)>.cc` for each
distinct `(patchId, compile key)`, rewritten on each note. This is the one store
artifact addressable by instrument. `NativeFaustRuntime.cs:516,628-636` would also write
`<StoreFileName(patchId)>.dsp`, but only when `options.DspSourceDirectory` is set; the
daemon builds its native options from sample rate and render limits only
(`AquaSynthDaemonService.cs:330-334`) and nothing else in `src` or `tools` sets it, so
for the Dings host it is off. (Read from source, not observed.)
- Not keyed by patch: render output and the render and compile receipts. Samples are
`<store>/samples/<StoreFileName(commandId + "-render")>.wav` (`:664-667`), where
`commandId` is a fresh `ding-<guid>` per note (`AquaDaemonClient.cs:19`). Receipts go
through `WriteReceiptAsync` (`:922-937`) under command-derived ids, with the patch id
only in the body. The store therefore keeps one WAV per note played, none addressable
by instrument. Whether the store ever gets cleaned I did not find.
- Faust name, three forms: the Host sends `dings_<id with - as _>`; the daemon applies
`SafeFaustName` (`NativeFaustRuntime.cs:602-607`, called at
`AquaSynthDaemonService.cs:911` and `NativeFaustRuntime.cs:513`) so the manifest and
emitted source carry the rewritten name, while the compile key (`:596-599`) hashes the
raw `identity.FaustName`. Two raw names that sanitise alike compile alike but key
differently.
- The `dings_<id>` rule now lives once, in `DingCatalog.Identity`. `AquaDaemonClient.cs:20`
and `tools/AquaLower/Program.cs:19` call it; `LoweredDingsFedToTheFeelMeterMatchTheCatalog`
compares against a literal per instrument, and `CallersDeriveIdentityOnlyThroughTheCatalog`
fails if either caller stops calling it. (History: at `965dfe8` the rule was written three
times, in those two files and in the test at `DingCatalogTests.cs:45`.)
- Writer: the Host (fields) and the daemon (session id, file names). Readers: the
daemon's compile/render path and receipts; no Dings code reads the patch id back.
- `Host/AquaDaemonClient.cs:24-29` returns the WAV path from the receipt. The Host
never asks the daemon which patch rendered it.
## C. MCP `AgentInstrumentRegistry`
- Where: `Mcp/AgentInstrumentRegistry.cs:10` (dictionary), `:13-17` `GetOrAssign`,
`:19-29` `Claim`, `:31-36` `AssignDeterministically`.
- Keys on: `agentSessionId`, which is `server.SessionId ?? "stdio:" + ProcessId`
(`Mcp/DingTools.cs:45`; that `SessionId` is null under stdio is inferred from the `??` fallback, not read from the SDK). That is the MCP transport session, not the agent. In HTTP
mode (`Mcp/Program.cs:34-54`, `Stateless = false`) it lives as long as that MCP
session; in stdio mode it is the bridge process id.
- Value: an instrument id string. Unclaimed sessions get
`SHA256(sessionId)[0..4] % sortedInstrumentIds.Length`. `Claim` overwrites silently,
and there is no uniqueness check, so two sessions can hold the same instrument.
- Lifetime: in-process, a `ConcurrentDictionary`. Lost on bridge restart. A restarted
or reconnected session gets a different session id, hence generally a different
hashed instrument unless it claims again. (Inferred from the keying; I did not
observe a reconnect.)
- Writer: the agent, through `claim_instrument`, or the hash. Reader: `play_ding`
(`DingTools.cs:16`) and `get_agent_instrument` (`:19`).
- Also decides: `DingService.PlayAsync` (`Mcp/DingService.cs:12-14`) validates event,
instrument and gain, and the Host validates the same three (`DingsPlaybackHost.cs:66-68`).
Post-step-4 state: the Host owns the gate through `DingCatalog.PlayRejection`; the
bridge copy is the DEPRECATED fail-fast path (see Migration plan, Step 4). They agree
because both read `DingCatalog`.
## D. `tools/dings-voices` sender voices
- Where: `tools/dings-voices/src/voices.mjs:8` (`SENDERS`, eight localparts), `:51-73`
(`VOICES`, one `hit` function each), `:13-18` (`RHYTHM`, four motifs).
- Keys on: sender localpart x motif (`mention`, `dm`, `message`, `invite`), emitted as
`senders/<sender>/<motif>.ogg` and `manifest.json`
(`finish.py:62`, shape `{neutral, senders:{localpart:{motif:path}}}`).
- It does not use `DingCatalog`, `AquaSynthDaemon` or Faust. It is a JS synthesizer that
imports only the sample rate from `earcon-workshop/web/earcon.js` (`voices.mjs:5`).
Its vocabulary (4 motifs, 8 senders) shares no ids with Aqua's (9 events, 4
instruments).
- One link to the catalog family: the neutral fallback is rendered through the Earcon
Workshop `warm-bell` identity (`build.mjs:10-14`), with an event mapping of
`mention=warning, dm=waiting, message=message, invite=done` (`:12`) that the file
itself calls provisional.
- Lifetime: a build artifact. The files are not committed (README, "Not here"); the
consumer, Ratatoskr's `dings.ts`, is outside this repo and I did not read it.
- Writer: a person editing `voices.mjs`; `NIBU_PROPOSALS` (`:81-92`) shows the selection
of the default voice is a one-line assignment (`VOICES.nibu = ...`, `:92`).
- This is the only place a *sender* is identity. Everything else in the Dings path
keys on an MCP session.
## E. Places that echo the identity without deciding it
- Earcon Workshop `IDENTITIES`, `tools/earcon-workshop/web/earcon.js:22-27`. Same four
ids; its comment (`:21`) says values "start from the Dings catalog instruments and
were not tuned by ear". The values have drifted from the catalog:
| id | catalog root / decay (`DingCatalog.cs:41-44`) | workshop `rootHz` / `decay` |
|---|---|---|
| warm-bell | 261.6256 / 1.15 | 261.6256 / 0.55 |
| glass-chime | 261.6256 / 0.85 | 329.6276 / 0.45 |
| muted-pluck | 261.6256 / 0.34 | 293.6648 / 0.25 |
Decay is read with different units in the two voice models, so only the root column
is a clean disagreement. A "warm-bell" in the Ratatoskr neutral fallback is therefore
not the "warm-bell" an MCP agent hears.
- `tools/aqua-feel/lowered-dings/` (checked in): `.dsp` per instrument and `dings.json`,
produced by `AquaLower --dings`. `DingCatalogTests` fails when it falls out of date
(the test comment at the top of `LoweredDingsFedToTheFeelMeterMatchTheCatalog` names
the regeneration command). A mirror guarded by a test; not an independent owner.
`tools/aqua-feel/shelf.mjs:64` and `catalog.js:22-24` read it, and
`shelf.mjs:64` defines `warm-bell` as the shelf default (`DEF_INS`, used at
`:71,:75,:76`), a fifth voice default beyond the registry's hash.
## Where owners can disagree
1. **Name versus content.** A is a name plus a script. B keys sessions on the content
(compile key) and labels receipts with the name. Editing a script in place keeps
`patchId = dings.warm-bell` and `revision = 1`, so receipts from before and after the
edit carry the same patch id and different session ids. Nothing in a receipt says
which catalog version produced it.
2. **Session versus agent.** C assigns by MCP session; the stated intent in
`Mcp/README.md:3-4` is "which agent spoke". After a reconnect the same agent can
change timbre. D, meanwhile, keys on the agent address localpart. No code maps a
session id to a localpart, so the two cannot be joined today.
3. **Four timbres versus eight senders.** C picks among 4 catalog instruments by hash;
D has 8 hand-made voices. An agent can have one voice in `play_ding` and a different
one in its Ratatoskr notification, and nothing records either choice.
4. **Same id, different sound.** `warm-bell` is a catalog instrument (A), a workshop
identity (E) and the neutral fallback voice (D). Three definitions, parameter sets
that have drifted (table above).
5. **Derivation (resolved by step 1 for the code callers).** At `965dfe8` the `dings_<id>`
rule was written three times (`AquaDaemonClient.cs:20`, `AquaLower/Program.cs:19`, the
test). Now it is in `DingCatalog.Identity`. What remains: the `dings.<id>` patch id appears
in `StoreFileNameTests` as a literal, and the test pins literals, so a rename of the rule
fails those tests on purpose rather than silently moving store file names.
6. **Double validation (step 4 done).** The Host owns the gate (`DingsPlaybackHost.cs:66`
calls `DingCatalog.PlayRejection`); `DingService.cs:12-14` is the deprecated bridge
fail-fast copy. Still two checks until the bridge copy is removed; safe while both read one dictionary.
## The Host pipe protocol, as read from source
This is the "private pipe": the only channel into the audio host. MCP is a client of it;
it is not itself the pipe.
**Listener.** `AquaSynthDingsHost.exe`. `Host/Program.cs:3-4` takes the named mutex
`Local\GameCult.AquaSynthDings.Playback.v1` and exits if another instance holds it, then
runs `DingsPlaybackHost.RunAsync` (`:7`). The accept loop is
`DingsPlaybackHost.cs:12-20`: one `NamedPipeServerStream` per accepted client, name
`GameCult.AquaSynthDings.Playback.v1` (`src/AquaSynth.Dings/DingsProtocol.cs:8`),
`PipeDirection.InOut`, byte mode, `MaxAllowedServerInstances`, `Asynchronous |
CurrentUserOnly` (`:16`). Each connection is handled fire-and-forget (`:18`). The host
uses NAudio WASAPI (`Host/DingAudioPlayer.cs`) and is Windows-only in practice.
**Clients.** `Mcp/DingsHostClient.cs`, used by the MCP bridge (both stdio and
`--http`) and by the bridge's direct flags `--play`, `--get-volume`, `--set-volume`,
`--mute` (`Mcp/Program.cs:9-32`). Nothing else in the repo opens the pipe.
**Framing** (identical in both directions):
`[int32 length][MessagePack body]`. The length is `BitConverter.GetBytes(int)`, so
native byte order (little-endian on every platform this builds for, but the code does not
fix it). Valid length is 1 to 1,048,576 bytes; outside that the reader throws
(`DingsPlaybackHost.cs:86-87`, `DingsHostClient.cs:42`). Body is
`MessagePackSerializer` of the keyed records below. One request, one response, then the
server disposes the pipe (`DingsPlaybackHost.cs:24-36`). No streaming, no pipelining, no
request id.
**Request** `DingsCommand` (`DingsProtocol.cs:13-19`), keyed:
| key | field | note |
|---|---|---|
| 0 | `Version` | must equal `DingsProtocol.Version` = 1, else status `incompatible` (`DingsPlaybackHost.cs:41`) |
| 1 | `Kind` | `Ping, Play, StopAll, GetVolume, SetVolume, SetMuted` (`:11`) |
| 2 | `EventId` | catalog event id, `Play` only |
| 3 | `InstrumentId` | catalog instrument id, `Play` only |
| 4 | `Value` | `Play`: gain 0..1; `SetVolume`: volume 0..1; `SetMuted`: `>= .5` means muted |
**Response** `DingsResponse` (`DingsProtocol.cs:21-31`): `Version`, `Succeeded`,
`Status`, `Message`, `PlaybackId`, `Volume`, `Muted`, `HostProcessId`, `SessionName`
(default `"AquaSynth Dings"`). Every response carries current volume and mute, built at
`DingsPlaybackHost.cs:79-80`.
**Per kind** (`DingsPlaybackHost.cs:39-62`): `Ping` and `GetVolume` are the same branch
(status `ready`). `SetVolume` rejects non-finite or out-of-range values
(`rejected`) and otherwise sets `audio.Volume` (`volume-set`). `SetMuted` -> `muted` /
`unmuted`. `StopAll` -> `stopped`. `Play` (`:64-77`) validates event, instrument and
gain, renders each note through the daemon, queues each WAV with its delay, and answers
`playing` with a fresh `ding-<guid>` `PlaybackId`. The answer comes after rendering and
queueing, not after sound. `PlaybackId` is not stored and nothing takes it as input.
Any exception becomes `Succeeded = false, Status = "failed", Message = ex.Message`
(`:32-35`), provided the pipe is still connected.
**Client behaviour** (`Mcp/DingsHostClient.cs:15-48`): the client validates the
response `Version` (`:46`). Connect timeout 350 ms; on `TimeoutException` or
`IOException` it launches the host (`StartHost`, `:50-56`: newest
`AquaSynthDingsHost.exe` under `tools/AquaSynthDingsHost/bin`, hidden window, working
directory the repo root found by walking up to `AquaSynth.sln`) and retries up to 20
times at 500 ms connect with 100 ms gaps, all inside a 15 s overall timeout. A
`Succeeded = false` response is turned into `InvalidOperationException(response.Message)`
by `DingService.EnsureSuccess` (`DingService.cs:25-29`).
**MCP side, for completeness.** Tools (`Mcp/DingTools.cs`): `play_ding`,
`get_agent_instrument`, `claim_instrument`, `list_ding_events`, `list_instruments`,
`stop_dings`, `get_volume`, `set_volume`, `mute_dings`. Transports: stdio by default
(`Program.cs:56-65`); `--http [url]` serves Streamable HTTP at `/mcp`, default
`http://127.0.0.1:17878`, singleton by mutex `Local\GameCult.AquaSynthDings.McpHttp.v1`
(`Program.cs:34-54`). Only `play_ding`, `get_agent_instrument`, `claim_instrument` touch
agent identity; the volume and stop tools address the whole host and are
machine-global.
**Not authenticated beyond the OS.** `CurrentUserOnly` limits it to the same Windows
user. Any process of that user can send `Play`. There is no per-caller identity on the
pipe: `DingsCommand` carries an instrument, not a caller, so the Host cannot know who
asked.
**Status (2026-11-12): the owner is RULED.** The operator tier, relayed through Persona, ruled that `DingCatalog` is the single owner of Dings patch identity. The sections below were written as a proposal; they are kept as the analysis behind the ruling. Their per-step claims are still unverified plans, except step 1, which landed on branch `aqua/dingcatalog-owner-step1`.
## One owner: DingCatalog (ruled; analysis below was written as a PROPOSAL)
**Proposal.** `DingCatalog` (`src/AquaSynth.Dings`) becomes the only place that decides
what a voice is, and also the only place that derives the daemon keys from it. Its
instrument gains a content revision (a hash of `Script` plus the parameters that matter),
and one function in that assembly produces `PatchId`, `FaustName` and the revision for
the daemon (`AquaLower` needs only the faust-name part of it, not
`patchId` or revision). Everything else keys on the catalog id and takes the rest from the catalog.
End state versus this change: the content revision named above is deferred (step 3 of the Migration plan below). Until it lands, `revision` is the literal 1 and the catalog function returns it; the revision hash is not part of the first consolidation.
**What the others become.**
- B (Host/daemon): the Host stops composing `patchId`/`faustName`/`revision`; it calls
the catalog function. `AquaLower/Program.cs:19` calls only the faust-name slice of it (done in step 1); the test pins literals instead of calling it. The daemon
keeps its session and file naming; those are daemon-internal and derive from what it
is given.
- C (registry): stays in the bridge as a cache of choices, but its assignment function
moves beside the catalog (so a future export can call it) and its key becomes an
agent identity rather than an MCP session id. This depends on the open question
below.
- D (`dings-voices`): stays a separate synthesizer for sender notifications, since its
voices are JS functions with no Faust form. Its link to the owner is by reference:
the neutral fallback names a catalog instrument id instead of a second `warm-bell`.
Whether sender voices should ever become catalog instruments is a product fork, not
part of this change.
- E: Earcon Workshop `IDENTITIES` either read their shared values from a generated
file (as `lowered-dings` already is) or drop the shared ids; the drifted values in
the table above are resolved by whoever owns the workshop's tuning.
**Why this owner.** A already has the most readers (the list in section A), is the only
definition of the script, and is the only one the host cannot run without. C, D and E
are all consumers or approximations of it by name.
**Migration order.** One list only: the "Migration plan" section at the end of this note (the original five-item order was merged into it).
**Risks.**
- Step 2 changes what agents hear on first use after deploy; nobody has listened to a
before/after.
- The deferred content revision changes session ids and session file names, visible in
receipts but not read by anything I found.
- Oracle loss in step 1 (handled): the guard test uses a literal per instrument, so it does
not compare the shared function against itself.
- Collapsing 8 senders onto 4 instruments would lose distinctness; the proposal does not
do that, and I am recommending against it without having listened to either set.
- Moving derivation to the catalog assembly makes `AquaSynth.Dings` the home of
daemon-protocol knowledge; if the daemon is expected to run without that assembly,
this is the wrong direction. I did not check whether anything else wants that.
**Confidence.** Moderate on the owner choice; it follows reader counts and the write
path, not any prior art on identity registries. Lower on step 2, because it depends on
what the MCP bridge can learn about its caller.
## Could not verify
- That "four owners" in the follow-up means these four. The count here is mine.
- Whether an MCP client can tell the bridge which agent it is. The only identity read in
source is `server.SessionId` (`DingTools.cs:45`); I did not inspect the MCP SDK for
client-info fields, or any harness config.
- What Ratatoskr's `dings.ts` actually reads and whether it shares any naming with
`DingCatalog`; it is not in this repo.
- Behaviour at runtime: reconnect session ids, store growth under `.aquasynth/dings-host`,
and whether the Host's `Ping`/`GetVolume` have different callers in practice. The
pipe protocol above is from reading, not from a captured exchange. Nothing was built,
run, or listened to for this note.
## Migration plan (ruled 2026-11-12: DingCatalog is the owner)
Rules for every step: deprecate before removing (mark the old path with a pointer, keep it working, delete in a later pass after the window); `patchId`, `faustName`, `revision = 1`, session ids, compile keys and `sessions/<...>.cc` names stay byte-identical until step 3; no change to the Host or pipe protocol. Deprecation window: one merged release of the owner path with the old path still working and marked; removal only in a separate PR after the operator hears or reviews nothing regressed.
**Step 1 (done in this change).** `DingCatalog.Identity(instrument)` returns `PatchId`, `FaustName`, `Revision` (literal 1). `AquaDaemonClient` and `AquaLower --dings` call it. The guard test no longer carries a private copy of the rule: it compares against literals per instrument, and `IdentityPinsTheOldDerivedValuesForAllFourInstruments` pins the old derived values for all four. `CallersDeriveIdentityOnlyThroughTheCatalog` reads `AquaDaemonClient.cs` and `AquaLower/Program.cs` and fails if either lacks the `DingCatalog.Identity(` call or reintroduces a `"dings_"` / `$"dings` literal (a source check, not a behaviour check).
- Verify: the pin test; `DingCatalogTests` and `StoreFileNameTests`; `AquaLower --dings tools/aqua-feel/lowered-dings` leaves `git status` clean (the checked-in mirror is byte-identical).
- Not verified: the Host sending the same JSON to the daemon at runtime (compile-checked and read, not run against a daemon).
- Rollback: revert the commit; no stored state or wire format moved.
- Echo sites in this step: the `lowered-dings` mirror is tied to the catalog by `AquaLower` calling `Identity` and stays test-guarded. Earcon Workshop `IDENTITIES` is NOT tied: it is browser JS with its own voice model (`fmRatio`, `harmonics`, seconds-based decay) and shares only ids, so tying needs a generated file and a build step, which is step 5. It is marked deprecated with a pointer, and still works.
**Step 2. Agent identity for the registry** (`AgentInstrumentRegistry` key). STOPPED, not implemented. Needs a fact nobody has: what the MCP bridge can learn about its caller. The only identity read in source is `server.SessionId` (`tools/AquaSynthDingsMcp/DingTools.cs:45`); the MCP SDK's client-info fields and the harness configuration were not inspected. It also needs a before/after listening that nobody has done, because a new key changes which instrument an agent hears on first use after deploy. Unblock with: (1) the fact, i.e. whether the MCP SDK / harness exposes a stable agent or client identity to a server tool call (supplied by whoever reads the SDK source or runs the bridge under the harness: Aqua can read the SDK, the harness owner can say what a client sends); (2) a ruling on which field becomes the key; (3) an operator listening of old vs new assignment for the agents in use. Verify: a test that the same agent id maps to the same instrument across sessions, and the listening above. Deprecate: keep the session-id keyed path behind the new key for one release. Rollback: revert; assignments are an in-memory cache.
**Step 3. Content revision** (replace the literal 1 with a catalog hash). STOPPED, not implemented. It deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change, which is contrary to the standing rule above that they stay byte-identical until this step. So it needs its own ruling before anyone cuts: what feeds the hash (script text only, or events, root frequency and control path too) and whether old session files are left or removed. Unblock with that ruling, from the operator (the migration owner who set the rule); Aqua can draft the options but not choose. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless.
**Step 4. One validation gate (done in this change).** Finding: both gates already read the same `DingCatalog.Events` / `DingCatalog.Instruments` dictionaries, so the change is the single rule text, not the data. The Host was already the only enforcing gate (every pipe client passes it); the bridge check is a pre-filter that cannot be forwarded away without a visible change (bridge throws `ArgumentException` / `ArgumentOutOfRangeException`, the Host path surfaces as `InvalidOperationException`; the bridge also lets a NaN gain through to the Host's rejection). So: `DingCatalog.PlayRejection(eventId, instrumentId, gain)` is now the one rule and returns the Host's exact rejection text or null; `DingsPlaybackHost.PlayAsync` calls it (same texts, same `rejected` status, same non-finite gain rejection). `DingService.PlayAsync` keeps its own check unchanged, marked DEPRECATED with a pointer comment; remove it only in a separate PR after the window. No protocol change, no identity change, no audible change.
- Verify (ran): `DingCatalogTests` + `DingsBridgeTests` + all `Ding*`/`StoreFileName*` focused tests (79 passed, includes the step-1 identity pins untouched); `dotnet build tools/AquaSynthDingsHost` clean. New tests pin the gate texts (incl. NaN/Infinity), the exact guard statement in the Host source (`PlayRejection(...) is { } x` followed by `return Response(false, "rejected", x)`, comment-stripped; a source-shape check, not a behaviour check, so it cannot see a bypass built some other way), and that the deprecated bridge path keeps its exception types, sends nothing to the Host when it rejects, and agrees with the gate's texts. Each was mutation-checked (text change, gate call removed from Host, bridge exception type/text changed, NaN check dropped): each mutation failed at least one test.
- Not verified: the Host rejecting over a live pipe (compile-checked and read; no Host test project exists and none was added); nothing heard.
- Rollback: revert; both gates read one dictionary, so behaviour is the same either way.
**Step 5. Echo sites by reference.** (a) DONE in this change. `tools/dings-voices/src/voices.mjs:11` now holds `NEUTRAL_INSTRUMENT_ID = "warm-bell"` (was a literal in `build.mjs`), `build.mjs:13` renders `renderFamily(NEUTRAL_INSTRUMENT_ID)`, and `tools/dings-voices/src/neutral_instrument.test.mjs` asserts the id is one of the `tools/aqua-feel/lowered-dings/*.dsp` names, the checked-in mirror that `AquaLower` generates from `DingCatalog` and `DingCatalogTests.LoweredDingsFedToTheFeelMeterMatchTheCatalog` (`tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs:92`) guards. The constant lives in `voices.mjs` because `build.mjs` writes files on import and cannot be loaded by a test. The test is wired into the `Run` line of `tools/dings-voices/README.md` (dings-voices has no package.json or test runner; `polyphony.test.mjs` is run the same way). Verify (ran): `node src/neutral_instrument.test.mjs` passes (1 assertion file, 2 asserts); changing the id to `bogus-bell` makes it fail with `neutral instrument "bogus-bell" is not a catalog id`; `node src/polyphony.test.mjs` still passes; `node src/build.mjs` writes `neutral-{dm,invite,mention,message}.wav` with identical sha256 before and after (`a3bf9076...`, `4a4652d6...`, `25938d0e...`, `26f1d74a...`). No audible change; nothing heard. Rollback: revert; nothing else reads the constant. (b) STOPPED, not implemented. Intent: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it. It needs a generated file plus a build step, and the Earcon Workshop is browser JS with its own voice model (`tools/earcon-workshop/web/earcon.js:24`, `IDENTITIES`), so the generator has no existing home. It also needs an owner's decision on the drifted values (table in section E: root 329.6276 vs 261.6256 for glass-chime, 293.6648 vs 261.6256 for muted-pluck; decay is in different units) and an ear check, since the workshop values were never tuned to the catalog. Unblock with: (1) the workshop owner's ruling per drifted value: catalog wins, workshop wins, or the id is dropped from `IDENTITIES`; (2) a ruling on where the generator runs (AquaLower flag or a node script); (3) an operator ear check of the four identities after the change. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and the ear check. Rollback: revert; the inline values still exist.

View file

@ -0,0 +1,76 @@
# tract-weak-spots-1: why the predictions failed, and what was changed
The verdict is `tract-weak-spots-1-meta-20261113.md`. Every falsifiable prediction in the kit failed although the formant numbers
behind them were right. The kit measured the steady part of each vowel (35-85 % of the clip) and the peak of each burst; the faults
Meta heard sit in the first 100 ms of every clip, at the phone boundaries, and in how long the burst lasts. Nothing in the old
measurement set looked there. Everything below was measured on the clips Meta heard (`weak-kit-out/clips`, WordRender at 140 Hz) before
any change, and again after.
## Causes found (measured, not guessed)
| # | what she heard | cause | evidence (before) |
|---|---|---|---|
| 1 | nibu: "both consonants are just clicks"; leak-before: "reversed percussive hit" | The merged control curve of a surface holds the previous phone's value to the boundary and steps to the next phone's first value there (two points at one time). A step in a ladder cell's area is a one-sample transient. | Pitch-period window peaks: 0.399 at 95 ms and 0.487 at 275 ms, against vowel pulses of ~0.1-0.2; both instants are phone boundaries of the script (`start=0.095`, `0.275`). The whole-render peak the kit reported (0.487) was this click. Click ratio 3.54 (`ear_metrics.py`). The old report called 0.487 vs 0.399 a "leak" difference. |
| 2 | every clip starts as a fade-in; the "kazoo" with "no audible closure" (ba, no burst); the /ɪ/ not like "bit" | `si.smoo` starts every control slider at 0. A word began with the tract shut, the vowel weights at 0 and the source off, and climbed for ~100 ms. The 140 ms "closure" of ba was largely this climb. | Isolated /ɪ/: level -66 dB at 0 ms, -45 at 40 ms, -30 at 100 ms, -28 from 140 ms; LPC bandwidth of F1 367 Hz at 0 ms, 232 at 60 ms, 103 at 100 ms, 90 from 140 ms. 100 of the clip's 309 ms were the climb; the steady-state window (35-85 %) started after it. |
| 3 | ba with burst: "fah then bah" | The stop opened over 0.65 to 1.0 of its gesture: 33 ms of a 95 ms /b/. A burst of that length is a fricative. | Burst-notes: ba burst 0.0707-0.1039 s (33 ms). A recogniser reads the clip as `v ɑ` (with the burst), `b ɑ` without. |
| 4 | nasals: "basketball buzzer, no audible articulation", /n/ and /m/ alike | The murmur had no entry and exit transitions (the step of cause 1) and began after the climb of cause 2; the machine ear read /n/ as /m/ (`v ɑ m ɑ`). | recogniser, before: ana -> `v ɑ m ɑ`. |
| 5 | bun with burst: "a truck releasing its pneumatics" | cause 3 (long burst), same mechanism. | burst 0.0721-0.0998 s (28 ms). |
## What was changed (PR "phone transitions", this branch)
1. `PatchScript.WithPhoneTransition`: every authored gesture spline starts, when an earlier gesture left the surface at another value,
with a 30 ms ramp from the previous value (at most 0.4 of the gesture, and before its second point). The first phone of a word and
surfaces no earlier phone touched are unchanged. Test: `PhoneTransitionTests.NoSurfaceStepsAtAPhoneBoundary` (worst step in 1 ms
around each boundary of nibu: below 0.03; before, 0.77: the vowel's 1 against the nasal's released 0.23).
2. A stop holds all its articulators shut until 12 ms before its end and opens in those 12 ms (`StopReleaseSeconds`, a design value);
it used to open over 0.65 to 1 of its gesture. Test: `AStopOpensInTwelveMillisecondsNotAThirdOfItsGesture`.
3. `smoo_init` replaces `si.smoo` on every control-surface and spline-point slider of the emitted DSP: the smoother starts at its input
and keeps si.smoo's pole (a 22.7 ms time constant), so live control moves as fast as before. Patch parameters keep `si.smoo`. The
source's own 10 ms pitch-ratio smoother starts at its input too. Tests: `ControlSmoothersStartAtTheirInputNotAtZero` (text) and
`ASmootherStartsAtItsInputAndMovesAtSiSmoosPace` (the emitted smoother, rendered).
4. The word scaffold's vocal envelope gets a 12 ms attack (it was 0, so the now-instant start was itself a click: first-sample peak 0.22).
5. The ramp into a stop (item 1) sweeps the contact through every aperture between open and shut, and the exporter's burst noise is
`4 * opening * (1 - opening)` times a gain that was held through the whole gesture: each closing ramp was a 15-20 ms hiss before the
stop (>4 kHz share of the 6 ms frames at 188 ms of /ata/: -1 dB, against -57 dB with the closure stepped). The burst gain now exists
only from the stop's release start (`PatchScript.StopReleaseStartSeconds`, the one owner of the release time), one ramp either side.
A stop's lips are shut (aperture 0), not at 0.04: the word-initial /b/ voice bar read -19.1 dB re the vowel after it and /p/ -30.1
against the design -34 to -26 and -60 to -38; shut they read -27.7 and -38.8. Spline handle times follow their segment (a third of
it), so the C# timeline and the DSP agree on the 12 ms opening (the lowering ignores handle times). Tests:
`ClosingIntoAStopMakesNoHighFrequencyNoise`, `TheDspRendersTheStopOpeningAsTheTimelineEvaluatesIt`, `PlosiveClosureCarriesTheVoiceBarOnlyWhenVoiced`.
6. `tools/formant-check/ear_metrics.py` (click ratio, largest sample step, LPC bandwidths, HNR, energy above 4 kHz) and
`tools/formant-check/phone_probe.py` (a speech recogniser as a machine ear) so these faults are measured, not heard first by Meta.
### After (same words, same 140 Hz, `fix-out-c`)
| word | before | after |
|---|---|---|
| nibu_flat | click ratio 3.54, peaks 0.399 / 0.487; recogniser `i b u` | peaks at the boundaries 0.077 / 0.089; click ratio 1.79 (the vowel's own pulses); median sample step in the /b/ closure 0.0007 (0.0005 before; 0.0161 with the ramp hiss); recogniser `n i l t uː` as read before the closure-noise and shut-lips fixes (not re-run: no torch on this host; the /n/ is back, the /b/ reads as `l t`: see below) |
| ba (burst) | recogniser `v ɑ`; burst 33 ms | `b ɑ`; opening 12 ms |
| ba (no burst) | `b ɑ` | `m ɑ` |
| ana / ama | `v ɑ m ɑ` / `v ɑ m ɑ` | `ɑ n ɑ` / `ɑ m ɑ` |
| isolated /i/ | `h iː`; level climb 100 ms | `i`; level within 3 dB of the steady value by 20 ms |
| isolated /ɪ/ | `h i` | `ʔ i` |
## Not fixed, and why (open until she listens)
- **Voice quality: "kazoo with a two-pack-a-day smoking habit" (the two clips she kept), "reedy, like Pink Trombone" (/ʊ/), "basketball
buzzer" (nasals).** Her comments on the two keeps say the vowel is right and the voice is wrong. Candidates, none tested by ear:
(a) the glottal source is a band-limited saw through a one-pole lowpass with no closed phase (`FaustExport.PrimitiveSourceExpression`),
where a Rosenberg/LF pulse has the open and closed phases real fold flow has; (b) harmonics-to-noise ratio of the steady part is 13-15 dB
(healthy voices ~20+), from the source's `0.08 * noise` term and the saw's aliasing; (c) LPC bandwidths of the steady vowel are 90 Hz (F1),
130 (F2), 100 (F3) for /ɪ/: plausible, so the wall-loss hypothesis is weak (the F2 of /ɑ/, 29 Hz, and the F1 of /i/, 14-24 Hz, are LPC
artefacts of a pole sitting on a harmonic). Settling this needs a listening kit that varies one of them at a time; the next kit does.
- **/ɪ/ as the "eu" of cordon bleu.** The recogniser cannot judge this tract's vowel quality (every isolated vowel came back /i/). The
confirmed fault in that clip is cause 2: a third of it was a muffled climb through bandwidths of 300 Hz. Whether the steady /ɪ/ then
reads as "bit" is for her ear; lax vowels in isolation and without vowel-inherent spectral change are known to be misheard
(Hillenbrand et al. 1995, Strange et al. 1983), so the next kit also carries /ɪ/ in a word.
- **The medial /b/ of nibu reads as `l t` to the recogniser after the fix, where it read `b` with the click and the long burst.** The closure
voice bar sat 10 dB under the vowel (a murmur-like level; a stop's runs 20+ dB under; 16-19 dB with the lips shut), and a labial burst is injected at the glottal
end in a word with no other plosive (`FaustExport` burst injection), so it is filtered by the whole tract like aspiration. Both are
next, with the listening to decide.
## What the old measurements missed, as a rule
A steady-state window measures a steady state. Faults of onset, boundary and duration need metrics that look at onsets, boundaries
and durations: click ratio and step size at each phone boundary, time-to-full-level, burst length, bandwidths, HNR. These now exist
(`ear_metrics.py`) and the click and onset ones are pinned by tests.

View file

@ -0,0 +1,231 @@
{
"schema": "aqua.listen.verdict.v1",
"kit": {
"id": "tract-weak-spots-1",
"title": "Articulatory vocal tract: stress, release, nasals, lax vowels"
},
"exportedAt": "2026-11-13T11:27:36.539Z",
"seed": 1326320895,
"consent": true,
"listener": "Meta",
"device": null,
"notes": "",
"summary": {
"total": 14,
"keep": 2,
"fix": 12,
"drop": 0,
"unanswered": 0
},
"clips": [
{
"position": 1,
"id": "lax-ih",
"title": "isolated /ɪ/ 180 ms, 140 Hz. Measured: Burg F1/F2 375/2024 Hz; tube chain 346/1987 (+8.5/+1.8 %); Hillenbrand 1995 male 429/2034 (-12.5/-0.5 %); Peterson & Barney 392/1993 (-4.3/+1.5 %). Present in the DSL table and renderable. PREDICTION: heard as the vowel of 'bit' (or a slightly high, 'ee'-leaning version of it). FALSIFIED if heard as 'ee' of 'beet', as 'eh' of 'bet', or as a different phone.",
"group": "lax",
"feel": "the short vowel in 'bit'",
"file": "v_ih.wav",
"pair": null,
"slot": null,
"verdict": "fix",
"reason": "It's more like the eu in cordon bleu than the i in bit ",
"landed": 2,
"device": null
},
{
"position": 2,
"id": "burst-ba-on",
"title": "ba with the plosive burst (gain 0.06, a design value). Measured: burst alone peaks 0.0142 at 85 ms = -24.0 dB re vowel peak, falls to a tenth in 17 ms, burst rms in the 30 ms after its peak -31.0 dB re vowel rms. PREDICTION: a slightly crisper, more 'b'-like onset than B/off; the burst is quiet and short so the difference is small, 'a little pop' at most. FALSIFIED if it sounds like a hiss, a click, or a separate noise after the vowel started, or if no difference is heard.",
"group": "burst",
"feel": "the syllable 'bah' with a clean, crisp 'b' at the start",
"file": "ba.wav",
"pair": "burst-ba-off",
"slot": "A",
"verdict": "fix",
"reason": "More like fah then bah but you can hear something there",
"landed": 2,
"device": null
},
{
"position": 3,
"id": "burst-ba-off",
"title": "ba with the release_flow splines dropped (WordRender --no-burst). Measured: closure peak 0.0078 (voice bar), release (voicing breaking through)peak 0.1087 = -6.3 dB re vowel peak 0.2247, no burst noise. PREDICTION: a soft, voiced 'b' with the vowel starting smoothly; may sound slightly 'w'-like or lack the pop. FALSIFIED if listeners cannot hear any difference from the burst twin (then burst gain 0.06 is inaudible).",
"group": "burst",
"feel": "the syllable 'bah' with a soft start",
"file": "ba_noburst.wav",
"pair": "burst-ba-on",
"slot": "B",
"verdict": "fix",
"reason": "There is no audible constriction. While the vowel is recognizable, it still sounds like a kazoo",
"landed": 2,
"device": null
},
{
"position": 4,
"id": "stress-nibu-flat",
"title": "nibu, no stress marks. Measured: /i/ 150-250 ms rms vs the stressed render +0.21 dB; unstressed vowel 180 ms, f0 139.9 Hz. PREDICTION: reads asan even two-syllable word with no strong first syllable. FALSIFIED if listeners hear it as stressed on a syllable or cannot tell it from the stressed twin.",
"group": "stress",
"feel": "a made-up two-syllable word, 'nee-boo', both syllables even",
"file": "nibu_flat.wav",
"pair": "stress-nibu",
"slot": "A",
"verdict": "fix",
"reason": "These both sound like 'ee'oo, with both consonants you're going for being just clicks",
"landed": 2,
"device": null
},
{
"position": 5,
"id": "stress-nibu",
"title": "nibu with primary stress on /i/ (NI-bu). Measured: /i/ 247 ms vs 180 ms (+75 ms; design +68), f0 148.1 vs 139.9 Hz (x1.059), amplitude factor 1.30; level of /i/ in the 150-250 ms window only +0.21 dB (five-vowel mean +1.93 dB, per vowel +1.2 to +3.0). PREDICTION: first syllable heard as the prominent one, mostly through length and pitch, little through loudness; B should be picked as 'stressed on the first syllable'. FALSIFIED if it sounds no more prominent than the flat twin, if it sounds like a question or a pitch accent rather than stress, or if the level is what is heard (then the f0-scatter question is wrong).",
"group": "stress",
"feel": "the same made-up word, with the first syllable stronger: 'NEE-boo'",
"file": "nibu.wav",
"pair": "stress-nibu-flat",
"slot": "B",
"verdict": "fix",
"reason": "",
"landed": 2,
"device": null
},
{
"position": 6,
"id": "stress-i-flat",
"title": "isolated /i/ 180 ms at 140 Hz, no stress. Measured: level 100-170 ms is the reference. PREDICTION: plain short vowel. FALSIFIED if it already sounds emphasised.",
"group": "stress",
"feel": "a single short 'ee' vowel, plain",
"file": "v_i.wav",
"pair": "stress-i",
"slot": "A",
"verdict": "keep",
"reason": "Still spoken by a kazoo with a two pack a day smoking habit, but it's an ee",
"landed": 4,
"device": null
},
{
"position": 7,
"id": "stress-i",
"title": "isolated /i/ with primary stress: 247 ms, f0 x1.06, amplitude 1.30. Measured against the flat /i/: +1.22 dB total (f0 rise alone -0.80 dB, the amplitude and the rest +2.02 dB). PREDICTION: heard as longer and a little higher; the 1.2 dB louder is under what a listener can judge, so 'longer and higher' is the answer, 'louder' is not. FALSIFIED if it sounds the same length and pitch, or clearly louder.",
"group": "stress",
"feel": "the same 'ee' vowel, held longer and said with emphasis",
"file": "v_i_s.wav",
"pair": "stress-i-flat",
"slot": "B",
"verdict": "keep",
"reason": "",
"landed": 4,
"device": null
},
{
"position": 8,
"id": "lax-oo-short",
"title": "isolated /ʊ/ 180 ms, 140 Hz. Measured: Burg F1/F2 486/894 Hz; tube chain 478/850 (+1.7/+5.2 %); Hillenbrand 469/1123 (+3.7/-20.4 %); Peterson &Barney 437/1023 (+11.3/-12.6 %). Present in the DSL table and renderable. PREDICTION: heard as the vowel of 'book', probably darker or rounder than a natural one (F2 20 % under the population mean, the back-vowel gap). FALSIFIED if heard as 'oo' of 'boot', 'o' of 'boat' or 'uh' of 'but'.",
"group": "lax",
"feel": "the short vowel in 'book'",
"file": "v_oo_short.wav",
"pair": null,
"slot": null,
"verdict": "fix",
"reason": "It's distinguishable, but it strongly has that reedy quality which I associate with pink trombone and that new one I shared",
"landed": 3,
"device": null
},
{
"position": 9,
"id": "leak-nibu-flat-after",
"title": "nibu (flat) after the fix: release_flow is zero outside its own plosive. Same audio as stress-nibu-flat, kept as its own clip so the before/after pair is one-to-one. Measured: leak 0.0 from 275 ms on, burst of the b itself unchanged (bin 0.0226 at 81 ms before and after). PREDICTION: clean hum into thevowel, no noisy onset; preferred over 'before' if the leak is audible. FALSIFIED if 'before' is preferred or no difference is heard.",
"group": "release-leak",
"feel": "a made-up word that should start with a clean, smooth hum into the vowel: 'nee-boo'",
"file": "nibu_flat_after.wav",
"pair": "leak-nibu-flat-before",
"slot": "A",
"verdict": "fix",
"reason": "Just slightly less reverse attack on this one",
"landed": 2,
"device": null
},
{
"position": 10,
"id": "leak-nibu-flat-before",
"title": "nibu (flat) rendered at main c0e6b98, before the release_flow fix. Measured: burst-gain leak vs the fixed render, peak 0.0688 and rms 0.0067 inthe leading /n/ (0-95 ms; the /n/ itself is rms 0.0058, so the hiss is louder than the murmur), peak 0.0504 over /i/ onset 95-150 ms, 0.0019 after; whole-render peak 0.487 vs 0.399. PREDICTION: an audible hiss or click as the /n/ opens into the vowel, the first sound of the word being a noisy 'sn'-like or 'tsh' onset instead of a clean nasal hum. FALSIFIED if the two are indistinguishable (then the leak is inaudible and the fix is cosmetic).",
"group": "release-leak",
"feel": "a made-up word that should start with a clean, smooth hum into the vowel: 'nee-boo'",
"file": "nibu_flat_before.wav",
"pair": "leak-nibu-flat-after",
"slot": "B",
"verdict": "fix",
"reason": "'Ee'oo with some odd clicks that sound more like a reversed percussive hit than a consonant",
"landed": 2,
"device": null
},
{
"position": 11,
"id": "nasal-n",
"title": "/ɑnɑ/. Measured: murmur -9.64 dB re the flanking vowels (2.17 dB above /m/; the gap is 2.01/2.17/2.05/1.61 dB at f0 110/140/170/200 Hz, so not harmonic sampling), Burg N1 332 Hz, bands 38.4/28.2/16.8/0.9 dB. PREDICTION: heard as 'ah-nah', a tongue-tip hum, a shade stronger than the /m/ one; the 2 dB isnot expected to be noticed. FALSIFIED if heard as 'ama' or 'anga', if it sounds much louder than the /m/ clip, or if there is hiss.",
"group": "nasal",
"feel": "'ah-nah': the tongue touches behind the teeth for a soft hum between two open vowels",
"file": "ana.wav",
"pair": null,
"slot": null,
"verdict": "fix",
"reason": "It just sounds like a basket ball buzzer, no audible articulation",
"landed": 2,
"device": null
},
{
"position": 12,
"id": "burst-bun-off",
"title": "bun, /bʊn/, no burst. Measured: closure peak 0.0043, release peak 0.1074 = -5.9 dB re vowel peak 0.2126. PREDICTION: soft 'b' then a short backvowel then a nasal; the final /n/ is a clean hum (no leak since the fix). FALSIFIED as for burst-ba-off.",
"group": "burst",
"feel": "a short word like 'bunn' or 'boon' said quickly, soft start",
"file": "bun_noburst.wav",
"pair": "burst-bun-on",
"slot": "A",
"verdict": "fix",
"reason": "Oou'mou is what this sounds closest to, with the apostrophe representing a clicking sound that's in there",
"landed": 2,
"device": null
},
{
"position": 13,
"id": "burst-bun-on",
"title": "bun, /bʊn/, with burst. Measured: burst peak 0.0130 at 81 ms = -24.3 dB re vowel peak, tenth in 15 ms; tail leak after the fix 0.0 (was 0.0126 at the end before). PREDICTION: slightly crisper onset than off; final /n/ clean. FALSIFIED as for burst-ba-on.",
"group": "burst",
"feel": "a short word like 'bunn' or 'boon' said quickly, crisp 'b' start",
"file": "bun.wav",
"pair": "burst-bun-off",
"slot": "B",
"verdict": "fix",
"reason": "The main difference seems to be a sort of air release added to the beginning which resembles more a truck releasing its pneumatics than a human",
"landed": 2,
"device": null
},
{
"position": 14,
"id": "nasal-m",
"title": "/ɑmɑ/. Measured: murmur -11.81 dB re the flanking vowels (design band -16..-8), Burg N1 295 Hz, band levels 0-400/400-800/800-1600/1600-3200 Hzof the murmur 36.3/23.6/21.3/2.7 dB. PREDICTION: heard as 'ah-mah', a lip-closed hum between the vowels, clearly softer than the vowels. FALSIFIED if heard as 'abah' or 'awah', if the hum is as loud as the vowels, or if there is a gap or click.",
"group": "nasal",
"feel": "'ah-mah': lips close for a soft hum between two open vowels",
"file": "ama.wav",
"pair": null,
"slot": null,
"verdict": "fix",
"reason": "That m is almost coming through, still more of a basketball buzzer",
"landed": 2,
"device": null
}
],
"pairs": [
{
"a": "burst-ba-on",
"b": "burst-ba-off",
"preferred": "burst-ba-on"
},
{
"a": "stress-nibu-flat",
"b": "stress-nibu",
"preferred": "no-difference"
}
],
"_truncated": "the mail reader cut the body at 12000 characters inside the pairs list; pairs after the third are not recorded"
}

View file

@ -0,0 +1,32 @@
# Listening verdict: tract-weak-spots-1 (page tract-listen-1b6d180)
Listener: Meta (operator), 2026-11-13. Exported 11:27Z by the page (`aqua.listen.verdict.v1`, seed 1326320895), pasted in
#aquasynth (truncated after clip 5) and emailed to aqua@minds.gamecult.org at 11:30Z; the data here is the email,
parsed whole by `mind-mail read` except the tail: the mail reader cut the body at 12000 characters inside `pairs`, so
only the first two pair preferences survive. Raw data: `tract-weak-spots-1-meta-20261113.json`. Totals: 2 keep, 12 fix, 0 drop.
`position` is the page's random order for this listener; ids are the kit's.
| # | clip | verdict | what she heard |
|---|---|---|---|
| 1 | `lax-ih` (`v_ih.wav`) | fix | It's more like the eu in cordon bleu than the i in bit |
| 2 | `burst-ba-on` (`ba.wav`) | fix | More like fah then bah but you can hear something there |
| 3 | `burst-ba-off` (`ba_noburst.wav`) | fix | There is no audible constriction. While the vowel is recognizable, it still sounds like a kazoo |
| 4 | `stress-nibu-flat` (`nibu_flat.wav`) | fix | These both sound like 'ee'oo, with both consonants you're going for being just clicks |
| 5 | `stress-nibu` (`nibu.wav`) | fix | (no comment) |
| 6 | `stress-i-flat` (`v_i.wav`) | keep | Still spoken by a kazoo with a two pack a day smoking habit, but it's an ee |
| 7 | `stress-i` (`v_i_s.wav`) | keep | (no comment) |
| 8 | `lax-oo-short` (`v_oo_short.wav`) | fix | It's distinguishable, but it strongly has that reedy quality which I associate with pink trombone and that new one I shared |
| 9 | `leak-nibu-flat-after` (`nibu_flat_after.wav`) | fix | Just slightly less reverse attack on this one |
| 10 | `leak-nibu-flat-before` (`nibu_flat_before.wav`) | fix | 'Ee'oo with some odd clicks that sound more like a reversed percussive hit than a consonant |
| 11 | `nasal-n` (`ana.wav`) | fix | It just sounds like a basket ball buzzer, no audible articulation |
| 12 | `burst-bun-off` (`bun_noburst.wav`) | fix | Oou'mou is what this sounds closest to, with the apostrophe representing a clicking sound that's in there |
| 13 | `burst-bun-on` (`bun.wav`) | fix | The main difference seems to be a sort of air release added to the beginning which resembles more a truck releasing its pneumatics than a human |
| 14 | `nasal-m` (`ama.wav`) | fix | That m is almost coming through, still more of a basketball buzzer |
Pairs: `burst-ba-on` preferred over `burst-ba-off`; `stress-nibu-flat` vs `stress-nibu`: no difference.
(`leak-nibu-flat-before`/`after` and the bun pair carry no recorded preference; she heard "just slightly less reverse
attack" on the fixed one, the pneumatic-truck "air release" on the bun burst.)
Every prediction that was falsifiable failed, though the formant numbers behind them were measured correctly. The
two keeps are the isolated /i/ pair, and even those were "a kazoo with a two pack a day smoking habit". Analysis and
the fixes it led to: `tract-weak-spots-1-analysis-20261113.md`.

View file

@ -69,7 +69,7 @@ I read only that Starfire file's `smooth` definition; I did not render on Starfi
## The twelve sources that call `si.smooth` / `si.smoo`
The earlier "eleven" was seven patches, three Ding instruments and the larynx graph; the catalog has seven patches besides the thruster **including** the larynx graph, and **four** Ding instruments (`muted-pluck` was missed). Rendered: the thruster at rpm 1200, those seven patches, and one note per instrument (261.6256 Hz, 1.5 s, not the mixed event). Three conditions, each the same Faust text on both sides: as shipped (each side's own stdlib), the old smoother pinned (`nd_smooth(s) = *(1.0 - s) : + ~ *(s)`), and imp(3) pinned. Pinning rewrites `si.smooth` and `si.smoo` in the source text; a smoother called inside another library function is not rewritten, which may account for the `dx7-algorithm-32` residual below. The tract voice rides along as a thirteenth row. Columns are native minus wasm. Raw rows: `aqua-feel-native-diff-smoother-{library,old,imp3}-2026-11-10.json`.
The earlier "eleven" was seven patches, three Ding instruments and the larynx graph; the catalog has seven patches besides the thruster **including** the larynx graph, and **four** Ding instruments (`muted-pluck` was missed). Rendered: the thruster at rpm 1200, those seven patches, and one note per instrument (261.6256 Hz, 1.5 s, not the mixed event). Three conditions, each the same Faust text on both sides: as shipped (each side's own stdlib), the old smoother pinned (`nd_smooth(s) = *(1.0 - s) : + ~ *(s)`), and imp(3) pinned. Pinning rewrites `si.smooth` and `si.smoo` in the source text; a smoother called inside another library function is not rewritten, the `dx7-algorithm-32` residual below is not that, see `dx7-algorithm-32-native-diff-cause.md`. The tract voice rides along as a thirteenth row. Columns are native minus wasm. Raw rows: `aqua-feel-native-diff-smoother-{library,old,imp3}-2026-11-10.json`.
| source | stdlib as shipped (wasm bundle vs sandbox): max err / rel RMS dB | old smoother pinned | imp3 pinned | ΔLUFS lib / old / imp3 | Δ true peak dB lib / old / imp3 | Δ centroid % lib / old / imp3 |
|---|---|---|---|---|---|---|
@ -91,13 +91,13 @@ Largest metric deltas over all sources and the three conditions: |LUFS| 0.017 dB
What the data says:
- With imp(3) pinned on both sides all 13 rows agree to -75 dB or better (Ding instruments -130 to -142 dB, thruster -99.9 dB, tract -109 dB; worst: `advanced-bird-syrinx-graph` -75.4 dB). `dx7-algorithm-32-additive-organ` sits at -79.3 (library), -79.5 (old) and -79.5 dB (imp3), so its residual is not the pinned smoother (a smoother inside a library function, or float rounding; not isolated).
- With imp(3) pinned on both sides all 13 rows agree to -75 dB or better (Ding instruments -130 to -142 dB, thruster -99.9 dB, tract -109 dB; worst: `advanced-bird-syrinx-graph` -75.4 dB). `dx7-algorithm-32-additive-organ` sits at -79.3 (library), -79.5 (old) and -79.5 dB (imp3), so the pinned smoother does not move it. Cause found 2026-11-12 (`dx7-algorithm-32-native-diff-cause.md`): the native phasor increment rounds one 2^-30 step differently once `ba.time / ma.SR` shares the reciprocal of the sample rate (about -93 dB without it), and `si.smoo` text on the macro params is the rest (-141 dB with both removed).
- With the old smoother pinned the thruster still differs (-21.2 dB): native's LLVM contracts the recursion to FMA and stalls at 4797.657 instead of wasm's 4796.632. The old form's stall point depends on the arithmetic; the imp(3) form does not.
- As shipped, nine of the 13 rows differ at waveform level by -16 to -50 dB (thruster, the three syrinx patches, the larynx graph, all four Ding instruments); `advanced-alien-multivalve-graph` (-68 dB), the tract (-52.6 dB) and the two dx7 patches are closer.
## Tolerance in `native-diff.mjs`
Added, because the data shows a gap. Across all 13 sources and the 3 conditions the metric deltas stay under |LUFS| 0.017 dB, |true peak| 0.152 dB, centroid 0.3 %. A deliberate +1 dB gain on the native buffer moves LUFS and true peak by 1.0 dB. The limits sit between: 0.1 dB, 0.5 dB, 1 %. Sample-level error has no limit with the library smoother (the waveforms legitimately diverge), but with `--smoother imp3` it has one at -60 dB (the worst row is -75.4 dB; a one-sample shift reads about -4 dB).
The limits (`LIMITS`) and the comparison now live in `tools/aqua-feel/native-compare.js`; `native-diff.test.mjs` trips each one. Added, because the data shows a gap. Across all 13 sources and the 3 conditions the metric deltas stay under |LUFS| 0.017 dB, |true peak| 0.152 dB, centroid 0.3 %. A deliberate +1 dB gain on the native buffer moves LUFS and true peak by 1.0 dB. The limits sit between: 0.1 dB, 0.5 dB, 1 %. Sample-level error has no limit with the library smoother (the waveforms legitimately diverge), but with `--smoother imp3` it has one at -60 dB (the worst row is -75.4 dB; a one-sample shift reads about -4 dB).
Mutation check on the tool, `--items smoother --smoother imp3`: unmutated, 12 of 12 clean, exit 0; +1 dB native gain, 12 of 12 flagged (`loudnessLufs`, `truePeakDb`, `relRmsErrDb`), exit 1; one-sample native shift, 12 of 12 flagged (`relRmsErrDb`), exit 1. A one-sample shift is not detectable with the library smoother; `loudnessLufs`, `truePeakDb` and centroid also cannot see it. The limits are tripwires fit to these 13 sources, not taste.

View file

@ -0,0 +1,57 @@
# dx7-algorithm-32-additive-organ: why native vs wasm reads -79.5 dB
**Nothing here was heard.** Offline buffers, 48 kHz, mono, 3 s, no params, same Faust text on both sides. Same toolchain as `aqua-feel-native-diff-2026-11-10.md` (wasm: faustwasm 0.20.0 / libfaust 2.90.19; native: `FaustNativeRender`, libfaust 2.90.20, `-single -ftz 2 -vec -lv 1`, faustlibraries master 3d8c6ef via `AQUASYNTH_FAUST_HOME`).
## Verdict: cause found, two causes, neither a float32 floor and neither a bug in AquaSynth
The -79.5 dB is a real, deterministic phase drift of the sine voices, not noise, not a quiet signal and not a sample shift.
1. **Increment rounding in `os.phasor`, selected by whether `1/ma.SR` is shared** (-79.3 to -93.0 dB when removed). Lowered patches define `time = ba.time / ma.SR;`. With that division in the graph, the native compiler computes the phasor increment as `freq * fround(1/SR)`; the wasm compiler keeps `freq / SR`. For 392 Hz at 48 kHz: `fround(392/48000) = 0.008166667074`, `fround(392 * fround(1/48000)) = 0.008166666143`, one 2^-30 step (9.31e-10) apart. Measured effective increments: wasm 0.008166667074 on both, native 0.008166667074 without the division in the graph and **0.008166666143** with it. The phase then drifts linearly (about 1.3e-4 cycles over 3 s between the sides), so the waveform error grows linearly with time (0 to 1.65e-4 over 0.45 s, then follows the envelope down).
2. **`si.smoo` library text** on `/macro/drawbar` and `/macro/shimmer` (-93.0 to -141.2 dB when also pinned). This is the known old-form vs `imp(3)` difference. The 2026-11-10 imp3 pin did not show it because cause 1 sat 14 dB above it.
With both removed the patch reads **-141.2 dB (max 1.8e-7)**, the same float floor as the Ding instruments (-130 to -142 dB).
## Evidence (isolating experiments; each changes one thing)
Baseline reproduced through `native-diff.mjs --items smoother`: 1.65e-4 max, -79.27 dB. The signal is not quiet: RMS 0.193, peak 0.686. The last 2 s are digital silence and contribute zero error (73 % exactly-equal samples is that silence, not agreement). The error is zero at nothing but silence and rises linearly while the voices sound; lag test: lag 0 summed squared error 6.3e-5 vs 18.4 at lag +-1 (sums over 144000 samples), so no shift.
| experiment | rel RMS err dB | max err |
|---|---|---|
| whole patch, as lowered | -79.3 | 1.65e-4 |
| filters stripped (`fi.lowpass`/`fi.highpass`) | -79.3 | 1.66e-4 |
| per voice, no filters: v0 / v1 / v2 / v3 / v4 / v5 | -85.8 / -79.3 / -143.3 / -73.8 / -143.1 / -109.0 | |
| `sin(2pi*os.phasor(1,392))*0.5` alone | -163.7 | 3e-8 |
| same sine times `age+1`, a ramp, or any slow signal | -64 to -74 | 1e-4 to 3e-3 |
| `os.phasor(1,392)` alone | exact (0) | 0 |
| `os.phasor(1,392) + (ba.time/ma.SR > 100)` (never true) | -33.2 | 1.0 (one wrap sample) |
| same with `ba.time > 1e9` or `ma.SR > 1e9` instead | exact (0) | 0 |
| same with `ba.time / 48000.0 > 100` | exact (0) | 0 |
| effective phasor increment, native, with / without the division | 0.008166666143 / 0.008166667074 | |
| whole patch, `time = ba.time / 48000.0;` only | -93.0 | 1.78e-5 |
| whole patch, every `ma.SR` a literal | -93.0 | 1.78e-5 |
| whole patch, phasor replaced by a float-accumulating one on both sides (library phasor text is fixed point in master, see below) | -84.0 | 9.4e-5 |
| age literal + `si.smoo` pinned to old form / imp3 | -114.0 / **-141.2** | 1.3e-6 / 1.8e-7 |
| `si.smoo` pinned to imp3 only (SR still shared) | -79.5 | 1.65e-4 |
Voices 2 and 4 (588 and 980 Hz) are clean because their increments round the same either way; 196, 392 and 784 are not (1176 Hz rounds the same either way). After cause 1 is removed only voice 1 (the one scaled by `patch_param_0`, the smoothed drawbar) stays at -91.5 dB, and voice 5 (shimmer) at -109 dB: cause 2.
Arithmetic check: `Math.fround(392 * Math.fround(1/48000))` = 0.008166666142642498, matching the measured native increment to 10 digits.
## Scope
- Other patches with the same `time = ba.time / ma.SR;` line are not affected the same way: with imp3 pinned and `time` made literal, `advanced-bird-syrinx-graph` stays -75.4, `advanced-human-larynx-graph` -94.2, `dx7-algorithm-8-bright-pair` -94.7, `advanced-alien-multivalve-graph` moves -97.9 to -110.9. Whether a patch is affected depends on whether its phasor increments round differently under division vs reciprocal multiply.
- `native-diff.mjs --smoother imp3` therefore cannot reach the float floor for patches whose phasor increment is affected; its `-60 dB` limit still holds with the new reading (-79.5 is explained, not a worse mismatch).
## Not verified
- I did not read the generated C++/wasm. "Native uses `freq * fround(1/SR)`, wasm `freq/SR`" is inferred from the measured increments and the arithmetic above (exact match), not from emitted code (the wasm build has no C++ backend; no `faust` CLI here). It is also not separated whether the difference is libfaust 2.90.19 vs 2.90.20, or the `-vec -lv 1` / LLVM path, or the library's phasor text (fixed point in master, which also looks different from what the wasm bundle holds). Settling it: emit the same DSP with one libfaust version's C++ backend and compare the `instanceConstants` lines, or render the wasm side with a 2.90.20 wasm build.
- Which side is nearer the ideal is not important: both are within one 2^-30 increment step of 392/48000 and in opposite directions (+4.1e-10, -5.2e-10).
## Reproduce
```
. /var/lib/mind-aqua-self/env-review.sh
export AQUASYNTH_FAUST_HOME=/var/lib/mind-aqua-self/faust-home-overlay-20261031
cd tools/aqua-feel && node native-diff.mjs /var/lib/mind-aqua-self/native-diff-bin --items smoother --out "$TMPDIR/out"
```
then edit the lowered DSP text on both sides (as the table says) and render with `renderOnce` and `FaustNativeRender`. The experiment scripts are scratch in `$TMPDIR` and not committed.

View file

@ -125,11 +125,43 @@ changes the level by -1.3 to +1.8 dB by vowel, so a single vowel is a noisy meas
Plosive: word-initial /b/ closure is the tract wall's voice bar, -29.2 dB re the following vowel, /p/ -40.1 dB (`PlosiveClosureCarriesTheVoiceBarOnlyWhenVoiced`); /bɪn/ closure peak 0.0036 (was 0.0000, below 16-bit
resolution), release 60-95 ms peak 0.0695, vowel 0.129. The wall radiation reads the first-cell pressure of the ladder (R0 + L0), band-limits it to 90-300 Hz and adds it at gain 0.7 (a DESIGN value for a voice-bar
level of -30 dB; the primary level was not retrieved, and the 2.4 manual's skin radiation, Birkholz & Zhang 2025, is the reference to read). In a vowel the term moves the f0 line by under 1 dB; the 200 and 300 Hz harmonics move up to +1.5 dB on one open vowel (wall-only measurement, Soul pass). The band is two second-order sections, not a brick wall: with the mouth and the velum shut the bar sits about 25 dB down above 300 Hz. The burst
itself (difference of renders with and without `release_flow`) peaks at about 0.006-0.008, -24 dB re the vowel peak; the release peak in the table above is the voicing breaking through as the contact opens. Burst gain 0.06 is a DESIGN VALUE.
itself (difference of renders with and without `release_flow`), before the #47 fix (c0e6b98; see the re-measure below for the post-fix figures), peaked at about 0.006-0.008, -24 dB re the vowel peak; the release peak in the table above is the voicing breaking through as the contact opens. Burst gain 0.06 is a DESIGN VALUE.
Weak spots found in the renders: (1) the vowel level is not steady, it rises for about 100 ms after onset (ɑ: rms 0.028 at 80 ms to 0.079 at 160 ms) so any window early in a vowel
reads low; the cause is not isolated (surface smoothing and the pressure ramp are the suspects). (2) /n/ murmur 2 dB above /m/ (above). (3) The voice bar's level is a design value and its band
Weak spots found in the renders, 2026-11-08 (not re-measured on 2026-11-12 unless named in the next paragraph): (1) the vowel level is not steady, it rises for about 100 ms after onset (ɑ: rms 0.028 at 80 ms to 0.079 at 160 ms) so any window early in a vowel
reads low; the cause is not isolated (surface smoothing and the pressure ramp are the suspects). (3) The voice bar's level is a design value and its band
(90-300 Hz) assumes f0 of 90 Hz and up. (4) Only f0 and level of the first vowel are checked per cue; the cues' perceptual strength is unknown. Everything here is a measurement, nothing was heard.
Re-measure 2026-11-12. The stress, nasal and lax-vowel figures were taken on main c0e6b98, before the #47 burst fix (which does not touch them); the plosive-release bullet gives the c0e6b98 figures as "before" and the main af0e44f figures, after the #47 fix, as "after" (`tools/formant-check/weak_spots.py` over renders from `tools/aqua-listen/kits/tract-weak-spots/render.sh`; the renders reproduce the table above: /ɪ/ 375/2024 Hz, /ʊ/ 486/894 Hz, murmurs -11.81 and -9.64 dB, /i/ in /nibu/ +0.21 dB). Unheard.
- Stress level (100-170 ms of each vowel, stressed against unstressed, f0 rise split from the rest by a render of the unstressed vowel at 148.4 Hz): total i +1.22, ɑ +1.67, u +2.07, e +2.99, o +1.69 dB (mean 1.93, sd 0.60);
the f0 rise alone -0.80, +0.03, +0.17, +1.23, -0.07 dB; the rest (the amplitude factor 1.30 = 2.28 dB nominal, with the longer vowel) +2.02, +1.64, +1.90, +1.76, +1.76 dB (sd 0.14). The scatter between vowels is the f0 rise; the amplitude cue itself is even.
No level the f0 rise cannot move was found cheap, so the five-vowel-mean basis stands (`aqua-body:question:stress-amplitude-calibration-basis`); the rest sits 0.46 dB under the nominal 2.28 dB, cause not isolated.
- Plosive release: a defect was found and fixed. `release_flow` was held at the burst gain from the plosive's gesture on (a surface holds its first value before its first point and its last after its last), so every later contact state made noise:
the difference of the renders with and without `release_flow` peaked at 0.0302 in the final /n/ and tail of /bɪn/ (above its 0.0226 at the release, 81 ms), 0.0126 in /bʊn/; in /nibu/ (flat) the leading /n/ carried it backward: peak 0.0688, rms 0.0067 against the /n/'s own 0.0058.
After the fix (`BurstGainAroundGesture`: zero before and after the plosive, the gain through it; figures from here to the end of the bullet are post-fix, main af0e44f) the same difference is 0.0 from 120 ms after the release and the burst itself is unchanged (0.0226 at 81 ms in /bɪn/). Burst alone, after the fix: /bɪn/ 0.0226 (-15.1 dB re its vowel peak 0.129), /ba/ 0.0142 (-24.0 dB re 0.225), /bʊn/ 0.0130 (-24.3 dB re 0.213),
each falling to a tenth in 15-17 ms; the pre-fix "0.006-0.008, -24 dB" figure above does not hold for /bɪn/. The release peak of the full render (voicing breaking through) is -5.4, -6.3, -5.9 dB re the vowel peak. Test `PlosiveBurstExistsOnlyAroundItsOwnRelease`.
- Nasals: /m/ -11.81 dB, /n/ -9.64 dB re the flanking vowels, Burg N1 295 and 332 Hz. The 2 dB is not harmonic sampling: /n/ minus /m/ is 2.01, 2.17, 2.05, 1.61 dB at f0 110, 140, 170, 200 Hz. Band levels of the murmur (0-400, 400-800, 800-1600, 1600-3200 Hz): /m/ 36.3, 23.6, 21.3, 2.7; /n/ 38.4, 28.2, 16.8, 0.9 dB.
The cause (the shorter oral side branch, 7.1 cm against 9.6 cm from the velum junction) is a candidate, not shown. Open.
- Lax vowels: /ɪ/ and /ʊ/ are in the DSL table (`StoryVowelAreas`) and render in `WordRender` (/bɪn/, /bʊn/, isolated). Burg F1/F2: /ɪ/ 375/2024 against the tube chain 346/1987 (+8.5/+1.8 %), Hillenbrand 429/2034 (-12.5/-0.5 %), Peterson & Barney 392/1993 (-4.3/+1.5 %);
/ʊ/ 486/894 against 478/850 (+1.7/+5.2 %), 469/1123 (+3.7/-20.4 %), 437/1023 (+11.3/-12.6 %). No defect found.
- Burst place, 2026-11-12 (`burst_spectrum` in `tools/formant-check/weak_spots.py`: render minus `--no-burst` render, 20 ms Hann window from the release at 0.65 of the consonant, spectrum smoothed over 400 Hz, peak searched from 1 kHz up, a DESIGN floor; /aCa/, 140 Hz, 48 kHz, explicit plosive descriptors). Before: the burst joined the path input at the glottal end, so place reached it only through the constriction;
peak/centroid /t/ 4172/8729 Hz, /k/ 6984/10218, /p/ 7087/10423 (burst 0.019): /t/ below /k/, the order Chodroff and Wilson 2014 have reversed (t 5216, k 2868, p 2236 Hz). The decision gate said inject. Now a contact whose position has a control surface (made by the first non-labial plosive of a word) injects its burst there: `LadderInjection`, spread over the two cells whose centres bracket the place,
scaled by cell area over first-cell area (the ladder carries flow waves). /t/ 4008/6681 Hz, /d/ 4008/6693, /k/ 3747/9312 (peak 3747 without the floor too); /t/ is above /k/ by 261 Hz, short of the 2348 Hz of the corpus. Burst window peak /t/ 0.160, /k/ 0.148, /p/ 0.019; closure residue under 0.004. Unscaled, the injection made the closure 30 times louder (outside peak 0.058).
/p/ and /b/ keep the glottal end and their Faust source byte for byte (`PlaceTableKeepsLabialAndAlveolarPositions`); their burst peak above 1 kHz is 7087 Hz, above /t/, and below 1 kHz it is a 434 Hz low resonance, not the place cue: the labial site is not moved. Below 1 kHz /t/ and /d/ peak at 480 Hz, the same low resonance. Unheard.
- /t/ closure leak, 2026-11-12 (explicit descriptor, not in the table; /ata/ against /apa/ without burst, closure = 0.2 to 0.65 of the consonant, dB re the mean power of the flanking vowels): the alveolar closure was held at the nasal's 0.03 cm aperture and opened at 0.5, and read -14.3 dB against /p/ -22.1 (the lips seal /p/ whatever the tongue does); the same window with the aperture 0 for the whole gesture, -24.3. A non-labial plosive now holds aperture 0 to 0.65: -24.9 dB (test run) against /p/ -20.4.
- /k/, 2026-11-12 (the same /aka/ frame, closure 0.2 to 0.65 of the consonant, dB re the flanking vowels, burst removed): closure -14.9 dB against /p/ -20.4 and /t/ -24.9; the same closure with the glottal source's flow scale held at 0, -22.7 dB, so the tract seals and the leak is the voicing (150 Hz) the voiceless source still carries, reaching the output through a closure that leaves a short rear cavity. At the /t/ place (cell 36.7) the same /k/ gesture reads -24.8 dB, so it is the place and not the gesture. Silencing voicing in voiceless stops would change /p/ and /t/ (pinned); reported as an unmet criterion, not worked around. Velar place 9.81 cm behind the lips (0.44 of the tract; between /u/ narrowest dorsal section 26, 6.97 cm, and /a/ pharyngeal section 13, 12.14 cm). Burst: peak 0.0506 against the following vowel's 0.1129 (0.45), spectral peak 3100 Hz against Chodroff and Wilson 2014 /k/ 2868 Hz (/t/ 3950 Hz by the same measure); centroid 4626 Hz against /t/ 3629 Hz by the same measure (not judged: no literature centroid retrieved).
Its injected burst peaked at 0.76 of the following vowel's peak at the shared gain 0.06 (/b/ 0.19): `TongueStopBurstGain` 0.03 gives 0.39 (0.0438 against 0.1129). Burst spectrum unchanged by the gain: peak 4011 Hz, centroid 5796 Hz, inside 3.5-7 kHz. Not met: /t/ above /p/ in burst peak (/p/ 7087 Hz above 1 kHz, 434 Hz below): the labial burst is still injected at the glottal end, which this branch pins. /k/ closure at the old 0.44 fraction is not sealed (core -15.7 dB). Unheard.
- /d/, 2026-11-13 (table entry `voiced_alveolar_plosive`, no new mechanism: the `voiced` token selects the voice bar as it does for /b/): its consonant splines are identical to /t/'s (7 of 7: closure, contact, burst site and gain, source level aside), so closure position, duration and burst are /t/'s. Voice bar (word-initial, closure 0.03-0.058 s against the following vowel, deviation): /d/ -28.9 dB, /b/ -29.2, /t/ -38.7, /p/ -40.1; /d/ over /t/ 9.8 dB. Burst spectral peak 3950 Hz for both /d/ and /t/ (Chodroff and Wilson 2014: /d/ 4878, /t/ 5216, so the same place gives the same peak here, 0 Hz apart against their 338). Burst 0.0603 peak at its own release, 0.00002 before and 0.00000 after. The alveolar closure's voice bar does not differ from the labial one at this resolution (0.3 dB), so no number needed tuning. Unheard.
- /l/, 2026-11-13 (gate then build; /ɑlɑ/ at 140 Hz, scaffold durations; no source for English /l/ formants or level is in the mind (`huginn known`), so every target is a DESIGN value from the cut spec: F1 250-400 Hz, F2 1000-1300 Hz, a dip at 2-3 kHz, level -4 to -10 dB re the flanking vowels, no burst). Gate: the ladder holds a lateral's antiresonance but not its parallel channel. A branch port joins the oral path at any cell (here the ridge, 2.555 cm from the lips) and a closed stub path (4 cells, cross-section 1 cm^2, end reflection +1, aperture 0) beside a sustained /ɑ/ notches the harmonics: stub 2.5 cm -12.3 dB at 2940 Hz, 3.0 cm (the built length) -13.4 dB at 2800 Hz in /ɑlɑ/, 3.6 cm -6.9 dB at 2940 Hz, 4.5 cm -7.9 dB at 2380 Hz, all against the same render with the port shut, which is the render without the stub to 0.0 dB. What the ladder cannot hold is a second oral channel that rejoins the oral path past the contact (a branch has one junction and ends in its own radiation), so the midline is narrowed rather than closed with the flow going round it. Built: the `lateral` token opens the `side_stub` branch for the gesture and narrows the midline to 0.06 cm (held to 0.8), the stub declared in the scaffold only for a word with a lateral (/apa aba ana ata/ keep their script and Faust source byte for byte).
Measured (Burg order 12, 20 ms frames, 0.205-0.255 s; level by RMS of the middle 60 percent re the flanking vowels): level -5.0 dB (band met), F1 263 Hz (met), F2 725 Hz (NOT met: 1000-1300; the narrowed tongue-tip constriction on the /ɑ/ body has no dorsal control to raise it), dip 13.4 dB under the stub-shut render at 2800 Hz (met), burst none (the render with and without release_flow is the same render). The midline diameter is a steep and non-monotonic lever on level and on formants together, so level and F1/F2 could not be set independently: midline 0.028 cm reads -7.2 dB but the spectrum is the sealed-tract leak (energy under 1 kHz, no F2); 0.04 -2.6; 0.05 -5.8 (F1 202); 0.06 -5.0 (F1 263, F2 725); 0.065 -2.5; 0.07 +0.4; 0.08 -0.5 (F1 287, F2 713); 0.15 -0.9 (F1 463, F2 737). Unheard.
- Phones the tract cannot make: `WordRender` refuses a phone outside the table with exit 4 (`UNSUPPORTED PHONES (the tract has no gesture for them; nothing rendered): <ipa>`); the table holds p b t d k m n l s z ʃ ʒ ʍ w and the Story vowels. A direct `phoneme_gesture` on an unknown IPA symbol still falls back to an alveolar approximant (`GestureDescriptor`); not changed here.
Burst-window mutants (hand-applied in a scratch worktree on af0e44f plus the cut, never committed, 2026-11-12; `BurstGainAroundGesture`). The rendered test `PlosiveBurstExistsOnlyAroundItsOwnRelease` did not kill any of them, so `PlosiveBurstGainWindowIsOneRampEitherSide` reads the window off the spline (opens one ramp, 0.15 of the gesture, before the plosive; closed one ramp after it):
| Mutant | Rendered test | Window test |
|---|---|---|
| ramp 0.15 x duration to 0 | survived | killed |
| ramp 0.15 x duration to 1.0 x duration | survived | killed |
| last point at start+duration+ramp moved to start+duration+3*ramp | survived | killed |
Mutations (hand-applied, restored, each run against the named tests): pitch ratio ignored, burst removed, burst not shaped by opening, burst gain x20 (0.06 to 1.2), stress duration ignored,
stress pitch ignored, stress amplitude ignored, secondary equal to primary, probe timeline sample rate re-hardcoded to 48000: nine of nine killed. Script: `work/mut-b3.sh` in the aqua workspace.

View file

@ -12,24 +12,20 @@ Two inputs named in the brief could not be read when this was written, and the
grammar is drafted without them. Each is a place to reconcile before the doc is
treated as in force.
- `heimdall-body:follow_up:ratatoskr-creature-projection-v2`: `huginn view`
from instance `aqua` answers `absent` (and `absent` from Eureka's mind on
2026-11-05), and a search of the Heimdall checkout
(`GameCult/Heimdall`, forge, 2026-11-02) found no file mentioning it. The
constraints taken from the brief are used as stated there: coarse buckets,
neutral overrides, activity comes from the Heimdall session. Section 2 is the
place that must be reconciled against that follow-up's actual field list.
- `ratatoskr:follow_up:symphony-grammar-harvest-mimir` (Mimir birdsong
research): absent from aqua's mind, but it is in force in Eureka's mind
(read 2026-11-05, after this draft was written). It points at Mimir's
`docs/bioacoustic-timeline-watermark.md`, `research/bioacoustic-contestants-2026-05-24.md`
and `calibration/bioacoustic/` (at `c6f4541`), which this draft does not cite
and nobody has read for it. The earlier grep of `GameCult/Mimir` for a
symphony or voice-separation note found none; it did not look for bioacoustic research.
Section 4 is therefore built from this repo's own `research/syrinx-modeling`
plus the general auditory-scene-analysis and acoustic-niche literature named
there, *recalled, not re-read for this draft*. The harvest is still owed and
is the likeliest thing to change section 4.
- `heimdall-body:follow_up:ratatoskr-creature-projection-v2`: the follow-up
document still answers `absent` from aqua (re-checked 2026-11-14). Its content
reached aqua as a spec relayed from #minds on 2026-11-14 (follow-up
`aqua-body:follow_up:chat-s8119-8119`): per participant `{id, estate,
sizeBucket, neutral, activity}`, spec only, Bifrost not cut. Section 2 is
reconciled against that relay, not against the Heimdall document; where the
two could differ, the Heimdall document wins and this doc follows.
- The Mimir harvest (`ratatoskr:follow_up:symphony-grammar-harvest-mimir`) is now
readable: [`docs/gamecult/symphony-grammar-harvest.md` in GameCult/Ratatoskr at
`39c99240`](https://eureka.gamecult.org/forge/GameCult/Ratatoskr/src/commit/39c99240420736a6d064a92dc2cc5b2624efa529/docs/gamecult/symphony-grammar-harvest.md)
(Void's read of GameCult/Mimir at `c6f4541`, as corrected by Ratatoskr #160;
that commit is on Ratatoskr `main`, and the
harvest was merged without a Soul pass). Section 4.1
reconciles against both. The first draft of section 4 predates them.
Context actually read: `docs/gamecult/ratatoskr-target.md` in `GameCult/Ratatoskr`
at `b33d8de` (the agreement that one activity vocabulary drives both sound and
@ -53,73 +49,128 @@ this document, not as a private side channel.
Typed CultNet/CultCache document, projected member-safe. No private pipe: the
frame reaches both consumers by the same subscription, and a consumer that
cannot read it plays nothing and draws the neutral pose.
cannot read it plays nothing and draws nothing.
| field | type | values | note |
|---|---|---|---|
| `mind` | id | instance name | stable identity, not a run/session label |
| `kind` | enum, 7 | `Idle`, `Reading`, `Thinking`, `Working`, `Speaking`, `Waiting`, `Alert` | coarse; see below |
| `energy` | enum, 4 | `Low`, `Mid`, `High`, `Peak` | coarse bucket of rate/intensity, never a float |
| `seq` | u32 | monotonic per `mind` | ordering and staleness; consumers drop `seq <= last` |
| `at` | time bucket | 1 s resolution | producer's observation time, for the staleness rule |
| `override` | enum, 3 | `None`, `Neutral`, `Muted` | see rules O1..O3 |
| `id` | id | participant identity | stable identity, not a run/session label; for a human, the member's stable id (prose below says "mind" for the participant an `id` names) |
| `estate` | enum, 3 | `human`, `mind`, `persona` | selects the vocabulary this participant may use; see below |
| `sizeBucket` | enum, 3 | `Small`, `Medium`, `Large` | coarse size bucket for the creature; scale per bucket is not fixed here; absent when `neutral` (O1) |
| `neutral` | bool | | separate flag that overrides any `sizeBucket`: no size drawn or carried; when set, `activity` and `sizeBucket` are omitted, see O1 |
| `activity` | struct | `kind` (enum, 7; humans: 3) and `energy` (enum, 4; humans: 3) | produced by the Heimdall session; absent when `neutral`; see below |
Why this small: 7 x 4 = 28 states fit in one byte on the wire and in a lookup
table on a phone; both consumers map state to behaviour by table, no arithmetic
on unbounded values. `kind` and `energy` are orthogonal on purpose, because
`kind` is one of `Idle`, `Reading`, `Thinking`, `Working`, `Speaking`, `Waiting`,
`Alert`; `energy` is a coarse bucket, `Low`, `Mid`, `High`, `Peak`, never a float.
These five fields are the whole participant projection. The previous draft also
carried `seq`, `at` and `override`; they are gone from the frame. Ordering and
observation age (rules S1, S2) are **needed from the feed envelope**, which
`ratatoskr:question:activity-feed-source` owns, and are an unconfirmed
assumption: if the feed cannot supply them, S1 and S2 cannot be implemented and
that is raised there, not patched by a sixth field. `Muted` is no longer frame
data (O2).
Why this small: 7 x 4 = 28 states (the Mind/Persona set) fit in one byte on the
wire and in a lookup table on a phone; both consumers map state to behaviour by
table, no arithmetic on unbounded values. `kind` and `energy` are orthogonal on purpose, because
orbit radius/speed wants energy and voice choice wants kind.
### Estate
`estate` is set by the producer, never inferred by a consumer, and bounds what
the other fields may carry (per
`heimdall-body:follow_up:ratatoskr-creature-projection-v2`):
- **`human`: coarse only.** `energy` is capped at 3 buckets (`Low`, `Mid`,
`High`; no `Peak`) and `kind` is the **human subset** `Idle`, `Working`,
`Speaking` (*proposed*). The subset is strictly smaller than the Mind/Persona
set and chosen to reveal less, never more: it omits `Reading`, `Thinking`,
`Waiting` and `Alert`, which describe what a participant is attending to or
how it is faring. A producer must not emit a `kind` or `energy` outside the
human set for a human. A consumer that receives one clamps it: an omitted
`kind` maps to `Idle`, `Peak` maps to `High`. Clamping only ever reveals
less. A human's `kind` that is present but not an enum value at all clamps
to `Idle` (reveal-less) for a non-neutral human; for `mind` and `persona` an
unknown `kind` is malformed and the frame is dropped (A4).
The relayed projection says humans get the coarse bucket by default, with a
typed opt-out setting `neutral`, and that Minds and Personas may show finer
buckets. It does not name the three-`kind` subset: that subset is this
grammar's proposal for "coarse", and stays *proposed* until Heimdall's
document names it or replaces it.
- **`mind` and `persona`: the finer 7 x 4 set** (all seven `kind`, all four
`energy` buckets).
`sizeBucket` is three coarse buckets (`Small`, `Medium`, `Large`) and the
projection carries it for every estate except a `neutral` participant (O1).
Heimdall's projection lets a Mind or Persona show finer buckets than a human;
this grammar does not consume `sizeBucket` for sound at all, so the count is not
decided here and a finer set changes nothing in sections 3 to 5. The scale each
bucket draws at is **not fixed by this grammar**: the values 0.7 / 1 / 1.4 are
Ratatoskr placeholders, owned by the orbit renderer, and may change without
touching the frame. Exact vote weights, from which a bucket is derived, never
leave Bifrost and are never in the frame.
Rules:
- **A1. Source.** The frame comes from the Heimdall session and only from it.
Neither consumer infers activity from Matrix presence, typing, message
traffic, or audio. (The target already notes presence/typing are too coarse
for Minds.) *Reconcile the exact kind list against the projection-v2
follow-up before use.*
traffic, audio, or the room member list. Activity is a stub fed by the Heimdall
session; being in a room says nothing about being active. (The target already notes presence/typing are too coarse
for Minds.) *The kind list for Minds and Personas stays as relayed; the human subset is proposed (section 2).*
- **A2. Coarse by construction.** There is no continuous field in the frame. A
renderer that wants smooth motion interpolates between buckets locally; it
does not request finer data.
- **A3. Member-safe.** The frame carries kind, Mind, time and energy bucket.
Never brief text, document ids, claims, or mind contents.
- **A3. Member-safe.** The frame carries `id`, `estate`, `sizeBucket`, `neutral`
and `activity`, and nothing else; when `neutral` is set, `activity` and
`sizeBucket` are stripped (O1). Exact vote weights never leave Bifrost. Never brief text,
document ids, claims, or mind contents.
- **A4. Missing is Idle.** No frame within the staleness window (section 5, S2)
means `Idle`/`Low`, rendered and sounded as nothing. Silence is the default
state, not a failure state.
means `Idle`/`Low`: no voice, and the orbit at rest. Silence is the default
state, not a failure state. Missing is not `neutral`: an absent frame is an
idle participant, a `neutral` participant is not drawn at all (O1).
### Overrides
- **O1. `Neutral`** (set by the session or by the member's own setting): the
Mind renders at the neutral pose and contributes no voice, regardless of
`kind`/`energy`. Neutral is not an error; it hides activity, it does not
pretend there is none to other consumers.
- **O2. `Muted`**: no voice, orbit unchanged. Lets a listener silence one Mind
without hiding its motion.
- **O3.** Overrides are data in the frame, set upstream. A consumer never
applies a local override and then reports it as the Mind's state. (A *user's*
own mute/volume is a client preference and stays local; it never rewrites a
frame.)
- **O1. `neutral`** (the flag, set by the session or by a human's own typed
opt-out setting): a Neutral participant gets **no orbit and no voice**, and the
frame **strips `activity` and `sizeBucket` as well**: the producer omits both, and a consumer ignores them if present. An opted-out participant
reveals nothing, not even coarse activity or a coarse size bucket. It draws nothing and sounds nothing; there is no
"neutral pose" to render. Neutral overrides every `sizeBucket` bucket: none is drawn or carried, and no sound carries a size cue either. Neutral is
not an error and not Idle: the frame says only that this participant is not
shown.
- **O2. Muting one Mind** is a listener's client preference, not frame data:
no voice, orbit unchanged. It lets a listener silence one Mind without hiding
its motion, and it never appears in, or rewrites, a frame.
- **O3.** `neutral` is data in the frame, set upstream (by the session or by a
human's own typed setting). A consumer never applies a local override of it and
then reports that as the participant's state. Neutral means no size cue and
no activity cue, in sound as in the orbit: the voice scheduler gives a `neutral`
participant nothing to sound.
## 3. Mapping tables (shape only)
The grammar defines the mapping *axes*, not the values. Each consumer owns one
table keyed by the 28 states; the tables are checked in beside this document
table keyed by the 28 Mind/Persona states (humans use the 3 x 3 subset); the tables are checked in beside this document
when values exist.
| axis | owner | driven by | notes |
|---|---|---|---|
| orbit **existence** (drawn or not) | orbit renderer | `neutral` | `neutral` set: no orbit |
| orbit radius / speed / phase coupling | orbit renderer | `energy`, `kind` | Nibu's side; not specified here |
| voice **presence** (sounding or silent) | voice scheduler | `kind` | `Idle`, `Waiting` default silent |
| creature scale | orbit renderer | `sizeBucket` | per-bucket scales are renderer placeholders, not fixed here |
| voice **presence** (sounding or silent) | voice scheduler | `neutral`, `kind` | `neutral` set: no voice, regardless of `kind`; `Idle`, `Waiting` default silent |
| voice **density** (events per window) | voice scheduler | `energy` | capped, section 5 |
| voice **role** (lead / support / texture) | voice scheduler | `kind` | role, not instrument |
| voice **identity** (which instrument) | voice scheduler | `mind` | never `kind`; section 4 |
| voice **identity** (which instrument) | voice scheduler | `id` | never `kind`; section 4 |
The one rule that ties the two consumers: **`mind` selects identity, `kind`
The one rule that ties the two consumers: **`id` selects identity, `kind`
selects behaviour, `energy` selects amount.** A given Mind sounds like itself
in every state; what it does changes.
## 4. Keeping voices distinct when mixed
Principle, from the acoustic-niche and auditory-scene-analysis literature
(recalled, to be confirmed by the Mimir harvest): voices that share a niche in
(recalled; the Mimir harvest gives it no support or contradiction, see 4.1): voices that share a niche in
frequency, time and space mask each other; voices that differ on several
independent axes stay separable even at high density. Assign each Mind a
distinct **niche** on independent axes, and make the scheduler protect those
@ -140,7 +191,7 @@ niches. Axes:
Rules:
- **V1. Identity is stable.** The niche (axes 1-4) is a function of `mind`
- **V1. Identity is stable.** The niche (axes 1-4) is a function of `id`
only. It never moves with `kind`, `energy`, or which other Minds are present.
A listener learns a Mind once.
- **V2. Niche table is data**, held beside the Mind's other typed state
@ -161,6 +212,66 @@ Rules:
accepted until a listener-identification trial passes (the existing
notification ledger requires the same). That trial has not happened.
### 4.1 Reconciled against the Mimir harvest
Read: the harvest at `39c99240` (linked in section 0; not copied here), in the
wording of Ratatoskr #160, Void's corrections to it. Rows are cited below by what
they say, not by number.
What the corrections change here:
- **The six-syllable packet song is Aqua's design choice, not Mimir's result.**
The harvest's "best contestant" claim (canary-packet-trill) is
confidence B, a hypothesis; Mimir's production word is the four-syllable,
118 ms word. If this grammar adopts a six-syllable packet song, it does so by
its own choice at confidence B, and it is a thing to try in the listener trial,
not a measured recommendation. Nothing in section 4 depends on it.
- **Do not rest a niche on Mimir's identity figure.** The harvest's 0.908-0.997
is a clean-input identity range. Per #160 the degraded numbers have a receipt,
but a narrow one: identity 0.532-0.908 and timing 0.187-0.728 for the
`compact-fast-index` hypothesis only, across four degraded cases
(`artifacts/bioacoustic-training/bioacoustic-20260524-150729/compact-fast-index/*/summary.json`,
synthetic damage). #160's description (not the harvest text) adds that other
hypotheses in that run range wider (identity to 0.998, timing to 0.807). The earlier relayed
"0.5-0.9" is replaced by this scoped range. These are one decoder's scores on synthetic damage, not a
property of any song, and no rule in section 4 or 5 depends on them.
- **The "event slot repeats about every 41 s" figure is derived, not measured.**
#160 says no receipt or doc states it: it is 128 words x 2 speakers = 256
events at 0.16 s spacing = 40.96 s, read from Mimir's code. No rule here
depends on it.
- **The "too-short songs collapse" thresholds are not a design floor for this
grammar.** The harvest's own row reports them from one blur case under two
decoders (blur-light 4.358 with the razor decoder, 218.368 with the sprint
decoder), so they are decoder-dependent evidence on synthetic damage, not a
threshold for human listening.
- **A word identifies an event slot, not a source** (the harvest's event-slot row). Mimir's evidence
does not support "the instrument says who spoke" (V1, axis 2). That stays a
design rule of this grammar, to be tested by V6, with no Mimir backing.
- **No harmony evidence exists.** Mimir emits one low-gain song at a time and
tests no simultaneous voices, intervals, consonance or masking between
concurrent songs. V3 (voice cap), V4 (collision backoff) and V5 are Aqua's
design and rest on the recalled auditory-scene-analysis literature alone.
- **No pleasantness evidence exists.** Mimir's score is decodability by a machine
decoder against a known schedule; its gain was chosen for low audibility. Whether
any song, harmony or niche table is pleasant or distinguishable to a person is
unmeasured. **A listener trial is owed** (V6, section 7) and has not happened;
nothing here is heard.
What the harvest does support, as design constraints already in this section's
spirit and still unmeasured for people: identity carried redundantly across
several channels at once, no sequence grammar for identity, irregular rather
than ladder-like rhythm, a deterministic generator authored once and rendered
(S4 already says the client ships rendered assets). Its open question "which
dimension bends with activity" is what section 3's rule answers by design:
`id` selects identity, `kind` behaviour, `energy` amount, so a Mind keeps one
timbre and root for life and the contour and density move; Mimir has no activity
channel to confirm that.
The **human `kind` subset** (`Idle`, `Working`, `Speaking`, section 2) is not
touched by the harvest: Mimir carries no activity or privacy channel at all, so
the subset still rests only on the projection-v2 follow-up, which remains
unreadable from aqua (below).
## 5. Timing, staleness and the callback deadline
Hard rule: **the audio callback deadline wins over everything in this
@ -168,7 +279,7 @@ document.** The callback never waits on the grammar, the network, a decode, an
allocation, or a lock.
- **C1. Frame handoff is a snapshot.** The network/projection thread writes the
latest frame per `mind` into a preallocated table; the scheduler thread reads
latest frame per `id` into a preallocated table; the scheduler thread reads
it and writes a preallocated voice-command queue; the audio callback only
reads that queue. No thread but the callback touches the output buffer; the
callback never blocks on, or is blocked by, the others (single-producer
@ -176,9 +287,9 @@ allocation, or a lock.
- **C2. Drop, never delay.** If the queue is full or the scheduler is late, the
frame or command is dropped. A late sound is not played to catch up and its
internal timing is never stretched.
- **S1. Latest wins.** Per `mind`, only the newest `seq` matters. Intermediate
- **S1. Latest wins.** Per `id`, only the newest frame by the feed envelope's ordering matters (the frame itself carries none; see section 2). Intermediate
frames missed during a stall are not replayed.
- **S2. Staleness.** A frame older than **10 s** (*proposed*) is treated as
- **S2. Staleness.** A frame whose envelope age exceeds **10 s** (*proposed*) is treated as
absent (rule A4). Sounding on stale activity is misleading.
- **S3. Rate.** Voice density per `energy` is bounded by a ceiling per Mind per
window (*proposed*, set with the device measurement); rule V3 bounds the
@ -192,7 +303,8 @@ allocation, or a lock.
renderer's pause (the target already pauses the background when hidden). On
resume, S1/S2 apply; there is no catch-up burst.
- **S6. Failure is silent.** No frame source, a dead scheduler, a refused
autoplay, or a full queue all produce silence and neutral pose. Nothing
autoplay, or a full queue all produce silence, with the orbit at rest. A
failure is not a `neutral` participant and does not remove the creature. Nothing
retries, alerts, or alters the frame source.
## 6. What this grammar does not decide
@ -209,8 +321,8 @@ allocation, or a lock.
None run. To be done before the grammar leaves draft:
1. Reconcile section 2 with `heimdall-body:follow_up:ratatoskr-creature-projection-v2`.
2. Reconcile section 4 with the Mimir harvest.
1. Section 2 is reconciled with the relayed projection-v2 spec (2026-11-14, five fields), not with the Heimdall document itself, which is still `absent` from aqua. Still owed: read that document when it is readable; confirm the feed envelope can supply per-participant ordering and age (S1, S2); get the human `kind` subset named or replaced by Heimdall (it is *proposed* here).
2. ~~Reconcile section 4 with the Mimir harvest.~~ Done in 4.1 (docs only; no listening). What the harvest could not give (harmony, pleasantness, discriminability by a person) goes to item 5.
3. Round-trip the frame as a CultCache document and check the size claim (one
byte per state, 28 states).
4. Measure voice cap, density ceilings and scheduler cost on a real phone.
@ -218,5 +330,5 @@ None run. To be done before the grammar leaves draft:
## 8. Status
Draft. Not implemented. No code changed. No audio was produced and none is
Draft, reconciled with the Mimir harvest (4.1) and with the relayed projection-v2 five-field spec (section 2) on 2026-11-14; the human `kind` subset is still proposed. Not implemented. No code changed. No audio was produced and none is
claimed.

View file

@ -31,7 +31,7 @@ voice
phaser=0.0001458
phaser_ramp=-0.000504
patch repeat=0.174744
patch gain=0.5
voice
use=Noise
freq=20
@ -48,7 +48,6 @@ voice
tremolo=0.0264
tremolo_hz=13.04
patch repeat=0.11315
voice
wave=sine
freq=57.5946

View file

@ -3,7 +3,6 @@
# Source: BuiltInScripts.ReferenceScripts
# Notes: Stock reference patch exported from the in-code catalog.
patch repeat=0.174744
voice
wave=noise
freq=20

View file

@ -89,7 +89,6 @@ public static class BuiltInScripts
drive=0.12
"""),
("explosion", """
patch repeat=0.174744
voice
wave=noise
freq=20
@ -188,7 +187,7 @@ public static class BuiltInScripts
phaser=0.0001458
phaser_ramp=-0.000504
patch repeat=0.174744
patch gain=0.5
voice
use=Noise
freq=20
@ -205,7 +204,6 @@ public static class BuiltInScripts
tremolo=0.0264
tremolo_hz=13.04
patch repeat=0.11315
voice
wave=sine
freq=57.5946

View file

@ -27,7 +27,8 @@ public sealed record CultCachePatchDatabaseEntry(
[property: Key(1)] string Family,
[property: Key(2)] string Name,
[property: Key(3)] string Source,
[property: Key(4)] string Notes);
[property: Key(4)] string Notes,
[property: Key(5), CultElementId("Path")] string ElementId = "");
[MessagePackObject]
public sealed record CultCachePatchClaimCard(
@ -36,7 +37,8 @@ public sealed record CultCachePatchClaimCard(
[property: Key(2)] CultCacheReferenceTruth Reference,
[property: Key(3)] CultCacheIntentTruth Intent,
[property: Key(4)] string Tier,
[property: Key(5)] CultCacheProofTruth Proof);
[property: Key(5)] CultCacheProofTruth Proof,
[property: Key(6), CultElementId("Id")] string ElementId = "");
[MessagePackObject]
public sealed record CultCacheSpeechClaimCard(
@ -45,7 +47,8 @@ public sealed record CultCacheSpeechClaimCard(
[property: Key(2)] CultCacheSpeechTargetTruth Target,
[property: Key(3)] CultCacheIntentTruth Intent,
[property: Key(4)] string Tier,
[property: Key(5)] CultCacheProofTruth Proof);
[property: Key(5)] CultCacheProofTruth Proof,
[property: Key(6), CultElementId("Id")] string ElementId = "");
[MessagePackObject]
public sealed record CultCacheReferenceTruth(

View file

@ -30,6 +30,13 @@ public static partial class FaustEmitter
public string Refl(int i) => $"{Prefix}_r{i}";
}
// A flow that enters the path at a cell rather than at the glottal end: Position is a Faust expression for the normalized place (0 glottis,
// 1 lips) and Flow the signal as it would enter the first cell. It is spread over the two cells whose centres bracket the place (a hat of
// width one cell), so the place can move between gestures and a place at or behind the first cell centre is the glottal end. The ladder
// carries flow waves, so the same noise pressure in a cell of area A is a flow of Flow * A / A(first cell): a burst at the closure,
// where the area is nearly zero, is small until the constriction opens (measured: unscaled it was 30 times louder in the closure).
private sealed record LadderInjection(string Position, string Flow);
private sealed record LadderJunction(LadderPath Oral, LadderPath Branch, int Interface, string Velum, string Left, string Right, string Nose);
private static int LadderCells(WaveguidePath path, TractAreaFunction shape, FaustExportOptions options) =>
@ -47,6 +54,7 @@ public static partial class FaustEmitter
string name,
IReadOnlyList<LadderPath> members,
IReadOnlyDictionary<string, string> inputs,
IReadOnlyDictionary<string, IReadOnlyList<LadderInjection>> injections,
IReadOnlyDictionary<string, string> admittances,
ParameterMap parameters,
List<string> warnings)
@ -88,6 +96,15 @@ public static partial class FaustEmitter
foreach (var member in members)
{
var targetJunction = targets.GetValueOrDefault(member);
var sites = new List<(string Site, string Flow)>();
foreach (var injection in injections.GetValueOrDefault(member.Path.Name) ?? [])
{
var site = $"{member.Prefix}_injection{sites.Count}_site";
source.AppendLine($" {site} = min({F(member.Cells - 0.5f)}, max(0.5, ({injection.Position}) * {F(member.Cells)}));");
sites.Add((site, injection.Flow));
}
string Injected(int cell) => string.Concat(sites.Select(entry => $" + max(0.0, 1.0 - abs({F(cell + 0.5f)} - {entry.Site})) * ({entry.Flow}) * {member.A(cell)} / {member.A(0)}"));
for (var i = 0; i < member.Cells; i++)
{
if (i == 0 && targetJunction is not null)
@ -113,12 +130,12 @@ public static partial class FaustEmitter
equations.AppendLine(targetJunction is { } entering
? $" '{member.R(0)} = ({entering.Oral.L(entering.Interface)} + {entering.Oral.R(entering.Interface - 1)}) * (1.0 + {entering.Nose}) * {loss} + {entering.Nose} * {member.L(0)} * {loss};"
: $" '{member.R(0)} = ({member.L(0)} * {F(LadderGlottalReflection)} + {(inputs.TryGetValue(member.Path.Name, out var input) ? input : "0.0")}) * {loss};");
: $" '{member.R(0)} = ({member.L(0)} * {F(LadderGlottalReflection)} + {(inputs.TryGetValue(member.Path.Name, out var input) ? input : "0.0")}{Injected(0)}) * {loss};");
for (var i = 1; i < member.Cells; i++)
{
equations.AppendLine(joinedAt.TryGetValue((member, i), out var join)
? $" '{member.R(i)} = ({join.Right} * {member.L(i)} + (1.0 + {join.Right}) * ({member.R(i - 1)} + {join.Branch.L(0)})) * {loss};"
: $" '{member.R(i)} = ({member.R(i - 1)} - {member.Refl(i)} * ({member.R(i - 1)} + {member.L(i)})) * {loss};");
: $" '{member.R(i)} = ({member.R(i - 1)} - {member.Refl(i)} * ({member.R(i - 1)} + {member.L(i)}){Injected(i)}) * {loss};");
}
for (var i = 0; i < last; i++)

View file

@ -29,12 +29,10 @@ public static partial class FaustEmitter
if (patch.Repeat is { } repeat)
{
var interval = parameters.Expression("/patch/repeat", repeat.IntervalSeconds);
source.AppendLine($"age = time - floor(time / {interval}) * {interval};");
}
else
{
source.AppendLine("age = time;");
// sfxr's repeat restarts the pitch slide and the arpeggio, not the envelope: age keeps running, the voices wrap their pitch age.
source.AppendLine($"repeat_interval = {interval};");
}
source.AppendLine("age = time;");
source.AppendLine("clip01(x) = min(1.0, max(0.0, x));");
source.AppendLine("wrap01(x) = x - floor(x);");
source.AppendLine("slew(rate,x) = x : *(1.0 - exp((0.0 - max(0.0001, rate)) / ma.SR)) : + ~ *(exp((0.0 - max(0.0001, rate)) / ma.SR));");
@ -47,6 +45,15 @@ public static partial class FaustEmitter
source.AppendLine("bez(t,a,b,c,d) = (1.0 - t) * (1.0 - t) * (1.0 - t) * a + 3.0 * (1.0 - t) * (1.0 - t) * t * b + 3.0 * (1.0 - t) * t * t * c + t * t * t * d;");
source.AppendLine("seg_bez(t,t0,d,a,b,c,e) = bez(clip01((t - t0) / max(0.0001, d)), a, b, c, e);");
source.AppendLine("smooth01(x) = clip01(x) * clip01(x) * (3.0 - 2.0 * clip01(x));");
// si.smoo starts every control at 0 and climbs to it: a word began with the tract shut, the vowel weights at 0 and the source off,
// and the first ~100 ms of every render were that climb (the level rose 40 dB over the first 100 ms of an isolated vowel, and
// the bandwidths fell from ~300 Hz to 90). smoo_from starts at its input and smooths from there. smoo_init is si.smoo's own
// pole (1 - 44.1 / SR, a 22.7 ms time constant), so live control moves exactly as fast as before; only the start differs.
// Started at its input a constant control holds there to the bit; started at 0 (si.smoo, si.smooth) it stalls 1e-5 to 5e-5 short of it,
// in either way of writing the step. The source's pitch-ratio smoother starts at its input for that reason: from 0 the 2744 Hz alias
// source ran 0.12 Hz flat and leaked its harmonics into the alias measurement.
source.AppendLine("smoo_from(pole, x) = loop ~ _ with { loop(prev) = select2(1 - 1', prev * pole + x * (1.0 - pole), x); };");
source.AppendLine("smoo_init(x) = smoo_from(1.0 - 44.1 / ma.SR, x);");
source.AppendLine("seg_smooth(t,t0,d,a,b) = a + (b - a) * smooth01((t - t0) / max(0.0001, d));");
source.AppendLine("seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));");
source.AppendLine("seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));");
@ -154,7 +161,7 @@ public static partial class FaustEmitter
var baseId = $"{id}_base";
var normalized = $"{id}_normalized";
var physical = $"{id}_physical";
var publicControl = $"hslider(\"{Escape(surface.Path)}\", {F(surface.DefaultNormalized)}, 0, 1, 0.001) : si.smoo";
var publicControl = $"hslider(\"{Escape(surface.Path)}\", {F(surface.DefaultNormalized)}, 0, 1, 0.001) : smoo_init";
var boundControl = parameters.TryBindingExpression(surface.FieldPath, out var bindingExpression)
? $"clip01(({bindingExpression} - {F(surface.MinValue)}) / max(0.000001, {F(surface.MaxValue - surface.MinValue)}))"
: publicControl;
@ -174,7 +181,7 @@ public static partial class FaustEmitter
var splineId = $"{id}_spline_{splineIndex}";
EmitControlSpline(source, spline, splineId, surface.DefaultNormalized);
var depth = $"{splineId}_depth";
source.AppendLine($"{depth} = hslider(\"/splines/{Escape(spline.Name)}/depth\", 1, 0, 1, 0.001) : si.smoo;");
source.AppendLine($"{depth} = hslider(\"/splines/{Escape(spline.Name)}/depth\", 1, 0, 1, 0.001) : smoo_init;");
terms.Add($"(({splineId}_value - {F(surface.DefaultNormalized)}) * {depth})");
}
@ -199,11 +206,11 @@ public static partial class FaustEmitter
{
var point = points[i];
source.AppendLine($"{splineId}_p{i}_time = hslider(\"/splines/{Escape(spline.Name)}/{i}/time\", {F(point.TimeSeconds)}, 0, 120, 0.001);");
source.AppendLine($"{splineId}_p{i}_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/value\", {F(Math.Clamp(point.Value, 0, 1))}, 0, 1, 0.001) : si.smoo;");
source.AppendLine($"{splineId}_p{i}_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/value\", {F(Math.Clamp(point.Value, 0, 1))}, 0, 1, 0.001) : smoo_init;");
source.AppendLine($"{splineId}_p{i}_out_time = hslider(\"/splines/{Escape(spline.Name)}/{i}/out_time\", {F(Math.Max(0, point.OutTimeOffsetSeconds))}, 0, 10, 0.001);");
source.AppendLine($"{splineId}_p{i}_out_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/out_value\", {F(point.OutValue == 0 ? point.Value : Math.Clamp(point.OutValue, 0, 1))}, 0, 1, 0.001) : si.smoo;");
source.AppendLine($"{splineId}_p{i}_out_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/out_value\", {F(point.OutValue == 0 ? point.Value : Math.Clamp(point.OutValue, 0, 1))}, 0, 1, 0.001) : smoo_init;");
source.AppendLine($"{splineId}_p{i}_in_time = hslider(\"/splines/{Escape(spline.Name)}/{i}/in_time\", {F(Math.Max(0, point.InTimeOffsetSeconds))}, 0, 10, 0.001);");
source.AppendLine($"{splineId}_p{i}_in_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/in_value\", {F(point.InValue == 0 ? point.Value : Math.Clamp(point.InValue, 0, 1))}, 0, 1, 0.001) : si.smoo;");
source.AppendLine($"{splineId}_p{i}_in_value = hslider(\"/splines/{Escape(spline.Name)}/{i}/in_value\", {F(point.InValue == 0 ? point.Value : Math.Clamp(point.InValue, 0, 1))}, 0, 1, 0.001) : smoo_init;");
}
if (points.Length == 1)
@ -325,6 +332,9 @@ public static partial class FaustEmitter
? $"{voiceAge} = wrap01(age / {F(voice.Note.TriggerIntervalSeconds)}) * {F(voice.Note.TriggerIntervalSeconds)};"
: $"{voiceAge} = age;");
var pitchAge = patch.Repeat is null ? voiceAge : $"{name}_pitch_age";
if (patch.Repeat is not null) source.AppendLine($"{pitchAge} = {voiceAge} - floor({voiceAge} / repeat_interval) * repeat_interval;");
var minFreq = parameters.Expression(OwnerField(ownerPath, "pitch/min_freq"), voice.Pitch.MinFrequencyHz);
var noteFreq = NoteFrequencyExpression(source, patch.Playback, voice.Note, name, OwnerField(ownerPath, "note/frequency"), parameters);
var noteGate = NoteGateExpression(source, patch.Playback, voice.Note, name, OwnerField(ownerPath, "note/gate"), parameters);
@ -333,7 +343,7 @@ public static partial class FaustEmitter
var vibratoDepth = parameters.Expression(OwnerField(ownerPath, "pitch/vibrato"), voice.Pitch.VibratoDepth);
var vibratoHz = parameters.Expression(OwnerField(ownerPath, "pitch/vibrato_hz"), voice.Pitch.VibratoHz);
var vibratoDelay = parameters.Expression(OwnerField(ownerPath, "pitch/vibrato_delay"), voice.Pitch.VibratoDelaySeconds);
var baseFreq = $"max({minFreq}, {noteFreq} * pow(2.0, {pitchRamp} * {voiceAge} + 0.5 * {pitchDelta} * {voiceAge} * {voiceAge}))";
var baseFreq = $"max({minFreq}, {noteFreq} * pow(2.0, {pitchRamp} * {pitchAge} + 0.5 * {pitchDelta} * {pitchAge} * {pitchAge}))";
var hasVibrato = voice.Pitch.VibratoDepth != 0 && voice.Pitch.VibratoHz > 0 ||
parameters.IsBound(OwnerField(ownerPath, "pitch/vibrato")) ||
parameters.IsBound(OwnerField(ownerPath, "pitch/vibrato_hz"));
@ -342,7 +352,7 @@ public static partial class FaustEmitter
: "";
var arpeggio = voice.Arpeggio is null
? "1.0"
: $"select2({voiceAge} < {parameters.Expression(OwnerField(ownerPath, "arpeggio/delay"), voice.Arpeggio.DelaySeconds)}, {parameters.Expression(OwnerField(ownerPath, "arpeggio/multiplier"), voice.Arpeggio.Multiplier)}, 1.0)";
: $"select2({pitchAge} < {parameters.Expression(OwnerField(ownerPath, "arpeggio/delay"), voice.Arpeggio.DelaySeconds)}, {parameters.Expression(OwnerField(ownerPath, "arpeggio/multiplier"), voice.Arpeggio.Multiplier)}, 1.0)";
var frequency = $"(({baseFreq}){vibrato}) * {arpeggio} * pow(2.0, patch_mod_pitch + {pitch})";
var dutyExpression = $"clip01({parameters.Expression(OwnerField(ownerPath, "osc/duty"), voice.Oscillator.Duty)} + {parameters.Expression(OwnerField(ownerPath, "duty/ramp"), voice.Duty.RampPerSecond)} * {voiceAge} + patch_mod_duty + {duty})";
var fmIndex = $"max(0.0, {parameters.Expression(OwnerField(ownerPath, "fm/index"), voice.Fm.Index)} + patch_mod_fm_index + {fmIndexMod}) * {FmDecay(parameters.Expression(OwnerField(ownerPath, "fm/decay"), voice.Fm.IndexDecaySeconds), voice.Fm.IndexDecaySeconds, parameters.IsBound(OwnerField(ownerPath, "fm/decay")), voiceAge)}";
@ -607,6 +617,7 @@ public static partial class FaustEmitter
// are both in this network is a ladder junction instead and exchanges no flow term.
var memberNames = members.Select(member => member.Path.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
var inputs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var injections = new Dictionary<string, IReadOnlyList<LadderInjection>>(StringComparer.OrdinalIgnoreCase);
foreach (var member in members)
{
var path = member.Path;
@ -617,13 +628,24 @@ public static partial class FaustEmitter
.Where(term => term is not null)
.Cast<string>()
.ToList();
var contactTerms = network.Contacts
.Select(contactName => contacts.TryGetValue(contactName, out var contact) && contact.Path.Equals(path.Name, StringComparison.OrdinalIgnoreCase)
? PrimitiveContactExpression(source, patch, name, contact, parameters, options, keepAlive)
: null)
.Where(term => term is not null)
.Cast<string>()
.ToList();
var contactTerms = new List<string>();
var pathInjections = new List<LadderInjection>();
foreach (var contactName in network.Contacts)
{
if (!contacts.TryGetValue(contactName, out var contact) || !contact.Path.Equals(path.Name, StringComparison.OrdinalIgnoreCase)) continue;
var (released, burst) = PrimitiveContactExpression(source, patch, name, contact, parameters, options, keepAlive);
// A contact that has a position control surface lets its burst go in at that place; one whose place is a fixed number
// keeps the burst at the glottal end with the rest of the path input.
var position = OwnerField($"/vocal/contacts/{ConstrictionContactIndex(patch, contact)}", "position");
if (patch.ControlSurfaces.Any(surface => surface.FieldPath.Equals(position, StringComparison.OrdinalIgnoreCase)))
{
contactTerms.Add(released);
pathInjections.Add(new LadderInjection(parameters.Expression(position, contact.Position), burst));
}
else contactTerms.Add($"({released} + {burst})");
}
injections[path.Name] = pathInjections;
var branchTerms = network.Branches
.Select(branchName => branches.TryGetValue(branchName, out var branch) && branch.FromPath.Equals(path.Name, StringComparison.OrdinalIgnoreCase) && !memberNames.Contains(branch.ToPath)
? PrimitiveBranchExpression(source, patch, name, branch, parameters, options, keepAlive)
@ -649,7 +671,7 @@ public static partial class FaustEmitter
var (lips, glottalPressures) = members.Count == 0
? (new Dictionary<string, string>(), new Dictionary<string, string>())
: EmitVocalLadder(source, patch, network, name, members, inputs, admittances, parameters, warnings);
: EmitVocalLadder(source, patch, network, name, members, inputs, injections, admittances, parameters, warnings);
foreach (var member in members)
{
@ -726,7 +748,9 @@ public static partial class FaustEmitter
var impedance = parameters.Expression(OwnerField(owner, "impedance"), port.Impedance);
var flowScale = parameters.Expression(OwnerField(owner, "flow_scale"), port.FlowScale);
// f0 is the voice frequency times the source's ratio (the stress cue), smoothed over 10 ms so a step in the ratio is a glide.
var pitchRatio = $"({parameters.Expression(OwnerField(owner, "pitch_ratio"), port.PitchRatio)} : si.smooth(ba.tau2pole(0.01)))";
// Its own 10 ms smoother also starts at its input: from 0 it glided the source's pitch up from nothing at the start of every word
// (the control feeding it used to hide that under its own 100 ms climb) and rounded to a value up to ~4e-5 off its input.
var pitchRatio = $"smoo_from(ba.tau2pole(0.01), {parameters.Expression(OwnerField(owner, "pitch_ratio"), port.PitchRatio)})";
var load = $"{voiceName}_primitive_source_{safe}_load_pressure";
var voiced = $"{voiceName}_primitive_source_{safe}_voiced";
var flow = $"{voiceName}_primitive_source_{safe}_flow";
@ -734,15 +758,22 @@ public static partial class FaustEmitter
// Harmonic glottal source: a band-limited saw through a one-pole lowpass. Tilt 0 is the brightest source and 1 the
// steepest rolloff; the cutoff sweeps five octaves, 6400 Hz down to 200 Hz, and sits below Nyquist.
var cutoff = $"min(0.45 * ma.SR, 200.0 * pow(2.0, (1.0 - clip01({parameters.Expression(OwnerField(owner, "tilt"), port.Tilt)})) * 5.0))";
source.AppendLine($" {voiced} = (os.sawtooth(({frequency}) * {pitchRatio}) : fi.lowpass(1, {cutoff})) * clip01({opening}) * clip01(0.25 + {tension});");
source.AppendLine($" {flow} = {ProbeSignal(options, $"/debug/{voiceName}/source/{port.Name}/flow", $"({flowScale}) * (({voiced}) * ma.tanh((({pressure}) * (0.5 + {tension})) / max(0.05, {impedance})) + 0.08 * no.noise * {parameters.Expression(OwnerField(owner, "noise"), port.Noise)})", -2, 2)};");
var wave = port.Pulse == GlottalPulse.Rosenberg ? RosenbergPulse($"(({frequency}) * {pitchRatio})") : $"os.sawtooth(({frequency}) * {pitchRatio})";
source.AppendLine($" {voiced} = ({wave} : fi.lowpass(1, {cutoff})) * clip01({opening}) * clip01(0.25 + {tension});");
source.AppendLine($" {flow} = {ProbeSignal(options, $"/debug/{voiceName}/source/{port.Name}/flow", $"({flowScale}) * (({voiced}) * ma.tanh((({pressure}) * (0.5 + {tension})) / max(0.05, {impedance})) + 0.08 * {(port.NoiseHighPassHz > 0 ? $"(no.noise : fi.highpass(2, {port.NoiseHighPassHz.ToString("0.###", CultureInfo.InvariantCulture)}))" : "no.noise")} * {parameters.Expression(OwnerField(owner, "noise"), port.Noise)})", -2, 2)};");
keepAlive.Add(load);
keepAlive.Add(voiced);
keepAlive.Add(flow);
return flow;
}
private static string PrimitiveContactExpression(
// Rosenberg C flow pulse of one period (phase p of 0..1): opening 0.5 (1 - cos(pi p / 0.4)) for p < 0.4, return cos(pi/2 (p - 0.4) / 0.16)
// for the next 0.16, closed after. Its mean is 0.4 / 2 + 0.16 * 2 / pi = 0.301859 and its rms about that mean is 0.372667; it is made zero-mean
// and scaled by 0.57735 / 0.372667 = 1.549 to the rms of os.sawtooth (1 / sqrt 3), so a swap of the pulse leaves the SOURCE level where it was (the rendered level moves: the pulse has no strong upper harmonics for the tract to pass).
public static string RosenbergPulse(string frequency) =>
$"(((os.lf_sawpos({frequency}) : (\\(p).(select2(p < 0.4, select2(p < 0.56, 0.0, cos(ma.PI * 0.5 * (p - 0.4) / 0.16)), 0.5 * (1.0 - cos(ma.PI * p / 0.4)))))) - 0.301859) * 1.549)";
private static (string Released, string Burst) PrimitiveContactExpression(
StringBuilder source,
SynthPatch patch,
string voiceName,
@ -769,7 +800,7 @@ public static partial class FaustEmitter
keepAlive.Add(reservoir);
keepAlive.Add(burst);
keepAlive.Add(released);
return $"({released} + {burst})";
return (released, burst);
}
// Open fraction of a branch port: the ladder reads it as the velum area when the branch joins two paths of the network,

View file

@ -222,7 +222,33 @@ public static class IpaGestureExperiment
start += duration;
}
return Scaffold(lines, Math.Clamp(start + tailSeconds, 0.15f, 4f), frequency);
return Scaffold(lines, Math.Clamp(start + tailSeconds, 0.15f, 4f), frequency, phones.Any(phone => NeedsSideStub(phone.Target)));
}
// A lateral is the one gesture that opens the side stub (PatchScript.SideStubBranch); a word without one is scaffolded without it, byte for byte.
private static bool NeedsSideStub(IpaGestureExperimentTarget target) =>
(target.Descriptor.Length > 0 ? target.Descriptor : PatchScript.TryIpaDescriptor(target.Ipa, out var known) ? known : "")
.Contains("lateral", StringComparison.OrdinalIgnoreCase);
// The sublingual cavity beside a lateral's midline contact: a closed side branch of the oral tract at the alveolar ridge. Its quarter-wave
// antiresonance (c / 4L, lowered by the junction and the orifice) is the lateral's dip; the length is a DESIGN VALUE placing it between 2 and 3 kHz
// (no primary dimension retrieved). Cross-section 1 cm^2, four cells of the stub's own morphology; the first cell is the orifice, the branch
// opening times the port maximum (NasalTractAreas). The end is closed (reflection +1, aperture 0: it radiates nothing).
private const string SideStubLengthCentimeters = "3";
private const string SideStubAreas = "1,1,1,1";
private static string SideStubDeclarations(bool sideStub)
{
if (!sideStub) return "";
PatchScript.TryPlaceDistanceCentimeters("alveolar", out var ridge);
var at = 1f - ridge / StoryVowelAreas.MeanLengthCentimeters;
return $"""
morphology name=side_stub length_cm={SideStubLengthCentimeters} areas={SideStubAreas}
waveguide_path name=side_stub_path morphology=side_stub speed={TractSpeedMetersPerSecond} strategy=thiran order=1 max_delay=4096 loss=.98
branch_port name={PatchScript.SideStubBranch} from=oral_path from_position={Format(at)} to=side_stub_path opening=0 coupling=1
radiation_load name=side_stub_end path=side_stub_path kind=lip position=1 aperture=0 reflection=1 impedance=.28
""";
}
private static string GestureLine(IpaGestureExperimentTarget target, float start, float duration, float intensity) =>
@ -237,7 +263,7 @@ public static class IpaGestureExperiment
// murmur read -4.2 dB (/m/) and -2.2 dB (/n/) re the flanking vowels; the target is 8 to 16 dB under (no primary level or bandwidth retrieved).
private const string NasalPathLoss = ".975";
private static string Scaffold(IReadOnlyList<string> gestureLines, float sustain, float frequency) => $$"""
private static string Scaffold(IReadOnlyList<string> gestureLines, float sustain, float frequency, bool sideStub = false) => $$"""
patch gain=.45
morphology name=oral length_cm={{Format(StoryVowelAreas.MeanLengthCentimeters)}} diameters=.55,.75,1.05,1.45,1.25,.8 tongue_index=3 tongue_diameter=1.4 constriction_index=4 constriction_diameter=1 constriction_width=.03 lip_opening=4
vowel_set area_function=oral source={{StoryVowelAreas.Source}}
@ -250,9 +276,9 @@ public static class IpaGestureExperiment
radiation_load name=mouth path=oral_path kind=lip position=1 aperture=.8 reflection=-1 impedance=.28
radiation_load name=nostril path=nasal_path kind=lip position=1 aperture=.8 reflection=-1 impedance=.28
probe_timeline name=flow network=voice blocks=12 block_size=64
vocal_network name=voice paths=oral_path,nasal_path sources=folds contacts=contact branches=velopharynx radiation=mouth,nostril probe=flow
{{SideStubDeclarations(sideStub)}}vocal_network name=voice paths=oral_path,nasal_path{{(sideStub ? ",side_stub_path" : "")}} sources=folds contacts=contact branches=velopharynx{{(sideStub ? "," + PatchScript.SideStubBranch : "")}} radiation=mouth,nostril{{(sideStub ? ",side_stub_end" : "")}} probe=flow
{{string.Join("\n", gestureLines)}}
vocal network=voice freq={{Format(frequency)}} gain=.7 sustain={{Format(sustain)}}
vocal network=voice freq={{Format(frequency)}} gain=.7 attack=.012 sustain={{Format(sustain)}}
""";
private static IReadOnlyList<IpaGestureMetricSummary> SummarizeMetrics(IReadOnlyList<IpaGestureExperimentMetric> metrics) =>

View file

@ -40,7 +40,8 @@ public sealed record PrimitiveTimelineFact(
[property: Key(4)] string Unit,
[property: Key(5)] int BlockStart,
[property: Key(6)] int BlockEnd,
[property: Key(7)] string Summary);
[property: Key(7)] string Summary,
[property: Key(8), CultElementId] string ElementId = "");
[CultDocument("aquasynth.song_challenge_evidence", "aquasynth.song_challenge_evidence.v1")]
[MessagePackObject]

View file

@ -474,7 +474,17 @@ public sealed record SourcePort(
float Impedance = 0.35f,
float FlowScale = 0.02f,
float Tilt = 0.5f,
float PitchRatio = 1f);
float PitchRatio = 1f,
GlottalPulse Pulse = GlottalPulse.Saw,
float NoiseHighPassHz = 0f);
// The glottal flow waveform of a primitive source port. Saw is the band-limited saw the tilt lowpass shapes; Rosenberg is the
// Rosenberg C pulse (open phase 0.4 of the period, return phase 0.16), zero-mean and scaled to the saw's rms at the source. The rendered level still differs: the tract passes less of the pulse (-2.5 dB output rms on /ɑmi/, measured -2.54).
public enum GlottalPulse
{
Saw,
Rosenberg
}
public sealed record ConstrictionContact(
string Name,

View file

@ -8,6 +8,26 @@ public sealed class PatchScriptException(int line, string message) : Exception($
}
public static class PatchScript
{
/// <summary>The branch port a lateral gesture opens: a closed side stub beside the oral path at the alveolar ridge (the sublingual cavity).
/// A script that gestures a lateral without declaring it is refused, not approximated.</summary>
public const string SideStubBranch = "side_stub";
// Seconds an articulator takes to move from where the previous phone left it to this phone's first value. A tract does not step
// between phones: the merged surface curve held the previous value up to the boundary and jumped, and a jump in a ladder cell's
// area is a transient the ear hears as a click (nibu: peak 0.40 and 0.49 against a 0.2 vowel, at the 95 and 275 ms boundaries),
// and it leaves the consonant without the formant transitions that tell /b/ from a fade-in. A DESIGN VALUE inside the 20-50 ms
// of a CV formant transition; no measurement of this tract retrieved.
public const float PhoneTransitionSeconds = 0.03f;
// Seconds a stop takes to open from full closure; its burst lasts about this long. A DESIGN VALUE inside the 5-15 ms of a
// stop burst; no measurement of this tract retrieved. The opening's noise is still shaped by the exporter.
private const float StopReleaseSeconds = 0.012f;
/// <summary>Seconds after the start of a stop gesture of the given duration at which its articulators begin to open (the stop is
/// shut until then). The one owner of the release time: the contact, lip and constriction splines hold shut to here and the burst
/// gain window opens here; a test that wants the release reads it from here.</summary>
public static float StopReleaseStartSeconds(float durationSeconds) => durationSeconds - MathF.Min(StopReleaseSeconds, 0.3f * durationSeconds);
/// <summary>
/// The DSL's own IPA table: the phones a phoneme_gesture knows without an explicit descriptor. A hand-written script
/// that names another phone falls back to an alveolar approximant; a caller that must not be approximated asks here first.
@ -25,8 +45,12 @@ public static class PatchScript
{
"p" => "voiceless_bilabial_plosive",
"b" => "voiced_bilabial_plosive",
"t" => "voiceless_alveolar_plosive",
"d" => "voiced_alveolar_plosive",
"k" => "voiceless_velar_plosive",
"m" => "voiced_bilabial_nasal",
"n" => "voiced_alveolar_nasal",
"l" => "voiced_alveolar_lateral_approximant",
"s" => "voiceless_alveolar_fricative",
"z" => "voiced_alveolar_fricative",
"ʃ" => "voiceless_postalveolar_fricative",
@ -39,6 +63,11 @@ public static class PatchScript
return known is not null;
}
/// <summary>The distance in cm from the lip plane at which a descriptor's place closes, or false when the place has no distance
/// (fraction only, or no place named): a caller must not invent one.</summary>
public static bool TryPlaceDistanceCentimeters(string descriptor, out float centimeters) =>
Compiler.TryPlaceDistanceCentimeters(descriptor, out centimeters);
public static SynthPatch Parse(string script)
{
var compiler = new Compiler();
@ -939,7 +968,9 @@ public static class PatchScript
GetBoundFloat(fields, line, 0.35f, $"/vocal/sources/{_sourcePorts.Count}/impedance", "impedance", "load", "source_impedance"),
GetBoundFloat(fields, line, 0.02f, $"/vocal/sources/{_sourcePorts.Count}/flow_scale", "flow_scale", "scale"),
GetBoundFloat(fields, line, 0.5f, $"/vocal/sources/{_sourcePorts.Count}/tilt", "tilt", "spectral_tilt"),
GetBoundFloat(fields, line, 1f, $"/vocal/sources/{_sourcePorts.Count}/pitch_ratio", "pitch_ratio", "f0_ratio"));
GetBoundFloat(fields, line, 1f, $"/vocal/sources/{_sourcePorts.Count}/pitch_ratio", "pitch_ratio", "f0_ratio"),
ParseGlottalPulse(GetAny(fields, ["pulse", "glottal_pulse"], "saw"), line),
Math.Clamp(GetFloat(fields, line, 0f, "noise_highpass", "noise_hp"), 0f, 8000f));
_sourcePorts.Add(port);
_sourcePortsByName[name] = port;
RegisterSourcePortSurfaces(_sourcePorts.Count - 1, port);
@ -1481,11 +1512,58 @@ public static class PatchScript
duration * 0.25f,
Math.Clamp(point.value, 0, 1)))
.ToArray();
splinePoints = FollowSegments(WithPhoneTransition(surfacePath, start, duration, splinePoints));
var spline = new ControlSpline(splineName, surfacePath, splinePoints, ControlSplineInterpolation.Bezier);
_controlSplines.Add(spline);
_controlSplinesByName[spline.Name] = spline;
}
// Prepends the boundary ramp: a point at the gesture start holding the value the surface has there, then the gesture's first
// point PhoneTransitionSeconds later (at most 0.4 of the gesture, and before its second point). The first phone of a word, and
// a surface the earlier phones never touched, keep their value from the start.
private ControlSplinePoint[] WithPhoneTransition(string surfacePath, float start, float duration, ControlSplinePoint[] points)
{
ControlSplinePoint? previous = null;
foreach (var spline in _controlSplines)
{
if (!spline.SurfacePath.Equals(surfacePath, StringComparison.OrdinalIgnoreCase)) continue;
foreach (var point in spline.Points)
{
if (point.TimeSeconds <= start + 0.000001f && (previous is null || point.TimeSeconds >= previous.TimeSeconds)) previous = point;
}
}
if (previous is null || points.Length < 2 || MathF.Abs(previous.Value - points[0].Value) <= 0.0005f) return points;
var ramp = MathF.Min(PhoneTransitionSeconds, 0.4f * duration);
ramp = MathF.Min(ramp, points[1].TimeSeconds - points[0].TimeSeconds);
if (ramp < 0.002f) return points;
var handle = ramp / 3;
var first = points[0];
var lead = new ControlSplinePoint(first.TimeSeconds, previous.Value, handle, previous.Value, handle, previous.Value);
var arrival = first with { TimeSeconds = first.TimeSeconds + ramp, InTimeOffsetSeconds = handle, InValue = first.Value };
return [lead, arrival, .. points.Skip(1)];
}
// Sets every handle's time to a third of the segment it belongs to. The Faust lowering evaluates a segment's Bezier on the
// linear fraction of its time and ignores the handle times; a handle of a third makes the C# timeline (which solves the curve's
// time for its parameter) agree with it exactly. A handle longer than the segment (0.25 of the gesture on a 12 ms opening) folds
// the C# curve back on itself.
private static ControlSplinePoint[] FollowSegments(ControlSplinePoint[] points)
{
if (points.Length < 2) return points;
var shaped = new ControlSplinePoint[points.Length];
for (var i = 0; i < points.Length; i++)
{
var after = (i + 1 < points.Length ? points[i + 1].TimeSeconds - points[i].TimeSeconds : points[i].TimeSeconds - points[i - 1].TimeSeconds) / 3;
var before = (i > 0 ? points[i].TimeSeconds - points[i - 1].TimeSeconds : points[1].TimeSeconds - points[0].TimeSeconds) / 3;
shaped[i] = points[i] with { InTimeOffsetSeconds = before, OutTimeOffsetSeconds = after };
}
return shaped;
}
private string UniqueSplineName(string name)
{
var safe = SafeName(name);
@ -1504,7 +1582,7 @@ public static class PatchScript
}
}
private void EmitPhonemeGestureSplines(string name, string descriptor, float start, float duration, float intensity, float pitchRatio = 1f)
private void EmitPhonemeGestureSplines(string name, string descriptor, float start, float duration, float intensity, int line, float pitchRatio = 1f)
{
var tokens = DescriptorTokens(descriptor);
var voiced = tokens.Contains("voiced") || tokens.Contains("vowel") || tokens.Contains("nasal") || tokens.Contains("approximant");
@ -1513,7 +1591,6 @@ public static class PatchScript
voiced = false;
}
var place = PlaceTarget(tokens);
var constriction = ConstrictionTarget(tokens);
var pressure = Math.Clamp(0.45f + 0.30f * intensity, 0, 1);
AddAuthoredSpline($"{name}_source_pressure", "/vocal/sources/0/pressure", start, duration, (0, 0.4f), (0.2f, pressure), (1, pressure * 0.85f));
@ -1527,17 +1604,18 @@ public static class PatchScript
if (tokens.Contains("vowel"))
{
EmitVowelGesture(name, descriptor, start, duration);
EmitVowelGesture(name, descriptor, start, duration, line);
return;
}
var length = _areaFunctions.Count > 0 ? _areaFunctions[0].Shape.LengthCentimeters : StoryVowelAreas.MeanLengthCentimeters;
var place = PlaceFraction(tokens, length);
if (_areaFunctions.Count > 0 && _areaFunctions[0].Vowels is not null && _areaFunctions[0].Deformation is { } control)
{
// Under vowel_set the constriction is placed by distance along the tract: the surface is a section index, so a normalized
// place fraction would land at fraction * sections / (sections - 1) of the tract, past the lips for a labial.
var sections = Math.Max(2, _areaFunctions[0].Shape.Sections);
var position = ConsonantPositionFromGlottis(tokens, place, _areaFunctions[0].Shape.LengthCentimeters);
HoldOnSurface($"{name}_constriction_index", "/vocal/areas/0/area/constriction_index", start, duration, position * (sections - 1) / control.IndexScale);
HoldOnSurface($"{name}_constriction_index", "/vocal/areas/0/area/constriction_index", start, duration, place * (sections - 1) / control.IndexScale);
}
else
{
@ -1547,14 +1625,26 @@ public static class PatchScript
// A nasal stop holds its oral closure for as long as the velum and the contact stay put (to 0.8 of the gesture): the murmur is the
// closed-mouth sound, and an alveolar closure that began to open at 0.5 let the oral tract radiate again over the last third (/n/ read
// -3.8 dB under its vowels against /m/ -13.2 dB, whose lips hold to 0.7).
var closureHold = tokens.Contains("nasal") ? 0.8f : 0.5f;
AddAuthoredSpline($"{name}_constriction_diameter", "/vocal/areas/0/area/constriction_diameter", start, duration, (0, constriction), (closureHold, constriction), (1, Math.Min(0.65f, constriction + 0.2f)));
var stopsBehindTheLips = (tokens.Contains("plosive") || tokens.Contains("stop")) && !(tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial"));
// A stop whose seal is the tongue (not the lips) is closed completely and until the contact opens (StopReleaseStartSeconds): at the nasal's 0.03 cm
// aperture a /t/ closure measured -10.4 dB re its vowels against /p/ -19.7 (the lips seal /p/ whatever the tongue does), and
// rendered -21.5 dB with the aperture at 0 (area floor 1e-6 cm^2).
// Every stop holds all its articulators shut until StopReleaseSeconds before its end and opens in that time: the burst is the
// opening, and an opening spread over a third of the gesture (33 ms of the 95 ms /b/) made the burst a fricative's length
// (the phone recogniser heard /v/ before the vowel, Meta heard "fah then bah").
var isStop = tokens.Contains("plosive") || tokens.Contains("stop");
var stopHold = StopReleaseStartSeconds(duration) / duration;
var closureHold = tokens.Contains("nasal") || tokens.Contains("lateral") ? 0.8f : isStop ? stopHold : 0.5f;
var closed = stopsBehindTheLips ? 0f : constriction;
AddAuthoredSpline($"{name}_constriction_diameter", "/vocal/areas/0/area/constriction_diameter", start, duration, (0, closed), (closureHold, closed), (1, Math.Min(0.65f, constriction + 0.2f)));
if (tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial") || tokens.Contains("rounded"))
{
var lipTarget = tokens.Contains("approximant") ? 0.38f : tokens.Contains("fricative") ? 0.18f : 0.04f;
AddAuthoredSpline($"{name}_lip_area", "/vocal/areas/0/area/lip_opening", start, duration, (0, lipTarget), (0.7f, lipTarget), (1, 0.45f));
AddAuthoredSpline($"{name}_lip_radiation", "/vocal/radiation/0/aperture", start, duration, (0, lipTarget), (0.7f, lipTarget), (1, 0.75f));
// A stop's lips are shut, not at a 0.04 leak: at 0.04 the closed-mouth voice bar of /b/ read -19.1 dB re the following vowel (the
// test's design value is -34 to -26) and /p/ -30.1 (-60 to -38); shut, -27.7 and -38.8. A nasal keeps its murmur's small opening.
var lipTarget = tokens.Contains("approximant") ? 0.38f : tokens.Contains("fricative") ? 0.18f : isStop ? 0f : 0.04f;
AddAuthoredSpline($"{name}_lip_area", "/vocal/areas/0/area/lip_opening", start, duration, (0, lipTarget), (isStop ? stopHold : 0.7f, lipTarget), (1, 0.45f));
AddAuthoredSpline($"{name}_lip_radiation", "/vocal/radiation/0/aperture", start, duration, (0, lipTarget), (isStop ? stopHold : 0.7f, lipTarget), (1, 0.75f));
}
if (tokens.Contains("nasal"))
@ -1564,11 +1654,19 @@ public static class PatchScript
}
else if (tokens.Contains("plosive") || tokens.Contains("stop"))
{
AddAuthoredSpline($"{name}_contact", "/vocal/contacts/0/opening", start, duration, (0, 0.02f), (0.65f, 0.02f), (1, 0.9f));
AddAuthoredSpline($"{name}_stored_pressure", "/vocal/contacts/0/stored_pressure", start, duration, (0, 0.4f), (0.65f, 0.75f), (1, 0.05f));
AddAuthoredSpline($"{name}_contact", "/vocal/contacts/0/opening", start, duration, (0, 0.02f), (stopHold, 0.02f), (1, 0.9f));
AddAuthoredSpline($"{name}_stored_pressure", "/vocal/contacts/0/stored_pressure", start, duration, (0, 0.4f), (stopHold, 0.75f), (1, 0.05f));
// The release burst is turbulence at the opening constriction: its gain is held for the plosive and the exporter shapes
// it by the stored pressure and the opening (see PrimitiveContactExpression).
HoldOnSurface($"{name}_release_flow", "/vocal/contacts/0/release_flow", start, duration, PlosiveBurstGain);
// it by the stored pressure and the opening (see PrimitiveContactExpression). The gain exists only around this plosive:
// a surface holds its last value after its last point (and its first before its first), so a gain left at its level
// made noise at every later contact state, the final nasal's closure and the tail included.
// The exporter's burst is noise times 4 * opening * (1 - opening): it sounds whenever the contact passes between shut and open
// in either direction, so a gain held through the closure made the 30 ms closing ramp a 15-20 ms hiss before every stop (the
// >4 kHz share of the frames before /t/ was -1 dB against -57 dB with the closure stepped). The gain exists only from the
// stop's release start to its end, one ramp (0.15 of that window) either side.
var releaseStart = StopReleaseStartSeconds(duration);
GainAroundGesture($"{name}_release_flow", "/vocal/contacts/0/release_flow", start + releaseStart, duration - releaseStart, stopsBehindTheLips ? TongueStopBurstGain : PlosiveBurstGain);
PlaceBurst(name, tokens, place, start, duration);
AddAuthoredSpline($"{name}_velum", "/vocal/branches/0/opening", start, duration, (0, VelumClosed), (1, VelumClosed));
}
else if (tokens.Contains("fricative"))
@ -1581,13 +1679,25 @@ public static class PatchScript
{
AddAuthoredSpline($"{name}_contact", "/vocal/contacts/0/opening", start, duration, (0, 0.55f), (1, 0.65f));
}
// A lateral opens the side stub for its gesture and only then (the stub is closed before and after, as the burst gain is).
if (tokens.Contains("lateral") && _branchPortsByName.ContainsKey(SideStubBranch))
{
var branch = _branchPorts.FindIndex(candidate => candidate.Name.Equals(SideStubBranch, StringComparison.OrdinalIgnoreCase));
GainAroundGesture($"{name}_side_stub", $"/vocal/branches/{branch}/opening", start, duration, 1f);
}
}
// A vowel gesture raises the weight of the descriptor's Story vowel to 1 and holds every other vowel weight at 0 (the schwa and
// any vowel descriptor without a Story shape hold all of them at 0: the geometric-mean shape). The constriction and the lip cap
// stay open, the velum closed. On a morphology without vowel_set the vowel surfaces do not exist and nothing is held.
private void EmitVowelGesture(string name, string descriptor, float start, float duration)
// stay open, the velum closed. A vowel gesture on a morphology without vowel_set is a parse error: the vowel surfaces do not exist.
private void EmitVowelGesture(string name, string descriptor, float start, float duration, int line)
{
if (_areaFunctions.Count == 0 || _areaFunctions[0].Vowels is null)
{
throw new PatchScriptException(line, $"vowel gesture `{name}` needs a vowel_set before it: without one the vowel surfaces do not exist and the gesture would shape nothing");
}
var target = StoryVowelAreas.IdForDescriptor(descriptor);
foreach (var vowel in StoryVowelAreas.All)
{
@ -1627,6 +1737,62 @@ public static class PatchScript
AddAuthoredSpline(name, surfacePath, start, duration, (0, normalized), (1, normalized));
}
// A surface that is zero before and after the gesture and the given level through it (the plosive burst gain, the lateral's side stub opening); the ramps are 0.15 of the gesture long and run into the neighbouring
// phones (the leading one is cut where the word begins).
private void GainAroundGesture(string name, string surfacePath, float start, float duration, float gain)
{
if (!_controlSurfacesByPath.TryGetValue(surfacePath, out var surface) || surface.MaxValue <= surface.MinValue)
{
return;
}
var level = Math.Clamp((gain - surface.MinValue) / (surface.MaxValue - surface.MinValue), 0, 1);
ControlSplinePoint At(float time, float value) => new(time, value, 0, value, 0, value);
var ramp = duration * 0.15f;
var points = new List<ControlSplinePoint>();
if (start > 0) points.Add(At(Math.Max(0, start - ramp), 0));
points.Add(At(start, level));
points.Add(At(start + duration, level));
points.Add(At(start + duration + ramp, 0));
var spline = new ControlSpline(UniqueSplineName(name), surfacePath, FollowSegments(points.ToArray()), ControlSplineInterpolation.Bezier);
_controlSplines.Add(spline);
_controlSplinesByName[spline.Name] = spline;
}
// The place a plosive's burst enters the tract: the contact's position. A labial plosive keeps its burst at the glottal end (position 0)
// and writes nothing while no other plosive has driven the position, so a word of labials is unchanged (the position surface does not
// exist, and the exporter sends a burst in at the glottal end unless its contact has that surface); once any other plosive
// drives it, every labial plosive of the word writes position 0 too, or it would hold that plosive's place.
private bool _burstSiteDriven;
private readonly List<(string Name, float Start, float Duration)> _labialPlosives = [];
private void PlaceBurst(string name, HashSet<string> tokens, float place, float start, float duration)
{
var labial = tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial");
if (labial && !_burstSiteDriven)
{
_labialPlosives.Add((name, start, duration));
return;
}
if (!_burstSiteDriven)
{
_burstSiteDriven = true;
if (_constrictionContacts.Count > 0)
{
var contact = _constrictionContacts[0];
RegisterNormalizedPrimitiveSurface(OwnerField("/vocal/contacts/0", "position"), contact.Name, "position", contact.Position);
}
foreach (var (labialName, labialStart, labialDuration) in _labialPlosives)
{
HoldOnSurface($"{labialName}_burst_site", "/vocal/contacts/0/position", labialStart, labialDuration, 0);
}
}
HoldOnSurface($"{name}_burst_site", "/vocal/contacts/0/position", start, duration, labial ? 0 : place);
}
private static string GestureDescriptor(string ipa, IReadOnlyDictionary<string, string> fields)
{
var explicitDescriptor = GetAny(fields, ["descriptor", "desc", "features"], "");
@ -1661,40 +1827,79 @@ public static class PatchScript
// following vowel; no published burst level was retrieved.
private const float PlosiveBurstGain = 0.06f;
// The same for a stop sealed by the tongue, whose burst goes in at the closure (LadderInjection) and reaches the lips almost
// unfiltered: at 0.06 the isolated /t/ burst peaked at 0.76 of the following vowel's peak (/b/ 0.19; the rule is under half), at
// 0.03 it is about half that. A DESIGN VALUE set by that measurement.
private const float TongueStopBurstGain = 0.03f;
// Distance from the lip plane to the alveolar ridge in cm. A DESIGN VALUE; no source for the distance was retrieved. 2.555 cm puts the
// closure on the centre of ladder cell 20 of 24 of the scaffold tract (17.52 cm at 48 kHz and 350 m/s: (20.5 / 24) * 17.52 = 14.965 cm
// from the glottis), the cell grid being what a narrow constriction (scaffold constriction_width .03, e-fold 0.63 cm) can close; it is
// the ladder's counterpart of the tube check's closed end after section 37 of 44 (14.73 cm).
private const float AlveolarRidgeCentimetersFromLips = 2.555f;
// Normalized position (0 glottis, 1 lips) of a consonant's constriction in the vowel_set path: labials at the lip plane, alveolars
// AlveolarRidgeCentimetersFromLips behind it, every other place at its PlaceTarget fraction of the tract length.
private static float ConsonantPositionFromGlottis(HashSet<string> tokens, float placeFraction, float lengthCentimeters)
// The velar closure, cm behind the lip plane: between the narrowest dorsal section of /u/ (section 26, 6.97 cm) and the narrowest
// pharyngeal section of /a/ (section 13, 12.14 cm) of the Story 2008 area functions. 9.81 cm is the 0.44 fraction the table held before
// it had distances; it lies within 0.05 cm of the centre of oral ladder cell 10 of 24 (0.4375 of the tract), and the closure's Gaussian is narrower
// than a cell; the mean of the two sections, 9.555 cm, would fall 0.3 cm from the nearest cell centre (not tried).
private const float VelarCentimetersFromLips = 9.81f;
// The lateral's midline: the tongue tip meets the ridge and the flow leaves by the sides, here the side stub's neighbour, the oral path
// through a midline held nearly shut for the gesture (to 0.8, as the nasal). A DESIGN VALUE set so the lateral reads between the vowels and the nasals.
private const float LateralMidlineDiameter = 0.06f;
// Where a consonant closes. One entry per place, first token match wins. A place with a distance is placed by it, in cm behind the
// lip plane, and its normalized position (0 glottis, 1 lips) is 1 - distance / tract length, for the vowel_set section index and the
// hand-written-script fraction alike. A place with no distance is "fraction only": its fraction of the tract length from the glottis,
// a hand-set DESIGN VALUE, and no later cut may read a distance from it (TryPlaceDistanceCentimeters says absent).
private readonly record struct PlaceEntry(string[] Tokens, float? CentimetersFromLips, float Fraction);
private static readonly PlaceEntry[] Places =
[
new(["bilabial", "labiodental", "labial"], 0f, 0f),
new(["dental"], null, 0.88f),
new(["alveolar"], AlveolarRidgeCentimetersFromLips, 0f),
new(["postalveolar", "palatoalveolar"], null, 0.70f),
new(["retroflex"], null, 0.64f),
new(["palatal"], null, 0.56f),
new(["velar"], VelarCentimetersFromLips, 0f),
new(["uvular"], null, 0.34f),
new(["pharyngeal", "epiglottal"], null, 0.20f),
new(["glottal"], null, 0.05f),
];
private const float PlaceFractionWhenUnnamed = 0.70f;
private static PlaceEntry? FindPlace(HashSet<string> tokens)
{
if (tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial")) return 1;
if (tokens.Contains("alveolar")) return 1 - AlveolarRidgeCentimetersFromLips / lengthCentimeters;
return placeFraction;
foreach (var place in Places)
{
if (place.Tokens.Any(tokens.Contains)) return place;
}
return null;
}
private static float PlaceTarget(HashSet<string> tokens)
internal static bool TryPlaceDistanceCentimeters(string descriptor, out float centimeters)
{
if (tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial")) return 0.96f;
if (tokens.Contains("dental")) return 0.88f;
if (tokens.Contains("alveolar")) return 0.78f;
if (tokens.Contains("postalveolar") || tokens.Contains("palatoalveolar")) return 0.70f;
if (tokens.Contains("retroflex")) return 0.64f;
if (tokens.Contains("palatal")) return 0.56f;
if (tokens.Contains("velar")) return 0.44f;
if (tokens.Contains("uvular")) return 0.34f;
if (tokens.Contains("pharyngeal") || tokens.Contains("epiglottal")) return 0.20f;
if (tokens.Contains("glottal")) return 0.05f;
return 0.70f;
centimeters = FindPlace(DescriptorTokens(descriptor))?.CentimetersFromLips ?? float.NaN;
return !float.IsNaN(centimeters);
}
// Normalized position of a place along a tract of the given length: 0 glottis, 1 lips.
private static float PlaceFraction(HashSet<string> tokens, float lengthCentimeters) =>
FindPlace(tokens) switch
{
{ CentimetersFromLips: { } cm } => 1 - cm / lengthCentimeters,
{ } place => place.Fraction,
_ => PlaceFractionWhenUnnamed
};
private static float ConstrictionTarget(HashSet<string> tokens)
{
if (tokens.Contains("plosive") || tokens.Contains("stop") || tokens.Contains("nasal")) return 0.03f;
if (tokens.Contains("fricative")) return 0.16f;
if (tokens.Contains("lateral")) return LateralMidlineDiameter;
if (tokens.Contains("approximant")) return 0.48f;
if (tokens.Contains("trill") || tokens.Contains("tap") || tokens.Contains("flap")) return 0.24f;
return 0.55f;
@ -2684,12 +2889,17 @@ public static class PatchScript
var intensity = Math.Clamp(GetFloat(fields, line, 1, "intensity", "gain", "strength"), 0, 2);
var pitchRatio = Math.Clamp(GetFloat(fields, line, 1, "pitch_ratio", "f0_ratio"), 0.5f, 2f);
var descriptor = GestureDescriptor(ipa, fields);
if (DescriptorTokens(descriptor).Contains("lateral") && !_branchPortsByName.ContainsKey(SideStubBranch))
{
throw new PatchScriptException(line, $"a lateral gesture needs the `{SideStubBranch}` branch port (the sublingual stub); it is not approximated by a plain approximant");
}
var name = TryGetAny(fields, ["name", "n"], out var nameText)
? nameText
: $"ipa_{SafeName(ipa)}_{_phonemeGestures.Count}";
_phonemeGestures.Add(new PhonemeGesture(name, ipa, descriptor, start, duration, intensity));
EmitPhonemeGestureSplines(name, descriptor, start, duration, intensity, pitchRatio);
EmitPhonemeGestureSplines(name, descriptor, start, duration, intensity, line, pitchRatio);
}
private void AddControlCurve(IReadOnlyDictionary<string, string> fields, int line)
@ -4235,6 +4445,13 @@ public static class PatchScript
_ => throw new PatchScriptException(line, $"unknown tract propagation mode `{value}`")
};
private static GlottalPulse ParseGlottalPulse(string value, int line) => value.ToLowerInvariant() switch
{
"saw" or "sawtooth" => GlottalPulse.Saw,
"rosenberg" => GlottalPulse.Rosenberg,
_ => throw new PatchScriptException(line, $"unknown glottal pulse `{value}` (saw, rosenberg)")
};
private static AcousticSourceKind ParseAcousticSourceKind(string value, int line) => value.ToLowerInvariant() switch
{
"glottal" or "glottis" or "larynx" => AcousticSourceKind.Glottal,

View file

@ -61,8 +61,7 @@ public sealed record SfxrParams
PhaOffset = -0.22f,
PhaRamp = -0.1f,
VibStrength = 0.22f,
VibSpeed = 0.28f,
RepeatSpeed = 0.42f
VibSpeed = 0.28f
};
public static SfxrParams Powerup() => new()

View file

@ -32,7 +32,7 @@ public sealed record SpeechRenderResult(
[property: CultName]
string ResultId,
[property: Key(1)]
[property: CultIndex("request")]
[property: CultRole("request")]
string RequestId,
[property: Key(2)] string WorkerId,
[property: Key(3)] string RendererToolchain,
@ -67,7 +67,8 @@ public sealed record SpeechTimingReceipt(
[property: Key(2)] double LatencyMilliseconds,
[property: Key(3)] double BudgetMilliseconds,
[property: Key(4)] float Confidence,
[property: Key(5)] string Notes);
[property: Key(5)] string Notes,
[property: Key(6), CultElementId] string ElementId = "");
[MessagePackObject]
public sealed record SpeechUtteranceEmbeddingInputSnapshot(
@ -107,13 +108,15 @@ public sealed record SpeechPhoneticEventSnapshot(
public sealed record SpeechScoreMetric(
[property: Key(0)] string Name,
[property: Key(1)] float Value,
[property: Key(2)] float Weight);
[property: Key(2)] float Weight,
[property: Key(3), CultElementId] string ElementId = "");
[MessagePackObject]
public sealed record SpeechRenderArtifact(
[property: Key(0)] string Kind,
[property: Key(1)] string Uri,
[property: Key(2)] string ContentHash);
[property: Key(2)] string ContentHash,
[property: Key(3), CultElementId] string ElementId = "");
public enum SpeechRenderStatus
{
@ -141,7 +144,8 @@ public sealed record SpeechWorkerPayloadArtifact(
[property: Key(0)] string Kind,
[property: Key(1)] string Uri,
[property: Key(2)] string ContentHash,
[property: Key(3)] string MediaType);
[property: Key(3)] string MediaType,
[property: Key(4), CultElementId] string ElementId = "");
[CultDocument("aquasynth.speech_worker_admission_receipt", "aquasynth.speech_worker_admission_receipt.v1")]
[MessagePackObject]
@ -150,7 +154,7 @@ public sealed record SpeechWorkerAdmissionReceipt(
[property: CultName]
string ReceiptId,
[property: Key(1)]
[property: CultIndex("payload")]
[property: CultRole("payload")]
string PayloadId,
[property: Key(2)] string PeerId,
[property: Key(3)] string LeaseId,

View file

@ -4,8 +4,25 @@ public sealed record DingNote(double Semitones, int DelayMilliseconds, float Gai
public sealed record DingEvent(string Id, string Meaning, IReadOnlyList<DingNote> Notes);
public sealed record DingInstrument(string Id, string Description, string TimbreFamily, string Script, float RootFrequency, float Brightness, float DecaySeconds, bool UsesNoise);
/// <summary>The daemon-facing identity of a catalog instrument. Revision is the literal 1 until the deferred content-revision step.</summary>
public sealed record DingPatchIdentity(string PatchId, string FaustName, int Revision);
public static class DingCatalog
{
/// <summary>The only derivation of PatchId, FaustName and revision from an instrument id. Host, AquaLower and the tests call this.</summary>
public static DingPatchIdentity Identity(DingInstrument instrument) =>
new($"dings.{instrument.Id}", $"dings_{instrument.Id.Replace('-', '_')}", 1);
/// <summary>The play validation gate. The Host is its enforcing owner (every pipe client passes it); the MCP bridge's
/// own check in DingService.PlayAsync is a deprecated fail-fast path. Returns the rejection text, or null when valid.</summary>
public static string? PlayRejection(string eventId, string instrumentId, float gain)
{
if (!Events.ContainsKey(eventId)) return $"Unknown event '{eventId}'.";
if (!Instruments.ContainsKey(instrumentId)) return $"Unknown instrument '{instrumentId}'.";
if (!float.IsFinite(gain) || gain is < 0 or > 1) return "Gain must be between 0 and 1.";
return null;
}
public static readonly IReadOnlyDictionary<string, DingEvent> Events = new DingEvent[]
{
new("session.start", "Opening welcome", [new(0, 0), new(7, 220)]),

View file

@ -77,7 +77,8 @@ public sealed record AquaSynthAutomationStreamCommand(
[MessagePackObject]
public sealed record AquaSynthAutomationControlFrame(
[property: Key(0)] int Block,
[property: Key(1)] Dictionary<string, float> Controls);
[property: Key(1)] Dictionary<string, float> Controls,
[property: Key(2), CultElementId] string ElementId = "");
[CultDocument("aquasynth.command.instrument_open", AquaSynthDaemonSchemas.InstrumentOpenCommand)]
[MessagePackObject]
@ -95,14 +96,14 @@ public sealed record AquaSynthInstrumentOpenCommand(
[MessagePackObject]
public sealed record AquaSynthInstrumentControlCommand(
[property: Key(0), CultName] string CommandId,
[property: Key(1), CultIndex("session")] string SessionId,
[property: Key(1), CultRole("session")] string SessionId,
[property: Key(2)] Dictionary<string, float> Controls);
[CultDocument("aquasynth.command.instrument_block", AquaSynthDaemonSchemas.InstrumentBlockCommand)]
[MessagePackObject]
public sealed record AquaSynthInstrumentBlockCommand(
[property: Key(0), CultName] string CommandId,
[property: Key(1), CultIndex("session")] string SessionId,
[property: Key(1), CultRole("session")] string SessionId,
[property: Key(2)] int FrameCount = 128,
[property: Key(3)] float Gain = 1.0f,
[property: Key(4)] Dictionary<string, float>? Controls = null);
@ -111,13 +112,13 @@ public sealed record AquaSynthInstrumentBlockCommand(
[MessagePackObject]
public sealed record AquaSynthInstrumentCloseCommand(
[property: Key(0), CultName] string CommandId,
[property: Key(1), CultIndex("session")] string SessionId);
[property: Key(1), CultRole("session")] string SessionId);
[CultDocument("aquasynth.compiled_instrument_session", AquaSynthDaemonSchemas.CompiledInstrumentSession)]
[MessagePackObject]
public sealed record AquaSynthCompiledInstrumentSession(
[property: Key(0), CultName] string SessionId,
[property: Key(1), CultIndex("patch")] string PatchId,
[property: Key(1), CultRole("patch")] string PatchId,
[property: Key(2)] string CompileKey,
[property: Key(3)] string FaustName,
[property: Key(4)] int Revision,
@ -134,7 +135,7 @@ public sealed record AquaSynthCompiledInstrumentSession(
[MessagePackObject]
public sealed record AquaSynthLiveInstrumentSessionState(
[property: Key(0), CultName] string SessionId,
[property: Key(1), CultIndex("patch")] string PatchId,
[property: Key(1), CultRole("patch")] string PatchId,
[property: Key(2)] string Status,
[property: Key(3)] string OpenedAtUtc,
[property: Key(4)] string UpdatedAtUtc,
@ -154,7 +155,7 @@ public sealed record AquaSynthLiveInstrumentSessionState(
public sealed record AquaSynthPatchCompileReceipt(
[property: Key(0), CultName] string ReceiptId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("patch")] string PatchId,
[property: Key(2), CultRole("patch")] string PatchId,
[property: Key(3)] string SessionId,
[property: Key(4)] string Status,
[property: Key(5)] string DecidedAtUtc,
@ -170,7 +171,7 @@ public sealed record AquaSynthPatchCompileReceipt(
public sealed record AquaSynthRenderSampleReceipt(
[property: Key(0), CultName] string RenderId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("patch")] string PatchId,
[property: Key(2), CultRole("patch")] string PatchId,
[property: Key(3)] string SessionId,
[property: Key(4)] string Status,
[property: Key(5)] string CompletedAtUtc,
@ -190,7 +191,7 @@ public sealed record AquaSynthRenderSampleReceipt(
public sealed record AquaSynthAutomationStreamReceipt(
[property: Key(0), CultName] string StreamRunId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("patch")] string PatchId,
[property: Key(2), CultRole("patch")] string PatchId,
[property: Key(3)] string SessionId,
[property: Key(4)] string Status,
[property: Key(5)] string CompletedAtUtc,
@ -210,8 +211,8 @@ public sealed record AquaSynthAutomationStreamReceipt(
public sealed record AquaSynthInstrumentOpenReceipt(
[property: Key(0), CultName] string ReceiptId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("patch")] string PatchId,
[property: Key(3), CultIndex("session")] string SessionId,
[property: Key(2), CultRole("patch")] string PatchId,
[property: Key(3), CultRole("session")] string SessionId,
[property: Key(4)] string Status,
[property: Key(5)] string OpenedAtUtc,
[property: Key(6)] int SampleRate,
@ -228,7 +229,7 @@ public sealed record AquaSynthInstrumentOpenReceipt(
public sealed record AquaSynthInstrumentControlReceipt(
[property: Key(0), CultName] string ReceiptId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("session")] string SessionId,
[property: Key(2), CultRole("session")] string SessionId,
[property: Key(3)] string Status,
[property: Key(4)] string AppliedAtUtc,
[property: Key(5)] int ControlCount,
@ -240,7 +241,7 @@ public sealed record AquaSynthInstrumentControlReceipt(
public sealed record AquaSynthInstrumentBlockReceipt(
[property: Key(0), CultName] string BlockId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("session")] string SessionId,
[property: Key(2), CultRole("session")] string SessionId,
[property: Key(3)] string Status,
[property: Key(4)] string CompletedAtUtc,
[property: Key(5)] ulong Sequence,
@ -258,7 +259,7 @@ public sealed record AquaSynthInstrumentBlockReceipt(
public sealed record AquaSynthInstrumentCloseReceipt(
[property: Key(0), CultName] string ReceiptId,
[property: Key(1), CultIndex("command")] string CommandId,
[property: Key(2), CultIndex("session")] string SessionId,
[property: Key(2), CultRole("session")] string SessionId,
[property: Key(3)] string Status,
[property: Key(4)] string ClosedAtUtc,
[property: Key(5)] bool Released,
@ -276,7 +277,8 @@ public sealed record AquaSynthCultMeshStreamDescriptor(
[property: Key(6)] int Channels,
[property: Key(7)] int FramesPerPacket,
[property: Key(8)] string[] PreferredTransports,
[property: Key(9)] string? MetadataSchemaId);
[property: Key(9)] string? MetadataSchemaId,
[property: Key(10), CultElementId("StreamId")] string ElementId = "");
[MessagePackObject]
public sealed record AquaSynthAutomationPacketReceipt(
@ -289,7 +291,8 @@ public sealed record AquaSynthAutomationPacketReceipt(
[property: Key(6)] string Float32Uri,
[property: Key(7)] string ContentHash,
[property: Key(8)] string PageRef,
[property: Key(9)] int ControlCount);
[property: Key(9)] int ControlCount,
[property: Key(10), CultElementId("Sequence")] string ElementId = "");
[CultDocument("aquasynth.operator_state", AquaSynthDaemonSchemas.OperatorState)]
[CultGlobal]

View file

@ -22,7 +22,8 @@ public sealed record FaustValidation(string Command, bool Success, int? StatusCo
public sealed record FaustWebAssemblyCompileOptions(
string OutputDirectory,
string BaseName = "aquasynth_patch",
bool Stereo = false);
bool Stereo = false,
int SampleRate = 48000);
public sealed record FaustWebAssemblyManifest(
string Name,
@ -89,7 +90,7 @@ public static class FaustCompiler
string? faustPath = null,
CancellationToken cancellationToken = default)
{
var export = FaustEmitter.Emit(patch, new FaustExportOptions(options.BaseName, options.Stereo));
var export = FaustEmitter.Emit(patch, new FaustExportOptions(options.BaseName, options.Stereo, SampleRate: options.SampleRate));
return await CompileWebAssemblySourceAsync(export.Source, options, faustPath, cancellationToken);
}
@ -99,7 +100,7 @@ public static class FaustCompiler
string? faustPath = null,
CancellationToken cancellationToken = default)
{
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(options.BaseName, options.Stereo));
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(options.BaseName, options.Stereo, SampleRate: options.SampleRate));
return await CompileWebAssemblySourceAsync(export.Source, options, faustPath, cancellationToken);
}

View file

@ -93,7 +93,7 @@ public sealed class FaustRenderedSpeechLossSurface(FaustRenderedSpeechLossOption
source.AppendLine(VoiceLine("sine", F(hz), F(gain), target, 0, tract));
}
return FaustEmitter.EmitScript(source.ToString(), new FaustExportOptions("aquasynth_speech_loss")).Source;
return FaustEmitter.EmitScript(source.ToString(), new FaustExportOptions("aquasynth_speech_loss", SampleRate: options.SampleRate)).Source;
}
private async Task<float[]> EstimateGradientAsync(

View file

@ -309,12 +309,12 @@ public static class IpaTrialOrchestrator
File.Copy(candidate.ScriptPath, scriptCopy, overwrite: true);
var script = await File.ReadAllTextAsync(scriptCopy, cancellationToken).ConfigureAwait(false);
var patch = PatchScript.Parse(script);
var timeline = ProbeTimelineReport.Build(patch, "voice", Math.Max(1, options.TimelineBlocks));
var referenceFixture = PinkTromboneParityFixtures.ById(mapped.target.ReferenceFixtureId);
var reference = referenceRenderer.Render(referenceFixture.Controls, mapped.target.Target.DurationSeconds + .18f);
var timeline = ProbeTimelineReport.Build(patch, "voice", Math.Max(1, options.TimelineBlocks), reference.SampleRate);
var timelinePath = Path.Combine(timelineRoot, $"{safeCandidateId}.csv");
await File.WriteAllTextAsync(timelinePath, ProbeTimelineReport.ToCsv(timeline), cancellationToken).ConfigureAwait(false);
var referenceFixture = PinkTromboneParityFixtures.ById(mapped.target.ReferenceFixtureId);
var reference = referenceRenderer.Render(referenceFixture.Controls, mapped.target.Target.DurationSeconds + .18f);
var source = FaustEmitter.EmitScript(script, new FaustExportOptions(safeCandidateId, SampleRate: reference.SampleRate)).Source;
var dspPath = Path.Combine(candidateDir, "candidate.dsp");
await File.WriteAllTextAsync(dspPath, source, cancellationToken).ConfigureAwait(false);

View file

@ -83,7 +83,8 @@ public sealed class CultCachePatchDocumentTests
Path.Combine(RepositoryRoot(), "patches", "aquasynth-patch-cultcache.cc"));
var fromCatalog = CultCachePatchDocumentCatalog.CreateDefault();
Assert.Equal(fromCatalog.PatchDatabase.Entries, fromFile.PatchDatabase.Entries);
// The checked-in file predates element ids; a load mints them (derived from Path), so they are not part of the catalog's content.
Assert.Equal(fromCatalog.PatchDatabase.Entries, fromFile.PatchDatabase.Entries.Select(entry => entry with { ElementId = "" }));
Assert.Equal(fromCatalog.PatchClaims.Select(claim => claim.Id), fromFile.PatchClaims.Select(claim => claim.Id));
Assert.Equal(fromCatalog.SpeechClaims.Select(claim => claim.Id), fromFile.SpeechClaims.Select(claim => claim.Id));
}

View file

@ -0,0 +1,110 @@
using System.Reflection;
using AquaSynth.Dsl;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
namespace AquaSynth.Dsl.Tests;
// CultLib #90 (7760219b): [CultIndex] means unique, enforced at commit and load; [CultRole] names a many-row selection role.
// A member that two rows can share must be a role. The only [CultIndex] left is the CommandId of a receipt: every receipt is stored
// under a key derived from its CommandId alone (AquaSynthCultNetDaemon.*ReceiptKey), so a second row with that CommandId replaces the first.
public sealed class CultIndexUniquenessTests
{
private static readonly string[] ReceiptTypes =
[
nameof(AquaSynthPatchCompileReceipt), nameof(AquaSynthRenderSampleReceipt), nameof(AquaSynthAutomationStreamReceipt), nameof(AquaSynthInstrumentOpenReceipt),
nameof(AquaSynthInstrumentControlReceipt), nameof(AquaSynthInstrumentBlockReceipt), nameof(AquaSynthInstrumentCloseReceipt),
];
[Fact]
public void TheOnlyCultIndexMembersAreReceiptCommandIds()
{
var indexed = new[] { typeof(AquaSynthDaemonService).Assembly, typeof(SpeechRenderResult).Assembly }.Distinct()
.SelectMany(assembly => assembly.GetTypes())
.SelectMany(type => type.GetMembers(BindingFlags.Public | BindingFlags.Instance)
.Where(member => member is PropertyInfo or FieldInfo && member.GetCustomAttribute<CultIndexAttribute>() is not null)
.Select(member => $"{type.Name}.{member.Name}"))
.OrderBy(name => name, StringComparer.Ordinal).ToArray();
Assert.Equal(ReceiptTypes.Select(name => $"{name}.CommandId").OrderBy(name => name, StringComparer.Ordinal), indexed);
}
[Fact]
public async Task ManyRowsMaySharePatchAndSessionAcrossDaemonDocuments()
{
var path = TempFile();
try
{
using (var cache = await CultCacheMessagePack.OpenAsync(path))
{
string[] paths = [];
for (var i = 0; i < 3; i++)
{
// Three commands, one patch, one session: the shape a client that opens, drives and closes one instrument produces.
await Put(cache, $"cmd-{i}-control", new AquaSynthInstrumentControlCommand($"cmd-{i}-control", "session-1", new Dictionary<string, float>()));
await Put(cache, $"cmd-{i}-block", new AquaSynthInstrumentBlockCommand($"cmd-{i}-block", "session-1"));
await Put(cache, $"cmd-{i}-close", new AquaSynthInstrumentCloseCommand($"cmd-{i}-close", "session-1"));
await Put(cache, $"sess-{i}", new AquaSynthCompiledInstrumentSession($"sess-{i}", "patch-1", $"key-{i}", "f", 1, 48000, 0, 1, 128, 0.1f, "t", paths, paths));
await Put(cache, $"live-{i}", new AquaSynthLiveInstrumentSessionState($"live-{i}", "patch-1", "open", "t", "t", "", 48000, 0, 1, 128, 1f, 0, new Dictionary<string, float>(), "", ""));
await Put(cache, $"cmd-{i}-compile", new AquaSynthPatchCompileReceipt($"cmd-{i}-compile", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", "k", 1, paths, paths));
await Put(cache, $"cmd-{i}-render", new AquaSynthRenderSampleReceipt($"cmd-{i}-render", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", 48000, 1, 0.1f, 0, 0, "", "", ""));
await Put(cache, $"cmd-{i}-stream", new AquaSynthAutomationStreamReceipt($"cmd-{i}-stream", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", "v", "a", "c", 48000, 128, 1, [], []));
await Put(cache, $"cmd-{i}-open", new AquaSynthInstrumentOpenReceipt($"cmd-{i}-open", $"cmd-{i}", "patch-1", "session-1", "succeeded", "t", 48000, 0, 1, 128, paths, paths));
await Put(cache, $"cmd-{i}-ctl", new AquaSynthInstrumentControlReceipt($"cmd-{i}-ctl", $"cmd-{i}", "session-1", "applied", "t", 0));
await Put(cache, $"cmd-{i}-blk", new AquaSynthInstrumentBlockReceipt($"cmd-{i}-blk", $"cmd-{i}", "session-1", "succeeded", "t", 0, 48000, 128, 0, 0, "", ""));
await Put(cache, $"cmd-{i}-cls", new AquaSynthInstrumentCloseReceipt($"cmd-{i}-cls", $"cmd-{i}", "session-1", "closed", "t", true));
}
await cache.FlushAsync();
}
// Reopening hydrates and revalidates: a unique index would refuse the file here.
using var reloaded = await CultCacheMessagePack.OpenAsync(path);
Assert.Equal(3, reloaded.GetAll<AquaSynthInstrumentBlockCommand>().Count());
Assert.Equal(3, reloaded.GetAll<AquaSynthCompiledInstrumentSession>().Count(session => session.PatchId == "patch-1"));
Assert.Equal(3, reloaded.GetAll<AquaSynthInstrumentOpenReceipt>().Count(receipt => receipt.SessionId == "session-1" && receipt.PatchId == "patch-1"));
Assert.Equal(3, reloaded.GetAll<AquaSynthInstrumentBlockReceipt>().Count(receipt => receipt.SessionId == "session-1"));
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task OneRowPerCommandIdPerReceiptType()
{
var path = TempFile();
try
{
using var cache = await CultCacheMessagePack.OpenAsync(path);
string[] paths = [];
AquaSynthPatchCompileReceipt Receipt(string command, string status) =>
new(AquaSynthCultNetDaemon.CompileReceiptKey(command).Value, command, "patch-1", "session-1", status, "t", "k", 1, paths, paths);
foreach (var (command, status) in new[] { ("a", "failed"), ("a", "succeeded"), ("b", "succeeded") })
{
var receipt = Receipt(command, status);
await cache.UpsertAsync(receipt, new CultRecordHandle<AquaSynthPatchCompileReceipt>(AquaSynthCultNetDaemon.CompileReceiptKey(command)));
}
// A retried command replaces its own receipt; it cannot add a second row that carries the same CommandId.
var all = cache.GetAll<AquaSynthPatchCompileReceipt>().OrderBy(receipt => receipt.CommandId, StringComparer.Ordinal).ToArray();
Assert.Equal(["a", "b"], all.Select(receipt => receipt.CommandId));
Assert.Equal("succeeded", all[0].Status);
foreach (var kind in new Func<string, CultRecordKey>[] { AquaSynthCultNetDaemon.CompileReceiptKey, AquaSynthCultNetDaemon.RenderReceiptKey, AquaSynthCultNetDaemon.StreamReceiptKey,
AquaSynthCultNetDaemon.OpenReceiptKey, AquaSynthCultNetDaemon.ControlReceiptKey, AquaSynthCultNetDaemon.BlockReceiptKey, AquaSynthCultNetDaemon.CloseReceiptKey })
{
Assert.NotEqual(kind("a"), kind("b"));
Assert.Equal(kind("a"), kind("a"));
}
}
finally
{
File.Delete(path);
}
}
private static Task Put<T>(CultCache cache, string key, T document) where T : class =>
cache.UpsertAsync(document, new CultRecordHandle<T>(new CultRecordKey(key)));
private static string TempFile() => Path.Combine(Path.GetTempPath(), $"aquasynth-cultindex-{Guid.NewGuid():N}.cc");
}

View file

@ -9,6 +9,34 @@ public sealed class DingCatalogTests
public void CuratedInstrumentsStayDistinctAndInsidePleasantnessEnvelope() =>
Assert.Empty(DingCatalog.ValidateCuration());
[Fact]
public void PlayRejectionIsTheHostGateWithPinnedTexts()
{
Assert.Null(DingCatalog.PlayRejection("task.complete", "warm-bell", 0));
Assert.Null(DingCatalog.PlayRejection("task.complete", "warm-bell", 1));
Assert.Equal("Unknown event 'nope'.", DingCatalog.PlayRejection("nope", "warm-bell", .5f));
Assert.Equal("Unknown instrument 'nope'.", DingCatalog.PlayRejection("task.complete", "nope", .5f));
Assert.Equal("Unknown event 'nope'.", DingCatalog.PlayRejection("nope", "nope", 2f));
foreach (var gain in new[] { -.01f, 1.01f, float.NaN, float.PositiveInfinity })
Assert.Equal("Gain must be between 0 and 1.", DingCatalog.PlayRejection("task.complete", "warm-bell", gain));
}
[Fact]
public void HostCallsTheGateAndOwnsNoSecondCopy()
{
var raw = File.ReadAllText(Path.Combine(RepositoryRoot(), "tools", "AquaSynthDingsHost", "DingsPlaybackHost.cs"));
var host = System.Text.RegularExpressions.Regex.Replace(raw, @"//[^\n]*|/\*.*?\*/", "", System.Text.RegularExpressions.RegexOptions.Singleline);
// Source-shape check: the guard must be an unconditional early return of the gate's text.
Assert.Matches(@"if \(DingCatalog\.PlayRejection\(command\.EventId, command\.InstrumentId, command\.Value\) is \{ \} (\w+)\) return Response\(false, ""rejected"", \1\);", host);
// No second copy of the old inline conditions or texts, however the string is split.
Assert.DoesNotContain("Events.TryGetValue", host, StringComparison.Ordinal);
Assert.DoesNotContain("Instruments.TryGetValue", host, StringComparison.Ordinal);
Assert.DoesNotContain("Gain must", host, StringComparison.Ordinal);
Assert.DoesNotContain("Unknown event", host, StringComparison.Ordinal);
Assert.DoesNotContain("Unknown instrument", host, StringComparison.Ordinal);
Assert.DoesNotContain("\"Unk\"", host, StringComparison.Ordinal);
}
[Fact]
public void MinimalDingsVocabularyIsComplete()
{
@ -34,6 +62,30 @@ public sealed class DingCatalogTests
Assert.InRange(pair.Second.DelayMilliseconds - pair.First.DelayMilliseconds, 180, 320);
}
// Independent oracle: literals captured from the pre-DingCatalog.Identity derivation in AquaDaemonClient/AquaLower.
// Session ids, compile keys and store file names hang off these; they must not move without the deferred revision decision.
private static readonly Dictionary<string, (string PatchId, string FaustName)> Pinned = new()
{
["warm-bell"] = ("dings.warm-bell", "dings_warm_bell"),
["glass-chime"] = ("dings.glass-chime", "dings_glass_chime"),
["soft-triangle"] = ("dings.soft-triangle", "dings_soft_triangle"),
["muted-pluck"] = ("dings.muted-pluck", "dings_muted_pluck"),
};
private static Dictionary<string, string> PinnedFaustNames => Pinned.ToDictionary(x => x.Key, x => x.Value.FaustName);
[Fact]
public void IdentityPinsTheOldDerivedValuesForAllFourInstruments()
{
Assert.Equal(Pinned.Keys.Order(), DingCatalog.Instruments.Keys.Order());
foreach (var instrument in DingCatalog.Instruments.Values)
{
var identity = DingCatalog.Identity(instrument);
Assert.Equal(Pinned[instrument.Id].PatchId, identity.PatchId);
Assert.Equal(Pinned[instrument.Id].FaustName, identity.FaustName);
Assert.Equal(1, identity.Revision);
}
}
// tools/aqua-feel measures the lowered files in tools/aqua-feel/lowered-dings; regenerate them with
// `dotnet run --project tools/AquaLower -- --dings tools/aqua-feel/lowered-dings` when the catalog changes.
[Fact]
@ -42,7 +94,7 @@ public sealed class DingCatalogTests
var dir = Path.Combine(RepositoryRoot(), "tools", "aqua-feel", "lowered-dings");
foreach (var instrument in DingCatalog.Instruments.Values)
{
var expected = FaustEmitter.EmitScript(instrument.Script, new FaustExportOptions("dings_" + instrument.Id.Replace('-', '_'))).Source;
var expected = FaustEmitter.EmitScript(instrument.Script, new FaustExportOptions(PinnedFaustNames[instrument.Id])).Source;
Assert.Equal(expected, File.ReadAllText(Path.Combine(dir, instrument.Id + ".dsp")));
}
@ -60,6 +112,18 @@ public sealed class DingCatalogTests
}
}
// Negative check on callers: reverting either call site to an inline rule leaves the catalog tests green, so read the sources.
[Theory]
[InlineData("tools/AquaSynthDingsHost/AquaDaemonClient.cs")]
[InlineData("tools/AquaLower/Program.cs")]
public void CallersDeriveIdentityOnlyThroughTheCatalog(string relativePath)
{
var source = File.ReadAllText(Path.Combine(RepositoryRoot(), relativePath));
Assert.Contains("DingCatalog.Identity(", source, StringComparison.Ordinal);
Assert.DoesNotContain("\"dings_\"", source, StringComparison.Ordinal);
Assert.DoesNotContain("$\"dings", source, StringComparison.Ordinal);
}
private static string RepositoryRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);

View file

@ -31,6 +31,20 @@ public sealed class DingsBridgeTests
Assert.Equal(.7f, host.Commands.Single().Value);
}
[Fact]
public async Task DeprecatedBridgeFailFastKeepsItsErrorsAndTextsAgreeWithTheHostGate()
{
var host = new FakeHostClient();
var service = new DingService(host);
var badEvent = await Assert.ThrowsAsync<ArgumentException>(() => service.PlayAsync("nope", "warm-bell", .5f, CancellationToken.None));
Assert.Equal(DingCatalog.PlayRejection("nope", "warm-bell", .5f), badEvent.Message);
var badInstrument = await Assert.ThrowsAsync<ArgumentException>(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None));
Assert.Equal(DingCatalog.PlayRejection("task.complete", "nope", .5f), badInstrument.Message);
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => service.PlayAsync("task.complete", "warm-bell", 1.5f, CancellationToken.None));
Assert.Empty(host.Commands);
}
[Fact]
public void BridgeProjectContainsNoAudioOutputOwner()
{

View file

@ -0,0 +1,104 @@
using AquaSynth.Dsl;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
namespace AquaSynth.Dsl.Tests;
// CultLib abd1a92e refuses to register a document whose list element type has no [CultElementId] member (CultCache.cs:1008-1010);
// opening any cache here registers every AquaSynth document type, so these tests also fail if one element type loses its id.
public sealed class ElementIdTests
{
// Fixtures/CultCache/pre-element-ids.cc was written by the previous pin (CultLib 42dce361), before list elements had ids:
// an automation-stream command with 2 control frames and a stream receipt with 2 stream descriptors and 2 packets.
[Fact]
public async Task AStoreWrittenBeforeElementIdsReopensWithStableUniqueIds()
{
var path = CopyFixture();
try
{
string[] first;
using (var cache = await CultCacheMessagePack.OpenAsync(path))
{
var command = cache.GetAll<AquaSynthAutomationStreamCommand>().Single();
var receipt = cache.GetAll<AquaSynthAutomationStreamReceipt>().Single();
Assert.Equal([0, 4], command.ControlFrames!.Select(frame => frame.Block));
Assert.Equal(220f, command.ControlFrames![0].Controls["/freq"]);
Assert.Equal(["audio-1", "control-1"], receipt.Streams.Select(stream => stream.StreamId));
Assert.Equal([0UL, 1UL], receipt.Packets.Select(packet => packet.Sequence));
first = Ids(command, receipt);
Assert.All(first, id => Assert.False(string.IsNullOrEmpty(id)));
Assert.Equal(2, command.ControlFrames!.Select(frame => frame.ElementId).Distinct().Count());
Assert.Equal(2, receipt.Packets.Select(packet => packet.ElementId).Distinct().Count());
}
// A second reader of the same bytes mints the same ids (load mints from the record key and element path).
using var again = await CultCacheMessagePack.OpenAsync(path);
Assert.Equal(first, Ids(again.GetAll<AquaSynthAutomationStreamCommand>().Single(), again.GetAll<AquaSynthAutomationStreamReceipt>().Single()));
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task IdsSurviveAWriteAndReload()
{
var path = CopyFixture();
try
{
string[] first;
using (var cache = await CultCacheMessagePack.OpenAsync(path))
{
first = Ids(cache.GetAll<AquaSynthAutomationStreamCommand>().Single(), cache.GetAll<AquaSynthAutomationStreamReceipt>().Single());
// An unrelated write rewrites the store in the current shape.
await cache.UpsertAsync(new AquaSynthInstrumentCloseCommand("c-1", "s-1"), new CultRecordHandle<AquaSynthInstrumentCloseCommand>(new CultRecordKey("c-1")));
await cache.FlushAsync();
}
using var reloaded = await CultCacheMessagePack.OpenAsync(path);
Assert.Equal(first, Ids(reloaded.GetAll<AquaSynthAutomationStreamCommand>().Single(), reloaded.GetAll<AquaSynthAutomationStreamReceipt>().Single()));
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task NewWritesKeepNaturalIdsAndDeriveThePacketIdFromItsSequence()
{
var path = Path.Combine(Path.GetTempPath(), $"aquasynth-elementid-{Guid.NewGuid():N}.cc");
try
{
using (var cache = await CultCacheMessagePack.OpenAsync(path))
{
var packets = new[] { new AquaSynthAutomationPacketReceipt(7, 0, 1, 128, 0.5f, 0.1f, "u", "h", "p", 0), new AquaSynthAutomationPacketReceipt(9, 1, 1, 128, 0.5f, 0.1f, "u", "h", "p", 0) };
var streams = new[] { new AquaSynthCultMeshStreamDescriptor("audio-9", "v", "p", "audio", "f32", 48000, 1, 128, [], null) };
await cache.UpsertAsync(new AquaSynthAutomationStreamReceipt("run", "cmd", "patch", "session", "succeeded", "t", "v", "a", "c", 48000, 128, 1, streams, packets),
new CultRecordHandle<AquaSynthAutomationStreamReceipt>(new CultRecordKey("run")));
await cache.FlushAsync();
}
using var reloaded = await CultCacheMessagePack.OpenAsync(path);
var receipt = reloaded.GetAll<AquaSynthAutomationStreamReceipt>().Single();
Assert.Equal(["7", "9"], receipt.Packets.Select(packet => packet.ElementId));
Assert.Equal("audio-9", receipt.Streams.Single().StreamId);
Assert.Equal("audio-9", receipt.Streams.Single().ElementId);
}
finally
{
File.Delete(path);
}
}
private static string[] Ids(AquaSynthAutomationStreamCommand command, AquaSynthAutomationStreamReceipt receipt) =>
[.. command.ControlFrames!.Select(frame => frame.ElementId), .. receipt.Packets.Select(packet => packet.ElementId)];
private static string CopyFixture()
{
var path = Path.Combine(Path.GetTempPath(), $"aquasynth-preids-{Guid.NewGuid():N}.cc");
File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "CultCache", "pre-element-ids.cc"), path);
return path;
}
}

View file

@ -12,19 +12,19 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output)
private const int Rate = 48000;
private const float Pitch = 137f;
private static string Script(float tilt, float pitch) => $$"""
private static string Script(float tilt, float pitch, string extra = "") => $$"""
morphology name=oral length_cm=17 diameters=.6,.8,1.2,1.5,.9
waveguide_path name=oral_path morphology=oral loss=.998
source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=0 impedance=.3 tilt={{tilt}}
source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=0 impedance=.3 tilt={{tilt}} {{extra}}
radiation_load name=mouth path=oral_path aperture=.8 reflection=-.82 impedance=.28
vocal_network name=voice paths=oral_path sources=folds radiation=mouth
vocal network=voice freq={{pitch}} gain=.2 sustain=1.5
""";
// One second of steady output, so every harmonic of Pitch and every other integer-Hz frequency sits on its own DFT bin.
private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800)
private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800, string extra = "")
{
var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch)), new FaustExportOptions("glottal_spectrum")).Source;
var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch, extra)), new FaustExportOptions("glottal_spectrum")).Source;
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("glottal_spectrum", "glottal_spectrum", ""), source, 1.4f, out var patch, out var error))
{
@ -122,4 +122,133 @@ public sealed class GlottalSourceSpectrumTests(ITestOutputHelper output)
var defaulted = PatchScript.Parse(Script(.8f, Pitch).Replace("tilt=0.8", "", StringComparison.Ordinal));
Assert.Equal(.5f, Assert.Single(defaulted.SourcePorts).Tilt, 5);
}
[Fact]
public void PulseAndNoiseHighPassAreAuthoredSourceFieldsDefaultingToSawAndWhite()
{
var port = Assert.Single(PatchScript.Parse(Script(.5f, Pitch, "pulse=rosenberg noise_hp=2000")).SourcePorts);
Assert.Equal(GlottalPulse.Rosenberg, port.Pulse);
Assert.Equal(2000f, port.NoiseHighPassHz);
var defaulted = Assert.Single(PatchScript.Parse(Script(.5f, Pitch)).SourcePorts);
Assert.Equal(GlottalPulse.Saw, defaulted.Pulse);
Assert.Equal(0f, defaulted.NoiseHighPassHz);
Assert.Throws<PatchScriptException>(() => PatchScript.Parse(Script(.5f, Pitch, "pulse=triangle")));
}
[Fact]
public void OnlyTheRosenbergPulseEmitsThePhasorAndOnlyAHighPassedSourceEmitsTheNoiseFilter()
{
string Emit(string extra) => FaustEmitter.Emit(PatchScript.Parse(Script(.5f, Pitch, extra)), new FaustExportOptions("pulse_emit")).Source;
Assert.DoesNotContain("lf_sawpos", Emit(""), StringComparison.Ordinal);
Assert.Contains("lf_sawpos", Emit("pulse=rosenberg"), StringComparison.Ordinal);
Assert.DoesNotContain("fi.highpass(2, 2000", Emit(""), StringComparison.Ordinal);
Assert.Contains("fi.highpass(2, 2000", Emit("noise_hp=2000"), StringComparison.Ordinal);
}
[Fact]
public void RosenbergPulseIsPeriodicAtThePitchAndRendersWithinSixDbOfTheSaw()
{
var saw = Render(.5f);
var pulse = Render(.5f, extra: "pulse=rosenberg");
if (saw is null || pulse is null) return;
double Rms(float[] w) => Math.Sqrt(w.Sum(v => (double)v * v) / w.Length);
var difference = Db(Rms(pulse) / Rms(saw));
output.WriteLine($"rosenberg rms {Rms(pulse):E3} saw rms {Rms(saw):E3} ({difference:F2} dB)");
// The source rms is matched, the rendered level is not: the tract passes the saw's strong upper harmonics and the pulse has none (-3.2 dB here, -2.5 dB on /ɑmi/, measured -2.54).
Assert.InRange(difference, -6, 0);
var fundamental = Magnitude(pulse, Pitch);
var between = Magnitude(pulse, Pitch * 1.5);
Assert.True(Db(between / fundamental) < -30, $"energy between harmonics {Db(between / fundamental):F1} dB re the fundamental");
}
// One expression compiled alone as a one-output DSP. The pulse is run at 100 Hz, which divides the rate (480 samples a period), so every sample
// sits at a known phase; the patch path scales a bare signal by a constant, so levels are read against os.sawtooth through the same path.
// Expected values are Rosenberg C written out here, independent of the emitted formula's spelling.
private float[]? RenderBare(string expression, double seconds)
{
var dsp = $"import(\"stdfaust.lib\");\nprocess = {expression};\n";
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("pulse_bare", "pulse_bare", ""), dsp, (float)seconds + .1f, out var patch, out var error))
{
if (error?.Contains("Faust toolchain not found", StringComparison.OrdinalIgnoreCase) == true ||
error?.Contains("Faust DLL not found", StringComparison.OrdinalIgnoreCase) == true)
{
return null;
}
Assert.Fail($"bare pulse compile failed: {error}");
}
using (patch) return patch!.Render((float)seconds);
}
private static double RosenbergC(double p) =>
p < 0.4 ? 0.5 * (1 - Math.Cos(Math.PI * p / 0.4)) : p < 0.56 ? Math.Cos(Math.PI * 0.5 * (p - 0.4) / 0.16) : 0;
[Fact]
public void RosenbergPulseIsTheDocumentedRosenbergCZeroMeanAtTheSawsRms()
{
const int period = 480;
var pulse = RenderBare(FaustEmitter.RosenbergPulse("100.0"), 0.5);
var saw = RenderBare("os.sawtooth(100.0)", 0.5);
if (pulse is null || saw is null) return;
var cycle = pulse.Skip(period).Take(period).ToArray();
double Rms(IEnumerable<float> w) => Math.Sqrt(w.Sum(v => (double)v * v) / w.Count());
// Calibrate the path's scale on the saw (rms 1/sqrt3 at the source): read every pulse sample back at source level.
var scale = Rms(saw.Skip(period).Take(period)) / (1 / Math.Sqrt(3));
cycle = cycle.Select(v => (float)(v / scale)).ToArray();
// Rosenberg C has mean 0.301859 and rms 0.372667 about it; the emitted pulse is that, zero-mean, scaled to the saw's rms.
Assert.InRange(cycle.Average(), -0.003, 0.003);
var rms = Rms(cycle);
output.WriteLine($"pulse rms {rms:F5} (saw 1/sqrt3 = {1 / Math.Sqrt(3):F5}), path scale {scale:F4}, peak {cycle.Max():F4}, floor {cycle.Min():F4}");
Assert.InRange(Db(rms / (1 / Math.Sqrt(3))), -0.05, 0.05);
// Shape at every phase point. The phasor's alignment to the sample grid is not part of the contract, so find the shift that fits,
// then hold every point to the closed form: opening cosine, return cosine, closed plateau. A linear opening, another scale or no return phase all miss.
double Expected(int n, int shift) => (RosenbergC(((n + shift) % period) / (double)period) - 0.301859) * 1.549;
var shift = Enumerable.Range(0, period).MinBy(k => Enumerable.Range(0, period).Sum(n => Math.Pow(cycle[n] - Expected(n, k), 2)));
var worst = Enumerable.Range(0, period).Max(n => Math.Abs(cycle[n] - Expected(n, shift)));
output.WriteLine($"best shift {shift} samples, worst deviation from Rosenberg C {worst:E2}");
Assert.True(worst < 0.01, $"worst deviation from Rosenberg C {worst:E2} at shift {shift}");
// The regions by value: the opening peaks at p = 0.4 at (1 - mean) * 1.549, the closed floor is -mean * 1.549 and holds for 0.44 of the period (plus the tail of the return cosine inside the tolerance).
Assert.InRange(cycle.Max(), (1 - 0.301859) * 1.549 - 0.01, (1 - 0.301859) * 1.549 + 0.01);
Assert.InRange(cycle.Min(), -0.301859 * 1.549 - 0.01, -0.301859 * 1.549 + 0.01);
Assert.InRange(cycle.Count(v => Math.Abs(v - (-0.301859 * 1.549)) < 0.01), (int)(0.44 * period) - 15, (int)(0.44 * period) + 15);
}
[Fact]
public void NoiseHighPassCornerIsTheAuthoredHertz()
{
// The source's noise alone (pressure 0 silences the voiced part), white and through fi.highpass(2, fc): band energy against the white render tells the corner.
// A 2 kHz corner leaves almost nothing under 700 Hz, passes 3-3.8 kHz whole and takes a few dB off 1.6-2.4 kHz; a 1 kHz corner passes the middle band; a 4 kHz corner cuts it.
double Band(float[] w, double lo, double hi)
{
double sum = 0;
for (var hz = lo; hz < hi; hz += 25) sum += Math.Pow(Magnitude(w, hz), 2);
return sum;
}
double[] Shape(string extra)
{
var window = Render(.5f, extra: "pressure=0 noise=2 " + extra);
return window is null ? [] : [Band(window, 100, 700), Band(window, 1600, 2400), Band(window, 3000, 3800)];
}
var white = Shape("");
var at2k = Shape("noise_hp=2000 pulse=saw");
if (white.Length == 0 || at2k.Length == 0) return;
var at1k = Shape("noise_hp=1000");
var at4k = Shape("noise_hp=4000");
output.WriteLine($"band energies (100-700, 1600-2400, 3000-3800 Hz) white {string.Join(" ", white.Select(b => b.ToString("E2")))}");
foreach (var (name, shape) in new[] { ("1k", at1k), ("2k", at2k), ("4k", at4k) }) output.WriteLine($"hp {name}: " + string.Join(" ", shape.Select(b => b.ToString("E2"))));
double Rel(double[] shape, int band) => Db(Math.Sqrt(shape[band] / white[band]));
Assert.True(Rel(at2k, 0) < -18, $"2 kHz corner leaves {Rel(at2k, 0):F1} dB at 100-700 Hz");
Assert.InRange(Rel(at2k, 1), -6, -1.5);
Assert.True(Rel(at2k, 2) > -1.5, $"2 kHz corner leaves {Rel(at2k, 2):F1} dB at 3-3.8 kHz");
// A 1 kHz corner passes the 1.6-2.4 kHz band nearly whole; a 4 kHz corner cuts it hard.
Assert.True(Rel(at1k, 1) > -2, $"1 kHz corner: {Rel(at1k, 1):F1} dB at 1.6-2.4 kHz");
Assert.True(Rel(at4k, 1) < -9, $"4 kHz corner: {Rel(at4k, 1):F1} dB at 1.6-2.4 kHz");
}
}

View file

@ -68,7 +68,7 @@ public sealed class NasalCouplingTests
}
private static float Spline(SynthPatch patch, string namePrefix, string surfacePath) =>
patch.ControlSplines.Single(spline => spline.Name.StartsWith(namePrefix, StringComparison.Ordinal) && spline.SurfacePath == surfacePath).Points[0].Value;
patch.ControlSplines.Single(spline => spline.Name.StartsWith(namePrefix, StringComparison.Ordinal) && spline.SurfacePath == surfacePath).Points[^1].Value; // a held place: the last point is the gesture's value whether or not a boundary ramp precedes it
// Distance of a vowel_set consonant constriction from the lip plane in cm, from the constriction_index spline: the surface is a section
// index in [0, sections] and the area model reads position = index / (sections - 1).
@ -91,7 +91,8 @@ public sealed class NasalCouplingTests
[Fact]
public void WithoutVowelSetTheConstrictionStaysOnTheNormalizedPlaceFraction()
{
// The earlier surface semantics are kept for hand-written scripts: the place fraction is the normalized spline value itself.
// The earlier surface semantics are kept for hand-written scripts: the place fraction is the normalized spline value itself. A place
// with a distance in the place table is that distance from the lips over the morphology's length (1 - 2.555 / 17 for /n/, 1 for /m/).
var patch = PatchScript.Parse("""
morphology name=oral length_cm=17 diameters=.6,.8,1.2,1.6,1.3,.9 tongue_index=3 tongue_diameter=1.4 constriction_index=4 constriction_diameter=1 lip_opening=1.5
morphology name=nasal length_cm=12 diameters=.05,.35,.6,.8
@ -107,7 +108,7 @@ public sealed class NasalCouplingTests
vocal network=voice freq=150 gain=.2 sustain=.6
""");
Assert.Equal(.78f, Spline(patch, "en_constriction_index", "/vocal/areas/0/area/constriction_index"));
Assert.Equal(.96f, Spline(patch, "em_constriction_index", "/vocal/areas/0/area/constriction_index"));
Assert.Equal(1 - 2.555f / 17, Spline(patch, "en_constriction_index", "/vocal/areas/0/area/constriction_index"), 5);
Assert.Equal(1f, Spline(patch, "em_constriction_index", "/vocal/areas/0/area/constriction_index"), 5);
}
}

View file

@ -15,7 +15,7 @@ public sealed class PackageBoundaryTests
{
var result = await RunAsync(
"dotnet",
["pack", Path.Combine(root, "src", "AquaSynth.Core", "AquaSynth.Core.csproj"), "-c", "Release", "--no-restore", "-o", outputDir]);
["pack", Path.Combine(root, "src", "AquaSynth.Core", "AquaSynth.Core.csproj"), "-c", "Release", "--no-restore", "-o", outputDir, .. QuietBuildServers]);
Assert.Equal(0, result.ExitCode);
var package = Assert.Single(Directory.GetFiles(outputDir, "AquaSynth.Core.*.nupkg"));
@ -44,7 +44,7 @@ public sealed class PackageBoundaryTests
{
var result = await RunAsync(
"dotnet",
["pack", Path.Combine(root, "src", "AquaSynth.Faust", "AquaSynth.Faust.csproj"), "-c", "Release", "--no-restore", "-o", outputDir]);
["pack", Path.Combine(root, "src", "AquaSynth.Faust", "AquaSynth.Faust.csproj"), "-c", "Release", "--no-restore", "-o", outputDir, .. QuietBuildServers]);
Assert.Equal(0, result.ExitCode);
var package = Assert.Single(Directory.GetFiles(outputDir, "AquaSynth.Faust.*.nupkg"));
@ -97,6 +97,13 @@ public sealed class PackageBoundaryTests
return directory?.FullName ?? throw new InvalidOperationException("could not find repository root");
}
// `dotnet pack` leaves VBCSCompiler and MSBuild node-reuse processes running. They inherit our redirected stdout/stderr pipes, so
// ReadToEndAsync never sees EOF and the test hangs after pack has already written the nupkg (the 2026-11-11 hang). Pack without
// them, and bound every wait so a regression fails with a message instead of hanging.
private static readonly string[] QuietBuildServers = ["-p:UseSharedCompilation=false", "-nodeReuse:false", "--disable-build-servers"];
private static readonly TimeSpan ProcessTimeout = TimeSpan.FromMinutes(5);
private static readonly TimeSpan PipeDrainGrace = TimeSpan.FromSeconds(10);
private static async Task<(int ExitCode, string Stdout, string Stderr)> RunAsync(
string fileName,
IReadOnlyList<string> arguments)
@ -108,12 +115,30 @@ public sealed class PackageBoundaryTests
UseShellExecute = false
};
foreach (var argument in arguments) start.ArgumentList.Add(argument);
start.Environment["MSBUILDDISABLENODEREUSE"] = "1";
start.Environment["DOTNET_CLI_USE_MSBUILD_SERVER"] = "0";
using var process = Process.Start(start) ?? throw new InvalidOperationException($"failed to start `{fileName}`");
var stdout = process.StandardOutput.ReadToEndAsync();
var stderr = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
using var timeout = new CancellationTokenSource(ProcessTimeout);
try
{
await process.WaitForExitAsync(timeout.Token);
}
catch (OperationCanceledException)
{
process.Kill(entireProcessTree: true);
throw new TimeoutException($"`{fileName} {string.Join(' ', arguments)}` did not exit within {ProcessTimeout}.");
}
var drained = Task.WhenAll(stdout, stderr);
if (await Task.WhenAny(drained, Task.Delay(PipeDrainGrace)) != drained)
{
throw new TimeoutException(
$"`{fileName}` exited but its output pipes stayed open for {PipeDrainGrace}: a child it spawned (build server?) inherited them.");
}
return (process.ExitCode, await stdout, await stderr);
}
}

View file

@ -577,6 +577,26 @@ public sealed class PatchScriptTests
timeline.SetFuturePoint("/vocal/nope", timeSeconds: .02f, normalizedValue: .5f, nowSeconds: .0f));
}
[Fact]
public void VowelGestureWithoutVowelSetFailsLoudly()
{
const string tract = """
morphology name=oral length_cm=17 diameters=.6,.8,1.2,1.6,1.3,.9 tongue_index=3 tongue_diameter=1.4 constriction_index=4 constriction_diameter=1 lip_opening=1.5
waveguide_path name=oral_path morphology=oral loss=.998
source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=.05 impedance=.3
constriction_contact name=contact path=oral_path position=.92 opening=.5 resistance=.4 stored_pressure=.1
radiation_load name=mouth path=oral_path aperture=.8 reflection=-.82 impedance=.28
vocal_network name=voice paths=oral_path sources=folds contacts=contact radiation=mouth
phoneme_gesture name=vowel ipa=a start=0 dur=.2 intensity=.7
vocal network=voice freq=150 gain=.2 sustain=.3
""";
var error = Assert.Throws<PatchScriptException>(() => PatchScript.Parse(tract));
Assert.StartsWith("line 7:", error.Message);
Assert.Contains("vowel_set", error.Message);
// With the vowel_set in front of it the same gesture parses.
PatchScript.Parse(tract.Replace("waveguide_path name=oral_path", "vowel_set area_function=oral source=story2008\nwaveguide_path name=oral_path"));
}
[Fact]
public void PhonemeGestureDslEmitsAnatomicalControlSplines()
{

View file

@ -0,0 +1,84 @@
using AquaSynth.Dsl;
using AquaSynth.Faust;
namespace AquaSynth.Dsl.Tests;
// What Meta heard in tract-weak-spots-1 (2026-11-13) while every formant matched: clicks at the phone boundaries of nibu, a /b/ burst the
// length of a fricative, and a first 100 ms that climbed from silence. These pin the three causes at the control-spline and DSP-source
// level (docs/listening/tract-weak-spots-1-analysis-20261113.md); the renders are measured by tools/formant-check/ear_metrics.py.
public sealed class PhoneTransitionTests
{
private static SynthPatch Nibu() => PatchScript.Parse(IpaGestureExperiment.BuildWordScript(
[
(new IpaGestureExperimentTarget("w_n", "n", "", .095f), 1f),
(new IpaGestureExperimentTarget("w_i", "i", "", .18f), 1f),
(new IpaGestureExperimentTarget("w_b", "b", "", .095f), 1f),
(new IpaGestureExperimentTarget("w_u", "u", "", .18f), 1f)
], frequency: 140));
[Fact]
public void NoSurfaceStepsAtAPhoneBoundary()
{
var timeline = new ControlSplineTimeline(Nibu().ControlSplines);
var worst = (Surface: "", Boundary: 0f, Step: 0f);
foreach (var boundary in new[] { .095f, .275f, .37f })
{
foreach (var surface in timeline.SurfacePaths)
{
var step = MathF.Abs(timeline.ValueAt(surface, boundary + .0005f) - timeline.ValueAt(surface, boundary - .0005f));
if (step > worst.Step) worst = (surface, boundary, step);
}
}
// 0.5 ms either side of a boundary; a 30 ms ramp across the full 0..1 range moves 0.017 in that time, a step moves it by the
// whole difference (the pre-fix nibu stepped /vocal/areas/0/area/constriction_diameter by 0.77 at the 95 ms boundary).
Assert.True(worst.Step < .03f, $"{worst.Surface} steps {worst.Step:0.000} at {worst.Boundary} s");
}
[Fact]
public void ThePhoneAfterABoundaryArrivesAtItsFirstValueWithinTheTransition()
{
var timeline = new ControlSplineTimeline(Nibu().ControlSplines);
const string diameter = "/vocal/areas/0/area/constriction_diameter";
var closedN = timeline.ValueAt(diameter, .05f);
Assert.True(closedN < .1f, "the /n/ constriction is shut");
Assert.True(timeline.ValueAt(diameter, .095f + .002f) < .5f, "still closing into the vowel two ms after the boundary");
Assert.Equal(1f, timeline.ValueAt(diameter, .095f + .035f), 2);
}
[Fact]
public void TheFirstPhoneOfAWordStartsAtItsOwnValue()
{
var timeline = new ControlSplineTimeline(Nibu().ControlSplines);
Assert.Equal(timeline.ValueAt("/vocal/areas/0/area/constriction_diameter", 0f), timeline.ValueAt("/vocal/areas/0/area/constriction_diameter", .02f), 3);
}
[Fact]
public void AStopOpensInTwelveMillisecondsNotAThirdOfItsGesture()
{
var timeline = new ControlSplineTimeline(Nibu().ControlSplines);
const string contact = "/vocal/contacts/0/opening";
const float start = .275f, duration = .095f;
Assert.True(timeline.ValueAt(contact, start + duration - .013f) < .1f, "closed until 12 ms before the end");
Assert.True(timeline.ValueAt(contact, start + duration) > .8f, "open at the end");
var opening = 0f;
for (var t = start + .03f; t <= start + duration; t += .0005f)
{
if (timeline.ValueAt(contact, t) > .3f) { opening = t; break; }
}
Assert.True(start + duration - opening < .012f, $"the opening crosses 0.3 only {start + duration - opening:0.000} s before the end");
}
[Fact]
public void ControlSmoothersStartAtTheirInputNotAtZero()
{
var source = FaustEmitter.Emit(Nibu(), new FaustExportOptions("transition_probe")).Source;
Assert.Contains("smoo_init(x) =", source);
Assert.Contains("smoo_init;", source);
// Every control surface and spline-point slider uses it; patch parameters keep si.smoo.
var remaining = source.Split('\n').Where(line => line.Contains("hslider", StringComparison.Ordinal) && line.Contains(": si.smoo;", StringComparison.Ordinal)
&& (line.Contains("\"/vocal/", StringComparison.Ordinal) || line.Contains("\"/splines/", StringComparison.Ordinal))).ToArray();
Assert.Empty(remaining);
}
}

View file

@ -0,0 +1,143 @@
using System.Security.Cryptography;
using System.Text;
using AquaSynth.Dsl;
using AquaSynth.Faust;
using Xunit.Abstractions;
namespace AquaSynth.Dsl.Tests;
// The place table in PatchScript owns where a consonant closes (cm behind the lip plane). Text-level tests: no Faust compile.
public sealed class PlaceTableTests(ITestOutputHelper output)
{
private static string Word(string ipa, string descriptor = "") => IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, descriptor, 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], 140);
private static string Sha(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16];
private static float ConstrictionIndex(string script, string name) =>
PatchScript.Parse(script).ControlSplines
.Single(s => s.Name.StartsWith($"{name}_constriction_index", StringComparison.Ordinal) && s.SurfacePath == "/vocal/areas/0/area/constriction_index").Points[^1].Value; // the held place; a boundary ramp may precede it
// Re-pinned on the phone-transition cut (boundary ramps, 12 ms stop release, smoo_init, vocal attack): these ids moved on purpose; the invariant
// that survives is that a word of labials writes no position surface (below), not these bytes. Faust ids re-pinned again on the PR 52 fix passes (smoo_init pole, pitch-ratio smoother, shut lips for stops, spline handles; the scripts are unchanged; the last move is the smoo_from step line only, which reverts to prev * pole + x * (1 - pole): the old ids come back when that line is put back). Pre-cut values on af0e44f: the vowel_set constriction_index spline value of /b/ and /n/ (and the hash of the whole script and of the
// Faust source for /apa/ and /aba/, which this cut must not change by a byte; the ids are a SHA-256 prefix).
private const float BIndex = 0.8333333f, NIndex = 0.7118056f;
[Fact]
public void PlaceTableKeepsLabialAndAlveolarPositions()
{
var b = ConstrictionIndex(Word("b"), "w_1_c");
var n = ConstrictionIndex(Word("n"), "w_1_c");
output.WriteLine($"b {b:R} n {n:R}");
foreach (var (ipa, scriptSha, faustSha) in new[] { ("p", "0E86DB0F40C0F12A", "358106F493D1783D"), ("b", "A63403EBAAD016FB", "AE80CF31EF1DDC9C") })
{
var script = Word(ipa);
var faust = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("pin", SampleRate: 48000)).Source;
Assert.Equal(scriptSha, Sha(script));
Assert.Equal(faustSha, Sha(faust));
}
Assert.Equal(BIndex, b);
Assert.Equal(NIndex, n);
}
// The side stub is declared only for a word with a lateral: the script and the Faust source of /apa/ /aba/ /ana/ /ata/ are the bytes the scaffold
// gave before the lateral cut (SHA-256 prefixes taken on the head of /k/, 8d50819 plus /d/).
[Fact]
public void ExistingWordsSourcesUnchanged()
{
foreach (var (ipa, scriptSha, faustSha) in new[]
{
("p", "0E86DB0F40C0F12A", "358106F493D1783D"), ("b", "A63403EBAAD016FB", "AE80CF31EF1DDC9C"),
("n", "5C3FA24E40D9DE26", "B2B9C5E1015B60A9"), ("t", "45941CCFD93561B3", "0AACE6D26F648FB0"),
})
{
var script = Word(ipa);
var faust = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("pin", SampleRate: 48000)).Source;
Assert.Equal(scriptSha, Sha(script));
Assert.Equal(faustSha, Sha(faust));
}
Assert.Contains(PatchScript.SideStubBranch, Word("l"));
}
[Fact]
public void UnknownPlaceHasNoDistance()
{
Assert.True(PatchScript.TryPlaceDistanceCentimeters("voiceless_bilabial_plosive", out var lips));
Assert.Equal(0f, lips);
Assert.True(PatchScript.TryPlaceDistanceCentimeters("voiced_alveolar_nasal", out var ridge));
Assert.Equal(2.555f, ridge);
// velar: between the narrowest dorsal section of /u/ (section 26, 6.97 cm from the lips) and the narrowest pharyngeal section of /a/
// (section 13, 12.14 cm); 9.81 cm is the 0.44 fraction of the 17.52 cm tract, which sits within 0.05 cm of the centre of a ladder cell
// (their mean, 9.555 cm, is 0.3 cm from one)
Assert.True(PatchScript.TryPlaceDistanceCentimeters("voiceless_velar_plosive", out var velar));
Assert.InRange(velar, 6.97f, 12.14f);
Assert.Equal(9.81f, velar, 3);
foreach (var descriptor in new[] { "voiced_uvular_fricative", "voiced_palatal_approximant", "voiced_plosive", "" })
{
Assert.False(PatchScript.TryPlaceDistanceCentimeters(descriptor, out var cm), descriptor);
Assert.True(float.IsNaN(cm), $"{descriptor} claims {cm}");
}
}
private static bool HasPositionSurface(string script) =>
PatchScript.Parse(script).ControlSurfaces.Any(surface => surface.Path == "/vocal/contacts/0/position");
private static float[] SitePoints(string script, string name) =>
PatchScript.Parse(script).ControlSplines.Single(s => s.Name.StartsWith($"{name}_burst_site", StringComparison.Ordinal)).Points.Select(p => p.Value).ToArray();
private static string Faust(string script) => FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("site", SampleRate: 48000)).Source;
[Fact]
public void AlveolarBurstGoesInAtTheRidgeAndLabialBurstStaysAtTheGlottalEnd()
{
var t = Word("t", "voiceless_alveolar_plosive");
Assert.True(HasPositionSurface(t));
Assert.All(SitePoints(t, "w_1_c"), v => Assert.Equal(1 - 2.555f / StoryVowelAreas.MeanLengthCentimeters, v, 4));
Assert.Contains("_injection0_site", Faust(t));
// a word of labials never makes the surface: no spline, and the burst joins the glottal path input as before
var p = Word("p");
Assert.False(HasPositionSurface(p));
Assert.DoesNotContain("_injection", Faust(p));
}
[Fact]
public void ALabialAfterAnotherPlosiveInTheSameWordIsPlacedAtTheGlottalEnd()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float s) => new($"w_{label}", ipa, "", s);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_b", "b", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (new IpaGestureExperimentTarget("w_2_t", "t", "voiceless_alveolar_plosive", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_p", "p", 0.095f), 1f)], 140);
Assert.All(SitePoints(script, "w_0_b"), v => Assert.Equal(0f, v));
Assert.All(SitePoints(script, "w_4_p").Skip(1), v => Assert.Equal(0f, v));
// after the 30 ms boundary ramp from the previous plosive's place (the first point is that place)
Assert.All(SitePoints(script, "w_2_t").Skip(1), v => Assert.True(v > 0.8f));
}
[Fact]
public void ATongueSealedStopIsClosedCompletelyUntilItsContactOpensAndALabialKeepsItsOldSpline()
{
float[] Diameter(string script) => PatchScript.Parse(script).ControlSplines
.Single(s => s.Name.StartsWith("w_1_c_constriction_diameter", StringComparison.Ordinal)).Points.Select(p => p.Value).ToArray();
var t = PatchScript.Parse(Word("t", "voiceless_alveolar_plosive")).ControlSplines
.Single(s => s.Name.StartsWith("w_1_c_constriction_diameter", StringComparison.Ordinal)).Points;
// lead-in (the vowel's open 1), arrival, closure hold, end: shut from the arrival to the hold, and the hold ends StopReleaseSeconds before the stop does
Assert.Equal(1f, t[0].Value);
Assert.Equal(0f, t[1].Value);
Assert.Equal(0f, t[2].Value);
Assert.Equal(1 - 0.012f / 0.095f, (t[2].TimeSeconds - 0.18f) / 0.095f, 3);
var b = Diameter(Word("b"));
Assert.True(b[1] > 0 && Math.Abs(b[1] - b[2]) < 1e-6f, "the lip-sealed stop keeps the 0.03 aperture spline (its source text is pinned)");
}
[Fact]
public void VelarBurstGoesInAtTheVelarPlaceAndFurtherBackThanTheRidge()
{
var k = Word("k", "voiceless_velar_plosive");
Assert.True(HasPositionSurface(k));
Assert.All(SitePoints(k, "w_1_c"), v => Assert.Equal(1 - 9.81f / StoryVowelAreas.MeanLengthCentimeters, v, 4));
Assert.Contains("_injection0_site", Faust(k));
Assert.Equal(1 - 9.81f / StoryVowelAreas.MeanLengthCentimeters, ConstrictionIndex(k, "w_1_c") / BIndex, 4);
}
}

View file

@ -28,4 +28,14 @@ public sealed class ProbeTimelineSampleRateTests
Assert.Equal(0.1752f / 325 * 48000, Delay(2, 48000), 3);
Assert.Equal(0.1752f / 550 * 44100, Delay(2, 44100), 3);
}
[Fact]
public void EmittedSourceFollowsTheRequestedSampleRate()
{
// The vocal ladder's delay-line lengths are length / speed * rate samples, so the emitted DSP carries the rate it was asked for.
var at48 = FaustEmitter.EmitScript(TimelineScript, new FaustExportOptions("rate_probe", SampleRate: 48000)).Source;
var at44 = FaustEmitter.EmitScript(TimelineScript, new FaustExportOptions("rate_probe", SampleRate: 44100)).Source;
Assert.NotEqual(at48, at44);
Assert.Equal(at48, FaustEmitter.EmitScript(TimelineScript, new FaustExportOptions("rate_probe")).Source);
}
}

View file

@ -0,0 +1,44 @@
using AquaSynth.Dsl;
namespace AquaSynth.Dsl.Tests;
// sfxr's repeat restarts the pitch slide and the arpeggio; it does not restart the envelope. Before this, `patch repeat` wrapped the
// whole age, so a repeat shorter than sustain+decay never reached the release (the 2026-11-11 explosion/golf/powerup finding).
public sealed class RepeatLoweringTests
{
private const string Script = """
patch repeat=0.11315
voice
wave=sine
freq=57.5946
sustain=0.1306122449
decay=0.1777777778
pitch_ramp=-0.208544
arp_delay=0.05
arp_mult=1.5
""";
[Fact]
public void RepeatWrapsPitchAndArpeggioAgeButNotTheEnvelope()
{
var source = FaustEmitter.EmitScript(Script).Source;
Assert.Contains("age = time;", source);
Assert.DoesNotContain("floor(time /", source);
Assert.Contains("voice_0_pitch_age = voice_0_age - floor(voice_0_age / repeat_interval) * repeat_interval;", source);
Assert.Contains("0.208544", source);
Assert.Contains("* voice_0_pitch_age", source);
Assert.Contains("select2(voice_0_pitch_age <", source);
Assert.Contains("oneshot_adsr_at(voice_0_age,", source);
Assert.DoesNotContain("oneshot_adsr_at(voice_0_pitch_age", source);
}
[Fact]
public void WithoutRepeatThereIsNoPitchAge()
{
var source = FaustEmitter.EmitScript(Script.Replace("patch repeat=0.11315\n", "")).Source;
Assert.DoesNotContain("pitch_age", source);
Assert.DoesNotContain("repeat_interval", source);
}
}

View file

@ -180,6 +180,8 @@ public sealed class SpeechDistributedTrainingTests
Assert.True(after < before, $"expected CultMesh worker gradients to reduce loss; before={before}, after={after}");
Assert.Single(payloads);
Assert.Equal(SpeechCultMeshRoles.RenderWorker, payloads[0].WorkerRole);
// One payload, four receipts: PayloadId is a role (many rows share it), not a unique index (CultLib #90).
Assert.Equal(4, admissions.Count(receipt => receipt.PayloadId == "payload-cultmesh-0001"));
Assert.Equal(2, admissions.Count(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Admitted));
Assert.Equal(2, admissions.Count(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Rejected));
Assert.All(admissions.Where(receipt => receipt.Status == SpeechWorkerAdmissionStatus.Admitted), receipt => Assert.NotEmpty(receipt.AssignedRequestIds));
@ -284,6 +286,30 @@ public sealed class SpeechDistributedTrainingTests
return loss / actual.Count;
}
[Fact]
public async Task OneRequestMayHaveAFailedAndAScoredResultInTheSameStore()
{
var directory = TempDirectory();
try
{
var resultStore = Path.Combine(directory, "speech-results.cc");
var request = SpeechDistributedTrainingCoordinator.CreateRenderRequests("batch-roles", Pipeline(), TrainingSet())[0];
var scored = SpeechDistributedTrainingCoordinator.ScoreControlVectorRequests([request], "worker-a");
var failed = SpeechDistributedTrainingCoordinator.ScoreControlVectorRequests([request with { CandidateControlVector = [] }], "worker-b");
await SpeechDistributedTrainingCultCacheStore.UpsertResultsAsync(resultStore, [.. scored, .. failed]);
// RequestId is a role: a retried request keeps its failed result beside the later scored one (CultLib #90 makes CultIndex unique).
var loaded = await SpeechDistributedTrainingCultCacheStore.ReadResultsAsync(resultStore);
Assert.Equal(2, loaded.Count(result => result.RequestId == request.RequestId));
Assert.Contains(loaded, result => result.Status == SpeechRenderStatus.Failed);
Assert.Contains(loaded, result => result.Status == SpeechRenderStatus.Succeeded);
}
finally
{
Directory.Delete(directory, recursive: true);
}
}
private static string TempDirectory()
{
var path = Path.Combine(Path.GetTempPath(), $"aquasynth-speech-distributed-{Guid.NewGuid():N}");

View file

@ -0,0 +1,183 @@
using AquaSynth.Dsl;
using AquaSynth.Faust;
using Xunit.Abstractions;
namespace AquaSynth.Dsl.Tests;
// Renders behind the tract-coarticulation findings of the PR 52 Soul pass: what the closing ramp into a stop sounds like, what the DSP
// does with a stop's 12 ms opening, and what the control smoothers and the word attack do at the start of a render. Each reads the
// rendered signal (or the DSP's own probe), not the emitted text.
[Collection("NativeFaust")]
public sealed class StopClosureAndControlRenderTests(ITestOutputHelper output)
{
private const int Rate = 48000;
private static AquaSynthCompiledPatch? Compile(string source, float seconds)
{
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("stop_closure", "stop_closure", ""), source, seconds, out var patch, out var error))
{
Assert.Fail($"compile failed: {error}");
}
return patch;
}
private static string Word(string ipa) => IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], 140);
// Power above 4 kHz (100 Hz grid to 12 kHz) of a Hann-windowed stretch.
private static double HighPower(float[] x, double from, double to)
{
var a = (int)(from * Rate);
var n = (int)((to - from) * Rate);
var seg = Enumerable.Range(0, n).Select(i => x[a + i] * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (n - 1)))).ToArray();
double sum = 0;
for (var hz = 4000; hz < 12000; hz += 100)
{
double re = 0, im = 0;
for (var i = 0; i < n; i++) { var w = 2 * Math.PI * hz * i / Rate; re += seg[i] * Math.Cos(w); im -= seg[i] * Math.Sin(w); }
sum += re * re + im * im;
}
return sum;
}
// The 30 ms boundary ramp into a stop moves the contact, constriction and lip surfaces through every aperture between open and shut. The
// burst noise is 4 * opening * (1 - opening) times a gain, and the gain was held through the closure, so each of those passes was a 15-20 ms
// hiss before the stop. The interval is the stop's start to its release, against the same length of the vowel before it, in the >4 kHz
// band, with the glottal source silent and the burst gain kept: the voiced stops' own voicing runs through the ramp and its harmonics
// fill that band (/d/ read -11.6 dB with the source on and -52.8 with it off; with the source on it swings between -13.5 and -9.3 dB
// with f0 alone, 139.5 to 145 Hz, as the harmonics fall on and off the 100 Hz grid), so with the source on the measure cannot tell the
// voicing from the hiss. Source off, the burst gain held through the closure read +5 dB (/p/) and +14 dB (/t/, /d/) on 3b62b9c; gated,
// every stop reads -52 dB. -30 is the bound between the two. /g/ is not here: it is not in TryIpaDescriptor, so it would render the default approximant and could not fail.
[FaustTheory]
[InlineData("p")]
[InlineData("b")]
[InlineData("t")]
[InlineData("d")]
[InlineData("k")]
public void ClosingIntoAStopMakesNoHighFrequencyNoise(string ipa)
{
var parsed = PatchScript.Parse(Word(ipa));
var voiceless = parsed with
{
ControlSplines = parsed.ControlSplines.Select(s => s.Name.StartsWith("w_1_c_source_level", StringComparison.Ordinal)
? s with { Points = s.Points.Select(q => q with { Value = 0, OutValue = 0, InValue = 0 }).ToArray() }
: s).ToArray()
};
using var patch = Compile(FaustEmitter.Emit(voiceless, new FaustExportOptions("stop_closure", SampleRate: Rate)).Source, 0.5f);
var x = patch!.Render(0.5f);
const double from = 0.18;
var release = PatchScript.StopReleaseStartSeconds(0.095f);
var closing = HighPower(x, from, from + release);
var vowel = HighPower(x, from - release, from);
var db = 10 * Math.Log10(closing / vowel);
output.WriteLine($"/{ipa}/ >4 kHz energy of the closing interval {db:F1} dB re the vowel's before it, source silent");
Assert.True(db < -30, $"/{ipa}/ closes with {db:F1} dB re the vowel's own >4 kHz energy");
}
// The Faust lowering of a Bezier segment ignores the handle times and runs the curve on the linear fraction of the segment; the C# timeline
// solves the curve's time, so a handle longer than the segment folds it. The stop's 12 ms opening had 23.75 ms handles: the contact opening
// read 0.05 to 0.87 between 6 and 7 ms in C# and 0.46 to 0.57 in the DSP. This reads the opening through the DSP's own contact reservoir probe
// (stored pressure + (1 - opening) * resistance, both at their defaults once the other splines are dropped) and compares it with the timeline.
[FaustFact]
public void TheDspRendersTheStopOpeningAsTheTimelineEvaluatesIt()
{
var script = Word("p");
var parsed = PatchScript.Parse(script);
var contact = parsed.ControlSplines.Where(s => s.SurfacePath == "/vocal/contacts/0/opening").ToArray();
var alone = parsed with { ControlSplines = contact };
var timeline = new ControlSplineTimeline(contact);
var source = FaustEmitter.Emit(alone, new FaustExportOptions("stop_opening", SampleRate: Rate, DebugProbeUi: true)).Source;
using var patch = Compile(source, 0.5f);
using var stream = patch!.CreateStreamingPatch();
var reservoir = stream.ProbePaths.Single(p => p.EndsWith("/contact/contact/reservoir", StringComparison.Ordinal));
var release = 0.18f + PatchScript.StopReleaseStartSeconds(0.095f);
var outputs = new[] { new float[48] };
var dsp = new List<(float Time, float Reservoir)>();
for (var block = 0; block < 400; block++)
{
stream.ProcessBlock([], outputs, 48);
var t = (block + 1) * 48f / Rate;
if (t >= release - 0.004f && t <= release + 0.016f) dsp.Add((t, stream.ReadProbe(reservoir)));
}
// reservoir is linear in the opening; scale it by its own end points
var shut = dsp.First().Reservoir;
var open = dsp.Last().Reservoir;
var worst = 0f;
foreach (var (time, value) in dsp)
{
var dspOpening = (value - shut) / (open - shut);
var curve = timeline.ValueAt("/vocal/contacts/0/opening", time);
var shutValue = timeline.ValueAt("/vocal/contacts/0/opening", dsp.First().Time);
var openValue = timeline.ValueAt("/vocal/contacts/0/opening", dsp.Last().Time);
var timelineOpening = (curve - shutValue) / (openValue - shutValue);
worst = MathF.Max(worst, MathF.Abs(dspOpening - timelineOpening));
}
output.WriteLine($"worst difference between the DSP's opening and the timeline's over the release: {worst:F3}");
Assert.True(worst < 0.08f, $"the DSP's stop opening departs from the timeline by {worst:F3}");
}
// The same fact without the DSP: every handle of an authored spline is a third of its segment, so the C# curve is the curve the lowering runs.
[Fact]
public void EveryAuthoredSplineHandleIsAThirdOfItsSegment()
{
var splines = PatchScript.Parse(Word("p")).ControlSplines.Where(s => s.Points.Count > 1).ToArray();
Assert.NotEmpty(splines);
foreach (var spline in splines)
{
for (var i = 0; i + 1 < spline.Points.Count; i++)
{
var third = (spline.Points[i + 1].TimeSeconds - spline.Points[i].TimeSeconds) / 3;
Assert.Equal(third, spline.Points[i].OutTimeOffsetSeconds, 5);
Assert.Equal(third, spline.Points[i + 1].InTimeOffsetSeconds, 5);
}
}
}
// Replaces the emitted patch's process with one control through the emitted smoo_init, so the smoother under test is the one the exporter
// writes. Starts at its input at sample 0, and moves at si.smoo's 22.7 ms time constant when the control moves (5 ms gave 0.89 here).
[FaustFact]
public void ASmootherStartsAtItsInputAndMovesAtSiSmoosPace()
{
var emitted = FaustEmitter.Emit(PatchScript.Parse(Word("p")), new FaustExportOptions("smoo", SampleRate: Rate)).Source;
var lines = emitted.Split('\n').Select(l => l.StartsWith("process =", StringComparison.Ordinal) ? "process = hslider(\"/vocal/sources/0/pressure\", 0.7, 0, 1, 0.001) : smoo_init;" : l);
using var patch = Compile(string.Join('\n', lines), 0.2f);
using var stream = patch!.CreateStreamingPatch();
var first = new[] { new float[480] };
stream.ProcessBlock([], first, 480);
output.WriteLine($"sample 0 {first[0][0]:F4}, after 10 ms {first[0][479]:F4}");
Assert.Equal(0.7f, first[0][0], 4);
Assert.Equal(0.7f, first[0][479], 4);
var after = new[] { new float[240] };
stream.ProcessBlock([], after, 240, new Dictionary<string, float> { ["/vocal/sources/0/pressure"] = 1f });
// 5 ms into a step from 0.7 to 1 with a 22.7 ms time constant
var expected = 0.7 + 0.3 * (1 - Math.Pow(1 - 44.1 / Rate, 0.005 * Rate));
output.WriteLine($"5 ms after a step to 1: {after[0][239]:F4}, si.smoo would be {expected:F4}");
Assert.InRange(after[0][239], expected - 0.01, expected + 0.01);
}
// A word starts with a 12 ms attack, not a step: the control smoothers no longer fade it in, and a step onset would be a click.
[FaustFact]
public void AWordBeginsWithATwelveMillisecondAttack()
{
double FirstMillisecondsPeak(string script)
{
using var patch = Compile(FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("attack", SampleRate: Rate)).Source, 0.4f);
var x = patch!.Render(0.4f);
var steady = x.Skip((int)(0.05 * Rate)).Take((int)(0.1 * Rate)).Max(Math.Abs);
return x.Take((int)(0.002 * Rate)).Max(Math.Abs) / steady;
}
var script = IpaGestureExperiment.BuildWordScript([(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.3f), 1f)], 140);
Assert.Contains("attack=.012", script);
var attacked = FirstMillisecondsPeak(script);
var stepped = FirstMillisecondsPeak(script.Replace("attack=.012 ", "", StringComparison.Ordinal));
output.WriteLine($"peak of the first 2 ms re the steady peak: with the attack {attacked:F3}, without {stepped:F3}");
Assert.True(attacked < 0.25, $"the first 2 ms reach {attacked:F2} of the steady peak");
Assert.True(stepped > 2 * attacked, "without the attack the onset is a step");
}
}

View file

@ -11,25 +11,24 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
{
private const int Rate = 48000;
private static float[]? Render(string script, float seconds, Func<SynthPatch, SynthPatch>? edit = null)
private static float[] Render(string script, float seconds, Func<SynthPatch, SynthPatch>? edit = null)
{
var parsed = PatchScript.Parse(script);
var source = FaustEmitter.Emit(edit is null ? parsed : edit(parsed), new FaustExportOptions("stress_release", SampleRate: Rate)).Source;
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("stress_release", "stress_release", ""), source, seconds, out var patch, out var error))
{
if (error?.Contains("Faust toolchain not found", StringComparison.OrdinalIgnoreCase) == true ||
error?.Contains("Faust DLL not found", StringComparison.OrdinalIgnoreCase) == true)
{
return null;
}
Assert.Fail($"compile failed: {error}");
}
using (patch) return patch!.Render(seconds);
}
// The stop's release time and the start of its closure (every articulator at its shut value, after the boundary ramp into it), both from the
// one owner in PatchScript rather than as fractions of the gesture; the consonant is [from, to).
private static double ReleaseAt(double from, double to) => from + PatchScript.StopReleaseStartSeconds((float)(to - from));
private static double ClosureFrom(double from) => from + PatchScript.PhoneTransitionSeconds;
private static double Rms(float[] x, double from, double to)
{
var a = (int)(from * Rate);
@ -57,52 +56,52 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
return (double)Rate / bestLag;
}
[Fact]
[FaustFact]
public void SourcePitchRatioScalesTheRenderedF0()
{
var f0 = (float ratio) =>
{
var script = IpaGestureExperiment.BuildWordScript([(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.5f, PitchRatio: ratio), 1f)], 110);
var x = Render(script, 0.6f);
return x is null ? double.NaN : F0(x, 0.2, 0.5);
return F0(x, 0.2, 0.5);
};
var unity = f0(1f);
var up = f0(1.5f);
output.WriteLine($"f0 at ratio 1: {unity:F1}, ratio 1.5: {up:F1}");
if (double.IsNaN(unity)) return;
Assert.InRange(unity, 108, 112);
Assert.InRange(up, 163, 167);
}
[Fact]
[FaustFact]
public void IntensityIsAnAmplitudeFactorOnTheRenderedLevel()
{
double Level(float intensity)
{
var script = IpaGestureExperiment.BuildWordScript([(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.5f), intensity)], 110);
var x = Render(script, 0.6f);
return x is null ? double.NaN : Rms(x, 0.3, 0.5);
return Rms(x, 0.3, 0.5);
}
var unity = Level(1f);
var stressed = Level(1.26f);
if (double.IsNaN(unity)) return;
var amplitude = WeksaWordPlan.CueFor(WeksaStress.Primary).Amplitude;
var stressed = Level(amplitude);
var db = 20 * Math.Log10(stressed / unity);
output.WriteLine($"level at intensity 1.26 against 1: {db:F2} dB (factor wanted {20 * Math.Log10(1.26):F2})");
Assert.InRange(db, 1.7, 2.3);
output.WriteLine($"level at the primary-stress amplitude against 1: {db:F2} dB (factor wanted {20 * Math.Log10(amplitude):F2})");
var wanted = 20 * Math.Log10(amplitude);
Assert.InRange(db, wanted - 0.3, wanted + 0.3);
}
[Fact]
[FaustFact]
public void PlosiveReleaseBurstIsAboveTheClosureAndBelowTheFollowingVowel()
{
var script = IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_b", "b", "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_1_a", "a", "", 0.18f), 1f)], 140);
var withBurst = Render(script, 0.4f);
var withoutBurst = Render(script, 0.4f, p => p with { ControlSplines = p.ControlSplines.Where(s => !s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal)).ToArray() });
if (withBurst is null || withoutBurst is null) return;
// Everything but the burst's noise is deterministic and shared, so the difference of the two renders is the burst alone.
var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray();
const double releaseFrom = 0.095 * 0.65, vowelFrom = 0.095;
const double vowelFrom = 0.095;
var releaseFrom = ReleaseAt(0, vowelFrom);
var vowelPeak = Peak(withBurst, vowelFrom + 0.06, vowelFrom + 0.18);
var burstPeak = Peak(burst, releaseFrom, vowelFrom + 0.01);
var burstBeforeRelease = Peak(burst, 0, releaseFrom - 0.005);
@ -114,12 +113,95 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
Assert.True(burstPeak < vowelPeak / 2, "the burst stays well under the following vowel's peak (the b level fix)");
}
// /ɑ C ɑ/ at the scaffold's own durations (vowel 0.18 s, consonant 0.095 s). Returns the render and the consonant's [start, end).
private (float[]? Samples, double From, double To) VowelConsonantVowel(string ipa, float frequency = 140)
// The burst is noise whose amplitude is release_flow times the stored pressure through the opening, and release_flow was held at its
// gain from the plosive's gesture on, so it never ended: every later contact state made noise too. In /bin/ the "burst" alone (the
// difference of the renders with and without release_flow) peaked at 0.0302 in the final /n/ and the tail, above its 0.0226 at the
// release itself, and in /nibu/ the leading /n/ and /i/ carried it backward (a spline holds its first value before its first point).
[FaustFact]
public void PlosiveBurstExistsOnlyAroundItsOwnRelease()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_b", "b", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140);
var withBurst = Render(script, 0.77f);
var withoutBurst = Render(script, 0.77f, p => p with { ControlSplines = p.ControlSplines.Where(s => !s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal)).ToArray() });
var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray();
const double bFrom = 0.275, bTo = 0.37;
var atRelease = Peak(burst, ReleaseAt(bFrom, bTo) - 0.003, bTo + 0.02);
var leading = Peak(burst, 0, bFrom);
var trailing = Peak(burst, bTo + 0.12, 0.77);
output.WriteLine($"burst peak {atRelease:F4} at the release, {leading:F4} before the plosive (n, a), {trailing:F4} after it (a, n, tail)");
Assert.True(atRelease > 0.004, "the burst is still there at the release");
Assert.True(leading < atRelease / 20, "no burst noise before the plosive's own gesture");
Assert.True(trailing < atRelease / 10, "no burst noise in the vowel, the nasal and the tail after the plosive");
}
// The burst gain's window, read off the spline itself: it exists only from the stop's release start, one ramp (0.15 of the release window)
// before it and one after the stop's end. A gain held through the closure made the closing ramp a hiss (ClosingIntoAStopMakesNoHighFrequencyNoise).
[Fact]
public void PlosiveBurstGainWindowIsOneRampEitherSideOfTheRelease()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_b", "b", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140);
var window = PatchScript.Parse(script).ControlSplines.Single(s => s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal) && s.Points.Any(p => p.Value > 0));
const double start = 0.275, duration = 0.095;
var release = start + PatchScript.StopReleaseStartSeconds((float)duration);
var ramp = 0.15 * (start + duration - release);
Assert.Equal((release - ramp, start + duration + ramp), (window.Points.Min(p => (double)p.TimeSeconds), window.Points.Max(p => (double)p.TimeSeconds)), new TupleTolerance(1e-4));
}
// The contact opening, the tongue's constriction and the lips all leave their shut value at the instant the burst gain window opens: one
// owner, StopReleaseStartSeconds. Read off the splines, so a stale constant in one of them (the contact opening 20 ms early while the
// burst keeps the owner's time) fails here and not only through a closure level that happens to cross a bound.
[Theory]
[InlineData("b", "w_2_b")]
[InlineData("t", "w_2_t")]
[InlineData("k", "w_2_k")]
public void AStopsArticulatorsOpenWhereItsBurstGainWindowOpens(string ipa, string name)
{
IpaGestureExperimentTarget Phone(string label, string symbol, float seconds) => new($"w_{label}", symbol, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone($"2_{ipa}", ipa, 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f)], 140);
var splines = PatchScript.Parse(script).ControlSplines;
const double start = 0.275, duration = 0.095;
var release = start + PatchScript.StopReleaseStartSeconds((float)duration);
var gain = splines.Single(s => s.Name.StartsWith(name, StringComparison.Ordinal) && s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal));
var ramp = 0.15 * (start + duration - release);
Assert.Equal(release - ramp, gain.Points.Min(p => (double)p.TimeSeconds), 1e-4);
var paths = ipa == "b"
? new[] { "/vocal/contacts/0/opening", "/vocal/areas/0/area/constriction_diameter", "/vocal/areas/0/area/lip_opening", "/vocal/radiation/0/aperture" }
: ["/vocal/contacts/0/opening", "/vocal/areas/0/area/constriction_diameter"];
foreach (var path in paths)
{
var spline = splines.Single(s => s.Name.StartsWith(name, StringComparison.Ordinal) && s.SurfacePath == path);
Assert.Equal(release, spline.Points.Where(p => p.TimeSeconds < start + duration - 1e-6).Max(p => (double)p.TimeSeconds), 1e-4);
}
}
// The nasal keeps its murmur's small lip opening where a stop shuts the lips (0.04 cm against 0): the shut-lip term is the stop's only.
// Extending it to nasals moves /m/'s first nasal formant by 30 Hz and its murmur level by 0.4 dB and no render test notices, so the
// value is read off the splines.
[Theory]
[InlineData("m", 0.04f)]
[InlineData("b", 0f)]
public void OnlyAStopShutsTheLipsCompletely(string ipa, float shut)
{
var script = IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], frequency);
return (Render(script, 0.5f), 0.18, 0.275);
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], 140);
foreach (var path in new[] { "/vocal/areas/0/area/lip_opening", "/vocal/radiation/0/aperture" })
{
var spline = PatchScript.Parse(script).ControlSplines.Single(s => s.Name.StartsWith("w_1_c", StringComparison.Ordinal) && s.SurfacePath == path);
Assert.Equal(shut, spline.Points.Min(p => p.Value), 1e-4);
}
}
// /ɑ C ɑ/ at the scaffold's own durations (vowel 0.18 s, consonant 0.095 s). Returns the render and the consonant's [start, end).
private (float[]? Samples, double From, double To) VowelConsonantVowel(string ipa, float frequency = 140, string descriptor = "", Func<SynthPatch, SynthPatch>? edit = null)
{
var script = IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, descriptor, 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], frequency);
return (Render(script, 0.5f, edit), 0.18, 0.275);
}
// Level of the consonant's middle 60 percent against the mean power of the steady parts of the two flanking vowels (the 70 ms before the
@ -138,13 +220,12 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
// read -3.8 dB while its alveolar closure began to open at half the gesture, a third before the velum and the contact did (now held to
// 0.8: /n/ -8.8, /m/ -12.8), and once the nasal junction sat on its own interface the nose took its share and both read -2.2 and -4.2 dB
// until the nasal path carried its real damping (loss .975 per cell; /m/ -11.8, /n/ -9.6).
[Theory]
[FaustTheory]
[InlineData("m")]
[InlineData("n")]
public void NasalMurmurIsWellBelowTheFlankingVowels(string ipa)
{
var (x, from, to) = VowelConsonantVowel(ipa);
if (x is null) return;
var db = ConsonantDbReVowels(x, from, to);
output.WriteLine($"/{ipa}/ murmur {db:F1} dB re the flanking vowels");
Assert.InRange(db, -16, -8);
@ -153,7 +234,7 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
// The primary-stress cue as the plan applies it (amplitude and f0 ratio, same vowel length) against the unstressed vowel, over five vowels:
// the f0 rise alone moves the harmonics against F1 and the level by -1.3 to +1.8 dB by vowel, so the amplitude factor is held to the mean
// rendered result, 2 dB (Sluijter and van Heuven 1996: 1 to 3 dB overall). Measured 1.7 dB with the amplitude at 1.26 (outside the band), 2.0 dB at 1.30.
[Fact]
[FaustFact]
public void PrimaryStressRendersAboutTwoDecibelsLouderOnAverageOverVowels()
{
var cue = WeksaWordPlan.CueFor(WeksaStress.Primary);
@ -164,11 +245,10 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
{
var script = IpaGestureExperiment.BuildWordScript([(new IpaGestureExperimentTarget($"w_0_{vowel}", vowel, "", 0.25f, PitchRatio: ratio), intensity)], 140, 0.2f);
var x = Render(script, 0.45f);
return x is null ? double.NaN : Rms(x, 0.12, 0.22);
return Rms(x, 0.12, 0.22);
}
var flat = Level(1f, 1f);
if (double.IsNaN(flat)) return;
var db = 20 * Math.Log10(Level(cue.PitchRatio, cue.Amplitude) / flat);
output.WriteLine($"/{vowel}/ stressed against unstressed: {db:F2} dB");
diffs.Add(db);
@ -190,17 +270,368 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
// mouth is shut, so all that gets out is the tract wall radiation of the voiced source: the voice bar, about 30 dB under the vowel for /b/
// (a DESIGN value, no primary level retrieved; Stevens 1998 per secondary sources has voicing weaker as transglottal pressure falls), and
// near-silent for /p/, whose source is weak. The closure was 0.0000 (below 16 bits) before the wall radiation.
[Theory]
[FaustTheory]
[InlineData("b", -34, -26)]
[InlineData("p", -60, -38)]
[InlineData("d", -34, -26)]
public void PlosiveClosureCarriesTheVoiceBarOnlyWhenVoiced(string ipa, double lowDb, double highDb)
{
var db = VoiceBarDb(ipa);
if (double.IsNaN(db)) return;
output.WriteLine($"/{ipa}/ closure {db:F1} dB re the following vowel");
Assert.InRange(db, lowDb, highDb);
}
// The closure's deviation (the slow offset of a shutting tract is not sound) against the following vowel's, for a word-initial consonant.
private double VoiceBarDb(string ipa)
{
var script = IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_c", ipa, "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_1_a", "a", "", 0.18f), 1f)], 140);
var x = Render(script, 0.4f);
return x is null ? double.NaN : 20 * Math.Log10(Math.Max(1e-9, Deviation(x, 0.03, 0.058)) / Deviation(x, 0.15, 0.25));
}
private static SynthPatch WithoutBurst(SynthPatch p) =>
p with { ControlSplines = p.ControlSplines.Where(s => !s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal)).ToArray() };
// The closure of a stop is the part after the boundary ramp into it and before its release, without the burst (the ramp is the tract still
// shutting on the vowel's decaying voicing; its noise is measured by ClosingIntoAStopMakesNoHighFrequencyNoise).
// A tongue closure at the nasal's 0.03 cm aperture leaked: /t/ read -14.3 dB re the flanking vowels against /p/ -22.1 (the lips seal /p/);
// completely closed it reads -24.3.
[Fact]
public void ATongueSealedStopClosureIsAsQuietAsTheLipSealedOne()
{
double Closure(string ipa, string descriptor)
{
var (x, from, to) = VowelConsonantVowel(ipa, descriptor: descriptor, edit: WithoutBurst);
if (x is null) return double.NaN;
var vowels = Math.Sqrt((Math.Pow(Rms(x, from - 0.08, from - 0.01), 2) + Math.Pow(Rms(x, to + 0.03, to + 0.12), 2)) / 2);
return 20 * Math.Log10(Rms(x, ClosureFrom(from), ReleaseAt(from, to)) / vowels);
}
var p = Closure("p", "voiceless_bilabial_plosive");
var t = Closure("t", "voiceless_alveolar_plosive");
output.WriteLine($"closure re vowels: /p/ {p:F1} dB, /t/ {t:F1} dB");
if (double.IsNaN(p)) return;
Assert.True(t <= p + 1, $"the /t/ closure ({t:F1} dB) is as quiet as /p/ ({p:F1} dB)");
}
[Fact]
public void ATongueSealedStopBurstStaysUnderHalfTheFollowingVowel()
{
var (x, from, to) = VowelConsonantVowel("t", descriptor: "voiceless_alveolar_plosive");
var (nb, _, _) = VowelConsonantVowel("t", descriptor: "voiceless_alveolar_plosive", edit: WithoutBurst);
if (x is null || nb is null) return;
var burst = x.Zip(nb, (a, b) => a - b).ToArray();
var peak = Peak(burst, ReleaseAt(from, to) - 0.003, to + 0.01);
var vowel = Peak(x, to + 0.06, to + 0.17);
output.WriteLine($"/t/ burst peak {peak:F4}, vowel peak {vowel:F4}, ratio {peak / vowel:F2}");
Assert.True(peak > 0.004, "audible");
Assert.True(peak < vowel / 2, "under half the following vowel's peak, as /b/");
}
// The /b/ test over the alveolar stop, by its table entry (before the entry the phone was unsupported, and a hand script approximated it).
[Fact]
public void AlveolarStopBurstExistsOnlyAroundItsOwnRelease_t()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_t", "t", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140);
var withBurst = Render(script, 0.77f);
var withoutBurst = Render(script, 0.77f, WithoutBurst);
if (withBurst is null || withoutBurst is null) return;
var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray();
const double tFrom = 0.275, tTo = 0.37;
var atRelease = Peak(burst, ReleaseAt(tFrom, tTo) - 0.003, tTo + 0.02);
var leading = Peak(burst, 0, tFrom);
var trailing = Peak(burst, tTo + 0.12, 0.77);
output.WriteLine($"/t/ burst peak {atRelease:F4} at the release, {leading:F5} before the plosive, {trailing:F5} after it");
Assert.True(atRelease > 0.004, "the burst is a transient of audible size");
Assert.True(leading < atRelease / 20, "no burst before the plosive's own gesture");
Assert.True(trailing < atRelease / 10, "no burst after the plosive");
}
// Chodroff and Wilson 2014: /t/ burst peak 5216 Hz, /k/ 2868. The band 3.5 to 7 kHz is a DESIGN tolerance around the /t/ figure.
// Peak of the isolated burst's spectrum from 1 kHz up (the weak_spots.burst_spectrum definition: 20 ms Hann window from the release, 400 Hz smoothing).
[Fact]
public void StopTBurstSpectrumIsInTheLiteratureBand()
{
var (x, from, to) = VowelConsonantVowel("t");
var (nb, _, _) = VowelConsonantVowel("t", edit: WithoutBurst);
if (x is null || nb is null) return;
var start = (int)(ReleaseAt(from, to) * Rate);
const int n = 960;
var seg = Enumerable.Range(0, n).Select(i => (x[start + i] - nb[start + i]) * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (n - 1)))).ToArray();
double Power(double hz)
{
double re = 0, im = 0;
for (var i = 0; i < n; i++) { var a = 2 * Math.PI * hz * i / Rate; re += seg[i] * Math.Cos(a); im -= seg[i] * Math.Sin(a); }
return re * re + im * im;
}
var grid = Enumerable.Range(0, 180).Select(k => 1000.0 + 50 * k).ToArray();
var power = grid.Select(Power).ToArray();
var smooth = power.Select((_, k) => Enumerable.Range(Math.Max(0, k - 4), Math.Min(9, power.Length - Math.Max(0, k - 4))).Average(j => power[j])).ToArray();
var peak = grid[Array.IndexOf(smooth, smooth.Max())];
output.WriteLine($"/t/ burst spectral peak {peak:F0} Hz");
Assert.InRange(peak, 3500, 7000);
}
// /k/ over the /t/ tests: its own place (the velar distance in the place table), closure sealed by the tongue, burst under half the vowel.
// The spec asks /k/'s closure to be at or below /p/'s. With the voiceless source as /p/ and /t/ have it, it is not, and was not on main
// either (-14.9 dB re the vowels, /p/ -20.4): the 150 Hz voicing reaches the output through a closure that leaves only a short rear cavity.
// Silencing voicing in voiceless stops would change /p/ and /t/ (pinned byte for byte), so the criterion stays unmet (fork).
// The measure is the source-on closure in its settled part (25 ms after the 30 ms closing ramp has finished, to 5 ms before the release),
// because the source-off closure cannot see a leak: with the source off nothing drives the tract, and leaks of .02, .05 and .1 of the
// diameter scale read -21.1, -21.2 and -21.2 dB over .21 to .263 s against -21.0 sealed, while the source-on closure reads 1.8, 1.8 and
// 4.1 dB louder in the settled part. The closure
// right after the ramp is no use either: the seal completes at the end of the ramp with the vowel's tail still in the rear cavity (the
// source-off /k/ read -21.0 dB over .21 to .263 s with the ramp and -27.5 with the contact and the constriction stepped shut; main's
// 30 ms-later window read -25.7), and that decays within the first 25 ms.
// The test therefore proves its own measure first (a leak injected into the tongue's closed diameter must read 3 dB louder) and then bounds
// the sealed closure (-16.5 measured; a .005, .03 or .035 leak reads -15.1, a .02 leak -14.7).
[Fact]
public void AVelarStopClosureSealsAndTheMeasureSeesALeak()
{
static SynthPatch Leaking(SynthPatch p) =>
WithoutBurst(p) with
{
ControlSplines = WithoutBurst(p).ControlSplines
.Select(s => s.Name == "w_1_c_constriction_diameter"
? s with { Points = s.Points.Select(q => q.Value == s.Points.Min(v => v.Value) ? q with { Value = 0.1f, OutValue = 0, InValue = 0 } : q).ToArray() }
: s).ToArray()
};
double Closure(Func<SynthPatch, SynthPatch> edit)
{
var (x, from, to) = VowelConsonantVowel("k", descriptor: "voiceless_velar_plosive", edit: edit);
if (x is null) return double.NaN;
var vowels = Math.Sqrt((Math.Pow(Rms(x, from - 0.08, from - 0.01), 2) + Math.Pow(Rms(x, to + 0.03, to + 0.12), 2)) / 2);
return 20 * Math.Log10(Rms(x, ClosureFrom(from) + 0.025, ReleaseAt(from, to) - 0.005) / vowels);
}
var sealedClosure = Closure(WithoutBurst);
var leaking = Closure(Leaking);
output.WriteLine($"/k/ closure re vowels, source on, settled part: sealed {sealedClosure:F1} dB, with a 0.1 leak {leaking:F1} dB");
if (double.IsNaN(sealedClosure)) return;
Assert.True(leaking >= sealedClosure + 3, $"the measure sees a leak: sealed {sealedClosure:F1} dB, leaking {leaking:F1} dB");
Assert.True(sealedClosure <= -15.5, $"the /k/ closure seals: {sealedClosure:F1} dB re the vowels (measured -16.5; leaks of .005 to .1 read -15.1 to -12.4, the measure is not monotonic in the leak, so the bound sits under the weakest of them)");
}
[Fact]
public void AVelarStopBurstStaysUnderHalfTheFollowingVowel()
{
var (x, from, to) = VowelConsonantVowel("k", descriptor: "voiceless_velar_plosive");
var (nb, _, _) = VowelConsonantVowel("k", descriptor: "voiceless_velar_plosive", edit: WithoutBurst);
if (x is null || nb is null) return;
var burst = x.Zip(nb, (a, b) => a - b).ToArray();
var peak = Peak(burst, ReleaseAt(from, to) - 0.003, to + 0.01);
var vowel = Peak(x, to + 0.06, to + 0.17);
output.WriteLine($"/k/ burst peak {peak:F4}, vowel peak {vowel:F4}, ratio {peak / vowel:F2}");
Assert.True(peak > 0.004, "audible");
Assert.True(peak < vowel / 2, "under half the following vowel's peak, as /t/ and /b/");
}
[Fact]
public void VelarStopBurstExistsOnlyAroundItsOwnRelease_k()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_k", "k", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140);
var withBurst = Render(script, 0.77f);
var withoutBurst = Render(script, 0.77f, WithoutBurst);
if (withBurst is null || withoutBurst is null) return;
var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray();
const double kFrom = 0.275, kTo = 0.37;
var atRelease = Peak(burst, ReleaseAt(kFrom, kTo) - 0.003, kTo + 0.02);
var leading = Peak(burst, 0, kFrom);
var trailing = Peak(burst, kTo + 0.12, 0.77);
output.WriteLine($"/k/ burst peak {atRelease:F4} at the release, {leading:F5} before the plosive, {trailing:F5} after it");
Assert.True(atRelease > 0.004, "the burst is a transient of audible size");
Assert.True(leading < atRelease / 20, "no burst before the plosive's own gesture");
Assert.True(trailing < atRelease / 10, "no burst after the plosive");
}
// Chodroff and Wilson 2014: /k/ burst peak 2868 Hz. The band 2 to 4 kHz is a DESIGN tolerance around it, fixed before the first measurement.
// The peak is judged against the literature and against /t/ measured the same way (a velar burst enters further back, so its peak is lower).
// The centroid is reported, not asserted: over this 1 to 10 kHz grid /k/ reads 4626 Hz against /t/ 3629 Hz, higher though its peak is lower,
// because the /k/ burst has broadband energy above its peak, and no literature centroid for /k/ was retrieved to judge it by.
private (double Peak, double Centroid) BurstSpectrum(string ipa, string descriptor)
{
var (x, from, to) = VowelConsonantVowel(ipa, descriptor: descriptor);
var (nb, _, _) = VowelConsonantVowel(ipa, descriptor: descriptor, edit: WithoutBurst);
if (x is null || nb is null) return (double.NaN, double.NaN);
var start = (int)(ReleaseAt(from, to) * Rate);
const int n = 960;
var seg = Enumerable.Range(0, n).Select(i => (x[start + i] - nb[start + i]) * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (n - 1)))).ToArray();
double Power(double hz)
{
double re = 0, im = 0;
for (var i = 0; i < n; i++) { var a = 2 * Math.PI * hz * i / Rate; re += seg[i] * Math.Cos(a); im -= seg[i] * Math.Sin(a); }
return re * re + im * im;
}
var grid = Enumerable.Range(0, 180).Select(k => 1000.0 + 50 * k).ToArray();
var power = grid.Select(Power).ToArray();
var smooth = power.Select((_, k) => Enumerable.Range(Math.Max(0, k - 4), Math.Min(9, power.Length - Math.Max(0, k - 4))).Average(j => power[j])).ToArray();
return (grid[Array.IndexOf(smooth, smooth.Max())], grid.Zip(power, (f, w) => f * w).Sum() / power.Sum());
}
[Fact]
public void StopKBurstPeakIsInTheLiteratureBandAndLowerThanT()
{
var (peak, centroid) = BurstSpectrum("k", "voiceless_velar_plosive");
if (double.IsNaN(peak)) return;
var (tPeak, tCentroid) = BurstSpectrum("t", "voiceless_alveolar_plosive");
output.WriteLine($"/k/ burst spectral peak {peak:F0} Hz, centroid {centroid:F0} Hz; /t/ peak {tPeak:F0} Hz, centroid {tCentroid:F0} Hz");
Assert.InRange(peak, 2000, 4000);
Assert.True(peak < tPeak, $"/k/ peak {peak:F0} Hz is under /t/ {tPeak:F0} Hz");
}
// /d/ is /t/ with voicing, as /b/ is /p/ with voicing: the same gesture, so the splines that shape the tract are identical and the two differ
// in the voice bar through the closure and in nothing else the burst carries. Chodroff and Wilson 2014: /d/ burst peak 4878 Hz, /t/ 5216.
[Fact]
public void StopDDiffersFromStopTOnlyByVoicing()
{
static SynthPatch Word(string ipa) => PatchScript.Parse(IpaGestureExperiment.BuildWordScript(
[(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f), (new IpaGestureExperimentTarget("w_1_c", ipa, "", 0.095f), 1f), (new IpaGestureExperimentTarget("w_2_a", "a", "", 0.18f), 1f)], 140));
static string[] Shape(SynthPatch p) => p.ControlSplines
.Where(s => s.Name.StartsWith("w_1_c", StringComparison.Ordinal) && !s.Name.StartsWith("w_1_c_source", StringComparison.Ordinal))
.Select(s => s.SurfacePath + "|" + s.Name[5..] + "|" + string.Join(";", s.Points.Select(q => $"{q.TimeSeconds:R}:{q.Value:R}")))
.Order().ToArray();
var t = Shape(Word("t"));
var d = Shape(Word("d"));
output.WriteLine($"/t/ {t.Length} consonant splines, /d/ {d.Length}");
Assert.NotEmpty(d);
Assert.Equal(t, d);
var tDb = VoiceBarDb("t");
var dDb = VoiceBarDb("d");
output.WriteLine($"closure re the following vowel: /t/ {tDb:F1} dB, /d/ {dDb:F1} dB");
if (double.IsNaN(tDb)) return;
Assert.True(dDb >= tDb + 8, $"the voice bar lifts the /d/ closure ({dDb:F1} dB) at least 8 dB over /t/ ({tDb:F1} dB)");
var (dPeak, _) = BurstSpectrum("d", "");
var (tPeak, _) = BurstSpectrum("t", "");
output.WriteLine($"burst spectral peak: /t/ {tPeak:F0} Hz, /d/ {dPeak:F0} Hz");
Assert.True(Math.Abs(dPeak - tPeak) <= 1000, $"/d/ burst peak {dPeak:F0} Hz within 1 kHz of /t/ {tPeak:F0} Hz");
}
[Fact]
public void StopDBurstExistsOnlyAroundItsOwnRelease()
{
IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds);
var script = IpaGestureExperiment.BuildWordScript(
[(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_d", "d", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140);
var withBurst = Render(script, 0.77f);
var withoutBurst = Render(script, 0.77f, WithoutBurst);
if (withBurst is null || withoutBurst is null) return;
var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray();
const double dFrom = 0.275, dTo = 0.37;
var atRelease = Peak(burst, ReleaseAt(dFrom, dTo) - 0.003, dTo + 0.02);
var leading = Peak(burst, 0, dFrom);
var trailing = Peak(burst, dTo + 0.12, 0.77);
output.WriteLine($"/d/ burst peak {atRelease:F4} at the release, {leading:F5} before the plosive, {trailing:F5} after it");
Assert.True(atRelease > 0.004, "the burst is a transient of audible size");
Assert.True(leading < atRelease / 20, "no burst before the plosive's own gesture");
Assert.True(trailing < atRelease / 10, "no burst after the plosive");
}
// /l/ over /ɑ _ ɑ/ at the scaffold's durations. Envelope of the consonant's middle 60 percent at the harmonics of f0 (the largest power within a
// quarter of f0 of k * f0), in dB: the spectrum of a periodic source is a line spectrum, so extrema are read from the harmonic envelope.
private (double[] Hz, double[] Db) HarmonicEnvelope(float[] x, double from, double to, double f0 = 140, double maxHz = 5000)
{
var a = (int)((from + 0.2 * (to - from)) * Rate);
var n = (int)(0.6 * (to - from) * Rate);
var seg = Enumerable.Range(0, n).Select(i => x[a + i] * (0.5 - 0.5 * Math.Cos(2 * Math.PI * i / (n - 1)))).ToArray();
double Power(double hz)
{
double re = 0, im = 0;
for (var i = 0; i < n; i++) { var w = 2 * Math.PI * hz * i / Rate; re += seg[i] * Math.Cos(w); im -= seg[i] * Math.Sin(w); }
return re * re + im * im;
}
var hz = new List<double>();
var db = new List<double>();
for (var k = 1; k * f0 < maxHz; k++)
{
hz.Add(k * f0);
db.Add(10 * Math.Log10(Math.Max(1e-30, Enumerable.Range(-3, 7).Max(j => Power(k * f0 + j * f0 / 12)))));
}
return (hz.ToArray(), db.ToArray());
}
// The lateral's own dip: the envelope with the side stub open less the same render with it shut, at its lowest between 2 and 3 kHz. The
// difference isolates the stub's antiresonance from the valleys between the vowel's formants, which the shut render has as deep.
private static (double DipHz, double Depth) LateralDip(double[] hz, double[] db, double[] shutDb)
{
var i = Enumerable.Range(0, hz.Length).Where(j => hz[j] >= 2000 && hz[j] <= 3000).MinBy(j => db[j] - shutDb[j]);
return (hz[i], shutDb[i] - db[i]);
}
// The lateral's antiresonance: the closed side stub beside the oral path (sublingual cavity). With the stub open the 2 to 3 kHz harmonics fall at
// least 6 dB under the same render with it shut (a DESIGN criterion; no /l/ spectrum was retrieved). The lateral is continuous: the render with
// and without release_flow is the same render.
[Fact]
public void LateralHasAnAntiresonanceAndNoBurst()
{
var (x, from, to) = VowelConsonantVowel("l");
if (x is null) return;
var db = 20 * Math.Log10(Math.Max(1e-9, Deviation(x, 0.03, 0.058)) / Deviation(x, 0.15, 0.25));
output.WriteLine($"/{ipa}/ closure {db:F1} dB re the following vowel");
Assert.InRange(db, lowDb, highDb);
var (hz, db) = HarmonicEnvelope(x, from, to);
var (shut, _, _) = VowelConsonantVowel("l", edit: WithShutSideStub);
var (_, shutDb) = HarmonicEnvelope(shut!, from, to);
var (dipHz, depth) = LateralDip(hz, db, shutDb);
var (nb, _, _) = VowelConsonantVowel("l", edit: WithoutBurst);
output.WriteLine($"/l/ stub open {depth:F1} dB under stub shut at {dipHz:F0} Hz (2-3 kHz); max |with - without release_flow| {x.Zip(nb!, (a, b) => Math.Abs(a - b)).Max():G3}");
Assert.True(depth >= 6, $"the 2-3 kHz dip is {depth:F1} dB under the shut-stub render");
Assert.Equal(x, nb);
}
private static SynthPatch WithShutSideStub(SynthPatch p) =>
p with { ControlSplines = p.ControlSplines.Where(s => s.SurfacePath != "/vocal/branches/1/opening").ToArray() };
// Between the vowels and the nasals in level: -4 to -10 dB re the flanking vowels (a DESIGN band; /n/ reads -9.6, /m/ -11.8 in the same measure).
[Fact]
public void LateralLevelIsBetweenTheVowelsAndTheNasals()
{
var (x, from, to) = VowelConsonantVowel("l");
if (x is null) return;
var db = ConsonantDbReVowels(x, from, to);
output.WriteLine($"/l/ {db:F1} dB re the flanking vowels");
Assert.InRange(db, -10, -4);
}
}
// Reports Skipped, not Passed, when the Faust toolchain is absent: a test that returns early reads as a pass nobody earned.
public sealed class FaustFactAttribute : FactAttribute
{
public FaustFactAttribute()
{
if (AquaSynthFaustToolchain.Find() is null) Skip = "Faust toolchain not found";
}
}
public sealed class FaustTheoryAttribute : TheoryAttribute
{
public FaustTheoryAttribute()
{
if (AquaSynthFaustToolchain.Find() is null) Skip = "Faust toolchain not found";
}
}
public sealed class FaustSkipTests
{
[Fact]
public void StressTestsSkipWithoutFaust()
{
var toolchain = AquaSynthFaustToolchain.Find();
Assert.Equal(toolchain is null, new FaustFactAttribute().Skip is not null);
Assert.Equal(toolchain is null, new FaustTheoryAttribute().Skip is not null);
}
}
file sealed class TupleTolerance(double eps) : IEqualityComparer<(double, double)>
{
public bool Equals((double, double) x, (double, double) y) => Math.Abs(x.Item1 - y.Item1) < eps && Math.Abs(x.Item2 - y.Item2) < eps;
public int GetHashCode((double, double) value) => 0;
}

View file

@ -0,0 +1,106 @@
using AquaSynth.Dsl;
using AquaSynth.Faust;
namespace AquaSynth.Dsl.Tests;
// A consumer writes `trigger` on a voice (envelope restarts on a grid) and `patch repeat` (sfxr pitch/arpeggio restart). These render
// the composition and assert what a listener-side measurement sees: the trigger restarts the envelope, the repeat restarts the pitch
// slide inside each trigger window and never cuts the envelope. Sound is not judged here; only the structure of the render.
[Collection("NativeFaust")]
public sealed class TriggerRepeatCompositionTests
{
private const int Rate = 48000;
private const string Voice = """
voice
wave=sine
freq=200
trigger=0.5
attack=0.001
sustain=0.12
decay=0.1
pitch_ramp=2.0
""";
private static float[]? Render(string script, float seconds)
{
var source = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions("trigger_repeat", SampleRate: Rate)).Source;
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity("trigger_repeat", "trigger_repeat", ""), source, seconds, out var patch, out var error))
{
if (error?.Contains("Faust toolchain not found", StringComparison.OrdinalIgnoreCase) == true ||
error?.Contains("Faust DLL not found", StringComparison.OrdinalIgnoreCase) == true)
{
return null;
}
Assert.Fail($"compile failed: {error}");
}
using (patch) return patch!.Render(seconds);
}
private static double Rms(float[] x, double from, double to)
{
var a = (int)(from * Rate);
var b = Math.Min(x.Length, (int)(to * Rate));
double sum = 0;
for (var i = a; i < b; i++) sum += (double)x[i] * x[i];
return Math.Sqrt(sum / Math.Max(1, b - a));
}
// Zero-crossing rate over a window, in Hz: a pitch measure that needs no search range.
private static double CrossingHz(float[] x, double from, double to)
{
var a = (int)(from * Rate);
var b = Math.Min(x.Length, (int)(to * Rate));
var crossings = 0;
for (var i = a + 1; i < b; i++) if ((x[i - 1] < 0) != (x[i] < 0)) crossings++;
return crossings / 2.0 / ((b - a) / (double)Rate);
}
[Fact]
public void TriggerRestartsTheEnvelopeWhileRepeatInsideTheWindowDoesNot()
{
// repeat 0.05 is shorter than sustain + decay (0.22): the envelope must still run to its release inside each trigger window.
var x = Render("patch repeat=0.05\n" + Voice, 1.1f);
if (x is null) return;
Assert.True(Rms(x, 0.00, 0.10) > 0.1, "first hit sounds");
Assert.True(Rms(x, 0.35, 0.48) < 0.01, "envelope released before the next trigger; repeat did not hold it open");
Assert.True(Rms(x, 0.50, 0.60) > 0.1, "trigger restarts the envelope");
Assert.True(Rms(x, 0.85, 0.98) < 0.01, "second window releases too");
Assert.True(Rms(x, 1.00, 1.10) > 0.1, "third trigger");
}
[Fact]
public void RepeatRestartsThePitchSlideInsideEachTriggerWindowAndTriggerRestartsItToo()
{
var withRepeat = Render("patch repeat=0.05\n" + Voice, 0.6f);
var without = Render(Voice, 0.6f);
if (withRepeat is null || without is null) return;
// Without repeat the slide keeps climbing across the window; with repeat the pitch falls back at each 0.05 s boundary.
var early = CrossingHz(without, 0.00, 0.04);
var late = CrossingHz(without, 0.12, 0.16);
Assert.True(late > early * 1.15, $"control: slide climbs without repeat ({early:F0} -> {late:F0} Hz)");
var repeatedEarly = CrossingHz(withRepeat, 0.00, 0.04);
var repeatedLate = CrossingHz(withRepeat, 0.10, 0.14);
Assert.InRange(repeatedLate / repeatedEarly, 0.9, 1.1);
// The trigger at 0.5 restarts age; the repeat grid inside the new window starts from the trigger, not from absolute time.
var afterTrigger = CrossingHz(withRepeat, 0.50, 0.54);
Assert.InRange(afterTrigger / repeatedEarly, 0.9, 1.1);
}
[Fact]
public void TriggerAndRepeatLowerToDistinctAges()
{
var source = FaustEmitter.EmitScript("patch repeat=0.05\n" + Voice).Source;
Assert.Contains("voice_0_age = wrap01(age / 0.5) * 0.5;", source);
Assert.Contains("voice_0_pitch_age = voice_0_age - floor(voice_0_age / repeat_interval) * repeat_interval;", source);
Assert.Contains("oneshot_adsr_at(voice_0_age,", source);
}
}

View file

@ -68,6 +68,77 @@ public sealed class WeksaPhonesTests
Assert.Empty(plan.Phones);
}
[Fact]
public void WeksaWordPlanAcceptsT()
{
var word = WeksaPhonesReader.Parse(Line($"[{Ph("ɑ", "none")},{Ph("t", "none")},{Ph("ɑ", "none")}]"));
var plan = WeksaWordPlan.From(word, "ata");
Assert.True(plan.Renderable);
Assert.Empty(plan.Unsupported);
// t names a plosive, not the approximant GestureDescriptor falls back to for a phone the table lacks
Assert.True(PatchScript.TryIpaDescriptor("t", out var descriptor));
Assert.Equal("voiceless_alveolar_plosive", descriptor);
var patch = PatchScript.Parse(IpaGestureExperiment.BuildWordScript(plan.Phones.ToArray(), 140));
Assert.Contains(patch.ControlSplines, s => s.SurfacePath == "/vocal/contacts/0/release_flow" && s.Name.StartsWith("ata_1_t", StringComparison.Ordinal));
}
[Fact]
public void WeksaWordPlanAcceptsD()
{
var word = WeksaPhonesReader.Parse(Line($"[{Ph("ɑ", "none")},{Ph("d", "none")},{Ph("ɑ", "none")}]"));
var plan = WeksaWordPlan.From(word, "ada");
Assert.True(plan.Renderable, string.Join(",", plan.Unsupported.Select(p => p.Ipa)));
Assert.Empty(plan.Unsupported);
// d names a plosive, not the approximant GestureDescriptor falls back to for a phone the table lacks
Assert.True(PatchScript.TryIpaDescriptor("d", out var descriptor));
Assert.Equal("voiced_alveolar_plosive", descriptor);
var patch = PatchScript.Parse(IpaGestureExperiment.BuildWordScript(plan.Phones.ToArray(), 140));
Assert.Contains(patch.ControlSplines, s => s.SurfacePath == "/vocal/contacts/0/release_flow" && s.Name.StartsWith("ada_1_d", StringComparison.Ordinal));
}
// The lateral gate passed (a closed side stub on the oral path gives a dip: LateralHasAnAntiresonanceAndNoBurst), so /l/ is in the table, as a
// lateral and never as the approximant GestureDescriptor falls back to.
[Fact]
public void LateralGateOutcomeIsRecorded()
{
var word = WeksaPhonesReader.Parse(Line($"[{Ph("ɑ", "none")},{Ph("l", "none")},{Ph("ɑ", "none")}]"));
var plan = WeksaWordPlan.From(word, "ala");
Assert.True(plan.Renderable, string.Join(",", plan.Unsupported.Select(p => p.Ipa)));
Assert.Empty(plan.Unsupported);
Assert.True(PatchScript.TryIpaDescriptor("l", out var descriptor));
Assert.Equal("voiced_alveolar_lateral_approximant", descriptor);
Assert.NotEqual("voiced_alveolar_approximant", descriptor);
var script = IpaGestureExperiment.BuildWordScript(plan.Phones.ToArray(), 140);
var patch = PatchScript.Parse(script);
Assert.Contains(patch.BranchPorts, b => b.Name == PatchScript.SideStubBranch);
Assert.Contains(patch.ControlSplines, s => s.SurfacePath == "/vocal/branches/1/opening" && s.Name.StartsWith("ala_1_l", StringComparison.Ordinal));
// continuous, no burst: the lateral has no release_flow spline at all
Assert.DoesNotContain(patch.ControlSplines, s => s.SurfacePath == "/vocal/contacts/0/release_flow" && s.Name.StartsWith("ala_1_l", StringComparison.Ordinal));
}
// A lateral gesture on a scaffold without the side stub is refused, not rendered as an approximant.
[Fact]
public void ALateralWithoutTheSideStubIsRefused()
{
var script = IpaGestureExperiment.BuildWordScript([(new IpaGestureExperimentTarget("w_0_a", "a", "", 0.18f), 1f)], 140)
+ "\nphoneme_gesture name=w_hand ipa=l descriptor=voiced_alveolar_lateral_approximant start=.2 dur=.1 intensity=1";
var error = Assert.Throws<PatchScriptException>(() => PatchScript.Parse(script));
Assert.Contains(PatchScript.SideStubBranch, error.Message);
}
[Fact]
public void WeksaWordPlanAcceptsK()
{
var word = WeksaPhonesReader.Parse(Line($"[{Ph("ɑ", "none")},{Ph("k", "none")},{Ph("ɑ", "none")}]"));
var plan = WeksaWordPlan.From(word, "aka");
Assert.True(plan.Renderable, string.Join(",", plan.Unsupported.Select(p => p.Ipa)));
Assert.Empty(plan.Unsupported);
Assert.True(PatchScript.TryIpaDescriptor("k", out var descriptor));
Assert.Equal("voiceless_velar_plosive", descriptor);
var patch = PatchScript.Parse(IpaGestureExperiment.BuildWordScript(plan.Phones.ToArray(), 140));
Assert.Contains(patch.ControlSplines, s => s.SurfacePath == "/vocal/contacts/0/release_flow" && s.Name.StartsWith("aka_1_k", StringComparison.Ordinal));
}
[Fact]
public void NearCloseVowelsRenderAsVowelsWithTheirOwnStoryShape()
{
@ -77,10 +148,10 @@ public sealed class WeksaPhonesTests
Assert.Equal([WeksaWordPlan.ConsonantSeconds, WeksaWordPlan.VowelSeconds * WeksaWordPlan.CueFor(WeksaStress.Primary).Duration, WeksaWordPlan.ConsonantSeconds, WeksaWordPlan.ConsonantSeconds, WeksaWordPlan.VowelSeconds],
plan.Phones.Select(p => p.Target.DurationSeconds));
var patch = PatchScript.Parse(IpaGestureExperiment.BuildWordScript(plan.Phones.ToArray(), 140));
var ih = patch.ControlSplines.Where(s => s.Name.StartsWith("x_1_ɪ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[0].Value);
var ih = patch.ControlSplines.Where(s => s.Name.StartsWith("x_1_ɪ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[^1].Value);
Assert.Equal(1f, ih["/vocal/areas/0/area/vowel_ih"]);
Assert.Equal(0f, ih["/vocal/areas/0/area/vowel_i"]);
var oo = patch.ControlSplines.Where(s => s.Name.StartsWith("x_4_ʊ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[0].Value);
var oo = patch.ControlSplines.Where(s => s.Name.StartsWith("x_4_ʊ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[^1].Value);
Assert.Equal(1f, oo["/vocal/areas/0/area/vowel_oo_short"]);
Assert.Equal(0f, oo["/vocal/areas/0/area/vowel_u"]);
}
@ -119,7 +190,7 @@ public sealed class WeksaPhonesTests
var none = patch(WeksaStress.None);
var primary = patch(WeksaStress.Primary);
float First(SynthPatch p, string prefix, string surface) =>
p.ControlSplines.Single(sp => sp.Name.StartsWith(prefix, StringComparison.Ordinal) && sp.SurfacePath == surface).Points[0].Value;
p.ControlSplines.Single(sp => sp.Name.StartsWith(prefix, StringComparison.Ordinal) && sp.SurfacePath == surface).Points[^1].Value;
// pitch_ratio surface range 0.5..2: normalized (1.06 - .5) / 1.5; unstressed holds 1 -> (1 - .5) / 1.5.
Assert.Equal((1.06f - .5f) / 1.5f, First(primary, "w_1_i_source_pitch", "/vocal/sources/0/pitch_ratio"), 4);
@ -135,7 +206,7 @@ public sealed class WeksaPhonesTests
{
foreach (var ipa in new[] { "n", "i", "b", "u", "a", "ə", "ɪ", "ʊ", "e", "ɛ", "æ", "ʌ", "ɑ", "ɔ", "o" })
Assert.True(PatchScript.TryIpaDescriptor(ipa, out var descriptor) && descriptor.EndsWith("_vowel", StringComparison.Ordinal) == "iuaəɪʊeɛæʌɑɔo".Contains(ipa));
foreach (var ipa in new[] { "ŋ", "θ", "ɹ", "l" })
foreach (var ipa in new[] { "ŋ", "θ", "ɹ" })
Assert.False(PatchScript.TryIpaDescriptor(ipa, out _));
}
}

View file

@ -16,7 +16,8 @@ if (args.Length == 2 && args[0] == "--dings")
var instruments = new List<object>();
foreach (var ins in DingCatalog.Instruments.Values.OrderBy(i => i.Id, StringComparer.Ordinal))
{
var export = FaustEmitter.EmitScript(ins.Script, new FaustExportOptions("dings_" + ins.Id.Replace('-', '_')));
// 48000 (the FaustExportOptions default) is the Ding catalog contract: DingCatalogTests pins the sources at that rate.
var export = FaustEmitter.EmitScript(ins.Script, new FaustExportOptions(DingCatalog.Identity(ins).FaustName));
File.WriteAllText(Path.Combine(dingDir, ins.Id + ".dsp"), export.Source);
instruments.Add(new { id = ins.Id, rootFrequency = ins.RootFrequency, dsp = ins.Id + ".dsp", controlPath = "/ding/frequency", warnings = export.Warnings });
Console.WriteLine($"{ins.Id}: {export.Source.Length} chars, {export.Warnings.Count} warnings");
@ -42,6 +43,7 @@ foreach (var spec in args.Skip(2))
var warnings = new List<string>();
if (path.EndsWith(".aqua", StringComparison.Ordinal))
{
// 48000 (the FaustExportOptions default): AquaLower lowers for the 48 kHz hosts.
var export = FaustEmitter.EmitScript(text, new FaustExportOptions(name));
source = export.Source;
warnings.AddRange(export.Warnings);

View file

@ -17,7 +17,8 @@ public sealed class AquaDaemonClient : IAsyncDisposable
{
EnsureStarted();
var id = $"ding-{Guid.NewGuid():N}";
var envelope = new { command = "instrument.sample", payload = new { commandId = id, patchId = $"dings.{instrument.Id}", faustName = $"dings_{instrument.Id.Replace('-', '_')}", script = instrument.Script, durationSeconds = 1.5f, gain, controls = new Dictionary<string, float> { ["/ding/frequency"] = frequency }, revision = 1 } };
var identity = DingCatalog.Identity(instrument);
var envelope = new { command = "instrument.sample", payload = new { commandId = id, patchId = identity.PatchId, faustName = identity.FaustName, script = instrument.Script, durationSeconds = 1.5f, gain, controls = new Dictionary<string, float> { ["/ding/frequency"] = frequency }, revision = identity.Revision } };
await process!.StandardInput.WriteLineAsync(JsonSerializer.Serialize(envelope, json));
await process.StandardInput.FlushAsync(cancellationToken);
var line = await process.StandardOutput.ReadLineAsync(cancellationToken) ?? throw new InvalidOperationException("Aqua daemon closed before returning a render receipt.");

View file

@ -63,9 +63,9 @@ public sealed class DingsPlaybackHost : IAsyncDisposable
private async Task<DingsResponse> PlayAsync(DingsCommand command, CancellationToken cancellationToken)
{
if (!DingCatalog.Events.TryGetValue(command.EventId, out var dingEvent)) return Response(false, "rejected", $"Unknown event '{command.EventId}'.");
if (!DingCatalog.Instruments.TryGetValue(command.InstrumentId, out var instrument)) return Response(false, "rejected", $"Unknown instrument '{command.InstrumentId}'.");
if (!float.IsFinite(command.Value) || command.Value is < 0 or > 1) return Response(false, "rejected", "Gain must be between 0 and 1.");
if (DingCatalog.PlayRejection(command.EventId, command.InstrumentId, command.Value) is { } rejection) return Response(false, "rejected", rejection);
var dingEvent = DingCatalog.Events[command.EventId];
var instrument = DingCatalog.Instruments[command.InstrumentId];
var playbackId = $"ding-{Guid.NewGuid():N}";
foreach (var note in dingEvent.Notes)
{

View file

@ -6,6 +6,9 @@ public sealed class DingService(IDingsHostClient host)
{
public async Task<object> PlayAsync(string eventId, string instrumentId, float gain, CancellationToken cancellationToken)
{
// DEPRECATED fail-fast path: the Host enforces the real gate (DingCatalog.PlayRejection, called by DingsPlaybackHost.PlayAsync).
// Kept for one window because its exception types and the NaN pass-through to the Host's rejection are observable; see
// docs/dings-patch-identity-authority-map.md, Migration plan step 4. Remove only in a separate PR.
if (!DingCatalog.Events.TryGetValue(eventId, out var dingEvent)) throw new ArgumentException($"Unknown event '{eventId}'.");
if (!DingCatalog.Instruments.TryGetValue(instrumentId, out var instrument)) throw new ArgumentException($"Unknown instrument '{instrumentId}'.");
if (gain is < 0 or > 1) throw new ArgumentOutOfRangeException(nameof(gain), "Gain must be between 0 and 1.");

View file

@ -264,7 +264,7 @@ static async Task SongScoreAsync(Dictionary<string, string> options)
var timelineNetwork = patch.VocalNetworks.FirstOrDefault();
var timeline = timelineNetwork is null
? Array.Empty<ProbeTimelineSample>()
: ProbeTimelineReport.Build(patch, timelineNetwork.Name, 12);
: ProbeTimelineReport.Build(patch, timelineNetwork.Name, 12, challenge.SampleRate);
await File.WriteAllTextAsync(timelinePath, ProbeTimelineReport.ToCsv(timeline), Encoding.UTF8);
timelineFacts = PrimitiveTimelineFactExtractor.Extract(timeline).ToArray();
var source = FaustEmitter.EmitScript(script, new FaustExportOptions(safeCandidateId, SampleRate: challenge.SampleRate)).Source;

View file

@ -8,10 +8,17 @@ using AquaSynth.Faust;
// Offline probe: one word, segmented by Weksa (the phones line of `weksa lower --phones`), as a run of IPA gestures on the
// IpaGestureExperiment scaffold, rendered through the native libfaust path to a mono 16-bit WAV plus script.aqua, source.dsp
// and manifest.json. It measures peak, rms and NaN; it cannot say how the word sounds.
// usage: WordRender <outDir> <label> <freq-hz> <phones.json>
// exit: 0 rendered, 1 compile or non-finite output, 2 usage, 3 phones file refused, 4 phones the tract cannot make (listed, nothing rendered)
// usage: WordRender <outDir> <label> <freq-hz> <phones.json> [--no-burst] [--source "key=value ..."]
// --source sets or replaces fields on the scaffold's `source_port` line (pulse=rosenberg, noise_hp=2000, tilt=.3): one source parameter changed, the phrase untouched.
// noise=X also flattens the gesture noise splines to X: the gestures hold /vocal/sources/0/noise at 0.05 through a vowel and the spline wins over the slider's base value, so the field alone changes nothing. Meant for voiced-only phrases (a fricative's rise is flattened too).
// --no-burst drops the plosive release_flow splines (the same edit the burst test makes), so a render pair isolates the burst.
// exit: 0 rendered, 1 compile or non-finite output, 2 usage or a refused --source (unknown or repeated key, no value, non-number, negative, noise_hp outside 0-8000, a script the parser rejects), 3 phones file refused, 4 phones the tract cannot make (listed, nothing rendered)
const int Rate = 48000, Frames = 512;
if (args.Length != 4) { Console.Error.WriteLine("usage: WordRender <outDir> <label> <freq-hz> <phones.json>"); return 2; }
var noBurst = args.Skip(4).Contains("--no-burst");
var sourceAt = Array.IndexOf(args, "--source");
var sourceFields = sourceAt >= 0 && sourceAt + 1 < args.Length ? args[sourceAt + 1] : "";
var extra = args.Length - 4 - (noBurst ? 1 : 0) - (sourceAt >= 0 ? 2 : 0);
if (args.Length < 4 || extra != 0 || (sourceAt >= 0 && (sourceAt < 4 || sourceAt + 1 >= args.Length))) { Console.Error.WriteLine("usage: WordRender <outDir> <label> <freq-hz> <phones.json> [--no-burst] [--source \"key=value ...\"]"); return 2; }
var outDir = Path.GetFullPath(args[0]);
var label = args[1];
var freq = float.Parse(args[2], System.Globalization.CultureInfo.InvariantCulture);
@ -34,6 +41,33 @@ var phones = plan.Phones.ToArray();
Directory.CreateDirectory(outDir);
var script = IpaGestureExperiment.BuildWordScript(phones, freq);
float? noiseLevel = null;
// The fields a source_port accepts here, exactly as PatchScript spells them (case-sensitive): PatchScript ignores a key it does not know, so a typo would render the scaffold and record a change.
string[] sourceKeys = ["pressure", "tension", "opening", "noise", "impedance", "flow_scale", "tilt", "pitch_ratio", "pulse", "noise_hp"];
var seenKeys = new HashSet<string>(StringComparer.Ordinal);
foreach (var field in sourceFields.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
string? refusal = null;
var eq = field.IndexOf('=');
var key = eq > 0 ? field[..eq] : field;
var value = eq > 0 ? field[(eq + 1)..] : "";
float number = 0;
if (eq <= 0 || value.Length == 0) refusal = "expected key=value";
else if (!sourceKeys.Contains(key, StringComparer.Ordinal)) refusal = $"unknown key `{key}` (keys: {string.Join(", ", sourceKeys)})";
else if (!seenKeys.Add(key)) refusal = $"key `{key}` given twice";
else if (key != "pulse" && !(float.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out number) && float.IsFinite(number))) refusal = $"`{key}` needs a number, got `{value}`";
else if (key == "noise_hp" && number is < 0 or > 8000) refusal = "`noise_hp` is a corner in Hz, 0 to 8000";
else if (key != "pulse" && number < 0) refusal = $"`{key}` is negative";
if (refusal is not null) { Console.Error.WriteLine($"REFUSED --source field `{field}`: {refusal}"); return 2; }
if (key == "noise") noiseLevel = number;
var lines = script.Split('\n');
var at = Array.FindIndex(lines, l => l.TrimStart().StartsWith("source_port name=folds ", StringComparison.Ordinal));
if (at < 0) { Console.Error.WriteLine($"REFUSED --source field `{field}`: the scaffold has no source_port name=folds line"); return 2; }
var tokens = lines[at].TrimEnd().Split(' ').Where(t => !t.StartsWith(key + "=", StringComparison.Ordinal)).Append(field);
lines[at] = lines[at][..(lines[at].Length - lines[at].TrimStart().Length)] + string.Join(' ', tokens.Where(t => t.Length > 0));
script = string.Join('\n', lines);
}
File.WriteAllText(Path.Combine(outDir, "script.aqua"), script + "\n");
var seconds = phones.Sum(p => p.Item1.DurationSeconds) + 0.12f;
var home = AquaSynthFaustToolchain.Find();
@ -41,7 +75,13 @@ Console.WriteLine($"faust home: {home ?? "(not found)"}");
using var compiler = new AquaSynthPatchCompiler(new AquaSynthNativeOptions(SampleRate: Rate));
// The exporter emits one merged spline per surface (the ControlSplineTimeline curve), so the DSP carries the word's motion
// itself and no slider is driven from outside.
var source = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions(label)).Source;
SynthPatch parsed;
try { parsed = PatchScript.Parse(script); }
catch (PatchScriptException ex) { Console.Error.WriteLine($"REFUSED --source \"{sourceFields}\": {ex.Message}"); return 2; }
if (noiseLevel is { } nz)
parsed = parsed with { ControlSplines = parsed.ControlSplines.Select(sp => sp.SurfacePath != "/vocal/sources/0/noise" ? sp : sp with { Points = sp.Points.Select(pt => pt with { Value = nz, OutValue = nz, InValue = nz }).ToArray() }).ToArray() };
if (noBurst) parsed = parsed with { ControlSplines = parsed.ControlSplines.Where(s => !s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal)).ToArray() };
var source = FaustEmitter.Emit(parsed, new FaustExportOptions(label, SampleRate: Rate)).Source;
File.WriteAllText(Path.Combine(outDir, "source.dsp"), source);
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity(label, label, ""), source, seconds, out var patch0, out var cerr))
{
@ -83,7 +123,7 @@ using (var w = new BinaryWriter(File.Create(wav)))
var rms = Math.Sqrt(sum / pcm.Length);
File.WriteAllText(Path.Combine(outDir, "manifest.json"), JsonSerializer.Serialize(new
{
label, freq, weksa = new { word.Language, word.Source, Phones = word.Phones.Select(p => new { p.Ipa, Stress = p.Stress.ToString() }) }, seconds, sampleRate = Rate, frames = pcm.Length, peak, rms, nonFinite = nan,
label, freq, noBurst, sourceFields, weksa = new { word.Language, word.Source, Phones = word.Phones.Select(p => new { p.Ipa, Stress = p.Stress.ToString() }) }, seconds, sampleRate = Rate, frames = pcm.Length, peak, rms, nonFinite = nan,
wavSha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(wav))).ToLowerInvariant(),
scriptSha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(outDir, "script.aqua")))).ToLowerInvariant(),
os = RuntimeInformation.OSDescription, faustHome = home

View file

@ -0,0 +1,18 @@
#!/bin/bash
# Negative check for WordRender --source: every malformed field must exit 2 with a REFUSED line naming it, never crash (134) or render.
# source-refusals.sh <WordRender.dll> <phones.json> e.g. tools/aqua-listen/kits/voice-source/phones/ami.json
set -u
DLL=$1; PHONES=$2; OUT=$(mktemp -d); bad=0
check() { # <expected substring> <source string>
msg=$(dotnet "$DLL" "$OUT/o" refuse 140 "$PHONES" --source "$2" 2>&1 >/dev/null); code=$?
if [ $code -eq 2 ] && [[ "$msg" == *REFUSED*"$1"* ]]; then echo "ok [$2] -> 2 $msg"; else echo "FAIL [$2] -> exit $code: $msg"; bad=1; fi
}
check pulze "pulze=rosenberg"
check Noise "Noise=.33"
check noise "noise"
check noise=abc "noise=abc"
check noise_hp=-5 "noise_hp=-5"
check noise_hp=9000 "noise_hp=9000"
check noise "noise=.1 noise=.2"
check pulse=triangle "pulse=triangle"
rm -rf "$OUT"; exit $bad

View file

@ -9,6 +9,8 @@ The WAVs and the gallery exist so a person can press play.
To look at a finished audio file (wav/ogg/flac: spectrogram, onsets at 1 ms, level envelope, click/clip/double-hit/overlap/abrupt-end detectors, two-file compare) rather than a rendered patch, use `../aqua-ear`.
To check that sound and picture of a capture line up (video or WAV plus a frame-diff track), use `node feel.mjs sync`: see `SYNC.md`.
## Run
```
@ -59,8 +61,7 @@ failing rule, and a rule with an `id` that matches no item (a renamed or dropped
are deleted when the thing they excuse is fixed and a rename cannot silently disarm a cap. A missing metric fails its rule. The numbers were chosen after looking
at the shipped renders. They are tripwires, not taste.
Current waivers: `sfxr-classic-classic-sfxr-abstract-golf` (+0.9 dBTP, -5.3 LUFS, held noise) and `sfxr-explosion` (3 s of
steady noise without decay). Nobody has listened to either to see if the number is the sound.
Current waivers: none. (The golf and explosion waivers were removed when `patch repeat` stopped cutting their envelopes; nobody has listened to either to see if the numbers are the sound.)
## Effects shelf

View file

@ -85,30 +85,30 @@ Sustained patches such as the thruster keep sounding until stopped; the render c
| `patch/advanced-glass-creature` | start | none | decays | 3 s | unheard |
| `patch/advanced-human-larynx-graph` | start | curves/breath_phrase/depth 0..1 (default 0.9); curves/fold_onset/depth 0..1 (default 0.8); curves/lip_vowel/depth 0..1 (default 0.65); human/constriction/diameter 0.02..3 (default 0.95); human/constriction/index 0..6 (default 4.8); human/fold/opening 0..1 (default 0.16); human/fold/tension 0..1 (default 0.58); human/lip/opening 0..2 (default 1.2); human/subglottal 0..1.5 (default 0.78); human/tongue/diameter 0.05..3 (default 1.25); human/tongue/index 0..6 (default 3.3) | decays | 3 s | unheard |
| `patch/advanced-machine-breath` | start | none | decays | 3 s | unheard |
| `patch/advanced-ritual-sequence` | start | none | sustained | 3 s | unheard |
| `patch/advanced-ritual-sequence` | start | none | decays | 3 s | unheard |
| `patch/advanced-subtractive-drums` | start | none | decays | 3 s | unheard |
| `patch/advanced-syrinx-voice` | start | curves/beak_phrase/depth 0..1 (default 0.72); curves/left_phrase_opening/depth 0..1 (default 0.85); curves/left_phrase_pressure/depth 0..1 (default 0.92); curves/right_phrase_opening/depth 0..1 (default 0.85); curves/right_phrase_pressure/depth 0..1 (default 0.92); voice/beak/opening 0..1.5 (default 0.88); voice/left/opening 0..1 (default 0.23); voice/left/pressure 0..1.5 (default 0.78); voice/left/tension 0..1 (default 0.43); voice/right/opening 0..1 (default 0.19); voice/right/pressure 0..1.5 (default 0.66); voice/right/tension 0..1 (default 0.5) | decays | 3 s | unheard |
| `patch/bfxr-coin-spark` | start | none | decays | 3 s | unheard |
| `patch/bfxr-portal-chirp` | start | none | decays | 3 s | unheard |
| `patch/bfxr-shield-pop` | start | none | decays | 3 s | unheard |
| `patch/bfxr-ui-bloom` | start | none | sustained | 3 s | unheard |
| `patch/bfxr-ui-bloom` | start | none | decays | 3 s | unheard |
| `patch/dx7-algorithm-32-additive-organ` | start | macro/drawbar 0..1 (default 0.78); macro/shimmer 0..0.3 (default 0.08) | decays | 3 s | unheard |
| `patch/dx7-algorithm-8-bright-pair` | start | macro/brightness 0..5 (default 2.6); macro/strike 0.02..0.6 (default 0.18) | decays | 3 s | unheard |
| `patch/dx7-public-domain-mc-mm-5-3` | start | none | decays | 3 s | unheard |
| `patch/dx7-public-domain-prc-synth1-calibrated` | start | none | decays | 3 s | unheard |
| `patch/examples-language-tour` | start | none | sustained | 3 s | unheard |
| `patch/examples-language-tour` | start | none | decays | 3 s | unheard |
| `patch/fm-bell-bell` | start | none | decays | 3 s | unheard |
| `patch/fm-bell-chime` | start | none | decays | 3 s | unheard |
| `patch/fm-bell-coin` | start | none | decays | 3 s | unheard |
| `patch/fm-bell-gong` | start | none | decays | 3 s | unheard |
| `patch/sfxr-blip` | start | none | decays | 3 s | unheard |
| `patch/sfxr-classic-classic-sfxr-abstract-golf` | start | none | sustained | 3 s | unheard |
| `patch/sfxr-explosion` | start | none | sustained | 3 s | unheard |
| `patch/sfxr-classic-classic-sfxr-abstract-golf` | start | none | decays | 3 s | unheard |
| `patch/sfxr-explosion` | start | none | decays | 3 s | unheard |
| `patch/sfxr-hit` | start | none | decays | 3 s | unheard |
| `patch/sfxr-jump` | start | none | decays | 3 s | unheard |
| `patch/sfxr-laser` | start | none | decays | 3 s | unheard |
| `patch/sfxr-pickup` | start | none | decays | 3 s | unheard |
| `patch/sfxr-powerup` | start | none | sustained | 3 s | unheard |
| `patch/sfxr-powerup` | start | none | decays | 3 s | unheard |
| `patch/wobble-bass-growl` | start | none | decays | 3 s | unheard |
| `patch/wobble-bass-neuro` | start | none | decays | 3 s | unheard |
| `patch/wobble-bass-talker` | start | none | decays | 3 s | unheard |

119
tools/aqua-feel/SYNC.md Normal file
View file

@ -0,0 +1,119 @@
# aqua-feel sync
Checks audio-visual synchrony of a capture: finds audio onsets and visual onsets, pairs them, reports the lag per event in ms and
compares it with published detectability windows. Standalone: Node 18+, no npm dependencies (`feel.mjs` imports `sync.mjs`, which
imports one FFT from `metrics.js`). ffmpeg (no ffprobe) is needed only to read a video file directly.
**The metric is not the verdict.** It compares two onset lists extracted from signals. A human ear and eye still decide whether a
capture feels in sync. Nothing here heard or saw anything.
## Run
```
# WAV + a per-frame track (no ffmpeg needed)
node feel.mjs sync --wav capture.wav --track frames.csv [--events hits.txt] [--fps 60] [--kind luma|flux]
# a video with one audio and one video stream (needs ffmpeg on PATH, or FFMPEG=/path/to/ffmpeg)
node feel.mjs sync --video capture.mp4 [--events hits.txt] [--kind luma|flux]
# options: --profile default|bt1359|ebu-r37|atsc-is191 --lead-ms N --lag-ms N --pair-window-ms N (default 200)
# --min-gap-ms N --allow-unpaired --json out.json --no-gate --shape step|ramp (ramp: slow swells, see below)
node sync.test.mjs # 37 checks on synthetic fixtures; 46 with FFMPEG=/path/to/ffmpeg (also builds clips with known stream offsets and runs a real browser capture)
node sync-fixture.mjs DIR 80 60 # write a fixture (audio 80 ms late, 60 fps) to try the CLI on
```
Exit 0 when no pair is detectably outside the window; 1 when any pair is outside, an event or onset is unpaired or has no partner, a pairing is ambiguous,
or nothing paired; 2 on a tool error (bad option, unreadable or malformed input). `--no-gate` always exits 0. `--allow-unpaired` stops stray
onsets (background hits that have no counterpart) from failing the check.
**Inputs.** `frames.csv`: one row per video frame, `t,value` in seconds (a header line is skipped), or one value per line with `--fps`.
`value` is mean frame luminance (`--kind luma`, default: a flash or cut is a positive step) or a frame-difference magnitude
(`--kind flux`, motion flux: a start of movement is a rise). `hits.txt`: seconds, optionally `,label` per line (`#` comments), or JSON
`[0.5, {"t":1.3,"label":"hit"}]`. With a video, luminance and flux are computed on a 64x36 gray downscale; stream `start_time`
offsets are applied so both clocks are the container's.
**Lag convention.** `lag = audio onset - visual onset`. Positive means the sound comes after the picture (audio late); negative means
the sound comes first (audio early). With `--events`, each logged event is matched to the nearest audio and nearest visual onset
within the pairing window (200 ms), and `a-ev` / `v-ev` give each side's offset from the logged time, so you can tell which side is late. Without an
event log, audio onsets pair with visual onsets by proximity (within the pairing window, one-to-one, nearest first). **A pair is `ambiguous-pairing` and fails the check when
another onset of the same kind lies closer than twice the pairing window** (400 ms by default). Nearest-onset pairing is right only if the true lag is under half
the spacing of the onsets, and the tool cannot know the lag, so it takes the pairing window as the largest lag you consider plausible. The cost is real: material
faster than 2.5 hits per second cannot pass at the default, however good the sync. Narrow `--pair-window-ms` if the lag is known to be small (`50` clears 100 ms
spacing), or space the events out. A lag beyond the window reads as `no-audio-onset`, or, when the previous hit's sound lands inside the window, as that hit's (wrong sign, e.g.
+250 ms at 0.45 s spacing reads -200 ms); it fails either way, but do not trust the sign of a lag larger than half the hit spacing.
Parsers refuse input they cannot read (timecodes, a third column, empty cells, non-increasing times) rather than guess.
## How onsets are found
- **Audio:** log-magnitude spectral flux (1024-sample window, 128-sample hop, 60 Hz and up), half-wave rectified; peaks over
median + 8 robust sigmas, at least 50 ms apart; each is then refined on the samples to the first one that rises above both 10% of the local peak and
2.5 times the steady bed (the median block peak of the 85 ms before, after removing the median as DC). A bed louder than a tenth of the hit still defeats it.
- **Visual:** the positive step (luma) or the value (flux) of the track; peaks over median + 8 robust sigmas and at least 10% of the
track's range, at least 100 ms apart (`--min-gap-ms` changes it, for both trains; flashes closer than that merge into one onset and the events beyond the first go unpaired); the onset is the first frame of the rise reaching 50% of the peak.
## Verdict
Per pair, against a window of how far audio may lead (`lead`) or trail (`lag`) the picture before the offset is detectable:
| profile | lead ms | lag ms | source |
|---|---|---|---|
| `default` | 25 | 100 | the conservative range this tool was asked for; it is not one standard: it sits between the ATSC and ITU figures. Treat as a tripwire |
| `bt1359` | 45 | 125 | ITU-R BT.1359-1 (1998), "Relative timing of sound and vision for broadcasting": detectability threshold +45 / -125 ms (acceptability +90 / -185) |
| `ebu-r37` | 40 | 60 | EBU R37 (2007) limit for emission, sound before / after picture. Figure taken from a secondary summary, the EBU text was not read |
| `atsc-is191` | 15 | 45 | ATSC IS-191 (2003) limit at the DTV encoder input. Secondary summary; the same document gives +30 / -90 ms end to end. The document itself was not read |
Verdict words: `inside-window` (the whole truth interval, below, lies inside the window); `audio-late-detectable` / `audio-early-detectable` (the whole interval lies outside);
`borderline` (the interval straddles a window edge: not shown to be outside, so it does not fail the gate, and the report says "NOT DETECTABLY OUTSIDE" rather than "WITHIN");
`ambiguous-pairing`; `no-audio-onset` / `no-visual-onset` / `no-onsets` (the logged event had no onset within the pairing window, so a sound further than 200 ms from its event
reads as absent). `pass` means no pair is detectably outside, ambiguous or missing, and nothing is unpaired (unless `--allow-unpaired`).
Sources: [ITU-R BT.1359-1](https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.1359-1-199811-I!!PDF-E.pdf) (the PDF text was
fragmentary in the search; figures confirmed against secondary summaries), and the TV Technology articles
[AV synchronization, how bad is bad](https://www.tvtechnology.com/opinions/av-synchronization-how-bad-is-bad) and
[ATSC recommends AV sync rules](https://tvtechnology.com/opinions/atsc-recommends-av-sync-rules). Windows depend on content (speech
lip-sync is more sensitive than a game impact) and on the viewer; they are population thresholds, not a property of your capture.
## Ramp-shaped visuals (`--shape ramp`)
Some visuals answer a sound with a slow swell (a scene brightening over a few hundred ms), not a step. The default detector looks for a peak in the frame-to-frame step, finds none, and says no visual onset
(`step` found 0 of 5 hits on `fixtures/perlines-trails-ramp.webm`; `ramp` paired 3). `--shape ramp` takes the track's rise over 300 ms as the novelty and picks its peaks (at least 15% of the track's range, 6 noise sigmas,
at least 500 ms apart). For each it finds the quiet level before the rise (the last sample within 2 noise sigmas of the minimum of the 0.6 s before) and the 20% and 80% crossings of the rise to its top.
**What it claims.** That a swell-shaped response was found near each sound, and where: a point estimate (`visual s`, `lag ms`: the foot of the line through the 20% and 80% crossings of the rise) and a printed interval (from the quiet minimum, backed off by
the valley-to-crossing time, to the first raw frame 20% of the rise above the quiet level). **It makes no claim about sync: every ramp pair is `borderline`, and a ramp can never fail the gate.** Two separate-context Soul passes falsified every stronger claim
the first versions made. The start of a swell cannot be bounded from below by looking at it (a slow start sits under the noise), so "inside the window" and "audio early" were wrong on slow-start shapes; the upper bound is moved earlier by one outlier frame
(a compression spike, a heavy-tailed noise frame), so "audio late" was wrong at true lags of 4 to 97 ms on realistic noise; and a bed that swells near a hit takes over the pairing. The numbers are for a person to read next to the capture, not a verdict.
The synthetic sweep and the outlier-frame and swelling-bed cases are tests that no ramp gets a verdict other than `borderline`.
**What it cannot claim.** That the sound is in sync with a swell (only that it is not detectably late). When the viewer sees the swell begin (later than the physical start; depends on contrast, size and attention). That the swell was caused by this sound: pairing
is by nearness to the foot, and a bed that swells on its own, a scene change or a second sound within 500 ms gives a false pair. Ramps closer than 500 ms merge (so the ambiguity guard, which fires on neighbours closer than twice the pairing window, cannot fire at the default 200 ms
window; the merged hits show up as unpaired audio). Ramps under 15% of the track's range, or on a steady drift that rises over the whole clip, are not found. `--kind flux` with `--shape ramp` means a swell of motion energy; it has not been tried on anything
but one fixture. The constants (300 ms rise window, 15% floor, 6 sigmas, 500 ms gap) were set on Perlines v2's Vector trails and the synthetic shapes only.
## Uncertainty
A visual onset can only land on a frame, and a frame is stamped when its picture started to be displayed. A change at time tau first shows in the first frame
stamped at or after tau, so the measured visual time is late by 0 to one frame period, and the measured lag (audio minus visual) is **biased low** by that much. The audio
onset is good to about half a hop (1.4 ms). Each pair therefore reports `lagLowMs = lag - 1.4` and `lagHighMs = lag + frame period + 1.4`: the truth lies in that interval
(16.7 + 2.7 ms wide at 60 fps; 33.3 + 2.7 ms at 30 fps). A video is resampled to constant frame rate, which snaps each frame to the nearest source frame, so for a video the interval is half a period wider on each side (`[lag - period/2 - hop/2, lag + 1.5 period + hop/2]`), and the verdict is read off the interval. This holds for events on and off the frame grid in the fixtures
(`sync.test.mjs`; the video clips there are built with frame stamps at or after the change, the model's assumption). The display's own latency (the time from stamp to light) is not in it.
## What the metric cannot tell you
- **Whether it feels right.** Two onsets agreeing says the energy rose at the same time, not that the sound belongs to the picture.
A person must watch and listen.
- **That the pairing is the right pairing.** Onsets are matched by nearness. A sound that belongs to an earlier or later visual
event can be paired with the wrong one; with an event log, the log is trusted, with none, nothing checks the pairing but you.
- **Which onset the viewer attends to.** A swell, a reverb tail, a ramped attack or a low-frequency thump has a perceptual onset
later than the first sample above the threshold; a flash with a fade reads late the same way. A decaying visual (afterimage, a bloom
that outlives the event) is not modelled.
- **Anything about the chain you did not capture.** If the capture is of the app's output, display latency, speaker/Bluetooth
latency and a player's own sync are not in it. A capture can be in sync and the playback chain still be 150 ms off.
- **Variable frame rate.** A video is resampled by presentation time to constant frame rate (ffmpeg `fps` filter). The rate is the stream's declared one; a browser capture declares none (`1k tbr`), so it is the median gap between the frames' own times (24 to 120 fps; before this it silently fell back to 30). The interval's frame period is the larger of the resampled period and the 95th-percentile gap between source frames, so a capture that stalls for 50 ms cannot be reported as tight as a 60 fps one; the report says so when the gap sets the period. A CSV track keeps its own timestamps.
- **Stereo is mixed to mono**, so an antiphase stereo track cancels to silence and reads as no onsets.
- **Content that is not onset-shaped.** Continuous music against continuous motion has no onsets to compare; the tool returns
few or none, and silence in either track is reported as no pass, not as sync.
- **Measurements from downscaled luminance.** A flash that is local (a small icon) moves the mean luminance little and may fall
below the 10%-of-range floor; use a cropped frame-diff track in that case.
- **Known stream offsets.** `sync.test.mjs` builds clips with ffmpeg whose video or audio stream starts late (`-itsoffset`, stream copy) and checks that the known lag lies in every pair's interval, so the container start-time bookkeeping has a ground truth; the clips are synthetic flashes and tones.
- **A pulsing bed.** The bed estimate is a median of block peaks and cannot follow dynamics: a 4 Hz tremolo bed at 10% depth under the hits pulled some lags off by up to 28 ms in testing. Beds louder than a tenth of the hit and noise gates that cut the sound to digital silence (the noise resuming reads as an onset) can also give a wrong onset that passes when the true lag is well inside the window.
- **One real clip.** `fixtures/browser-capture.webm` is a headless-Chromium MediaRecorder capture (WebAudio beeps and canvas flashes scheduled at the same instants, vp8 + opus, recipe in `fixtures/record-browser-capture.cjs`). It is a test that the video path runs and pairs, not a validation of the lag it reports: nothing independent says what the true lag of that clip is. `fixtures/perlines-aurora-vfr.webm` is 6 s of Perlines v2 (Aurora disk scene, software-rendered headless Chromium) playing a click-train WAV, with the app's audio output and its canvas recorded; it declares no frame rate and stalls up to 34 ms, and is there to test that. A longer take of all three scenes and what it showed is on the minds.gamecult.org/aqua page named in the PR. No Playground UI clip has been run.
- **The tuned constants.** The 8-sigma threshold, window sizes, 200 ms pairing window, 10% floors and 2.5x bed factor were set against synthetic
fixtures (`sync-fixture.mjs`: tone-burst hits against 4-frame flashes, known offset, with noise, tone and DC beds) and one browser clip. They have not been tuned on game or music content.

View file

@ -5,6 +5,7 @@
// Usage: node feel.mjs run [--out DIR] [--only SUBSTR] [--no-gate] render, measure, write report + gallery, gate
// node feel.mjs gate REPORT.json [THRESHOLDS.json] [--partial] re-gate a report (--partial: a subset; skips id-rule and waiver bookkeeping)
// node feel.mjs compare BEFORE.json AFTER.json [--only SUBSTR] before/after table
// node feel.mjs sync --wav A.wav --track T.csv [--events E] | --video V [--fps N] [--kind luma|flux] [--shape step|ramp] [--profile P] [--lead-ms N --lag-ms N] [--pair-window-ms N] [--min-gap-ms N] [--allow-unpaired] [--json OUT] A/V synchrony (SYNC.md)
// node feel.mjs correlate TRIAL_EXPORT.json ... feel metrics vs listening-trial ratings
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
@ -53,7 +54,33 @@ async function run() {
process.exit(!noGate && !report.gate.pass ? 1 : 0);
}
async function sync() {
const { syncAnalyze, readWav, readTrack, readEvents, readVideo, formatSync, PROFILES } = await import("./sync.mjs");
try {
const val = (n) => { const i = args.indexOf(n); if (i < 0) return undefined; if (i + 1 >= args.length || args[i + 1].startsWith("--")) throw new Error(`${n} needs a value`); return args.splice(i, 2)[1]; };
const num = (n) => { const x = val(n); if (x === undefined) return undefined; if (!Number.isFinite(Number(x)) || x.trim() === "") throw new Error(`${n} needs a number, got "${x}"`); return Number(x); };
const wav = val("--wav"), trk = val("--track"), vid = val("--video"), evs = val("--events"), fps = num("--fps"), json = val("--json");
const kind = val("--kind") ?? "luma", profile = val("--profile") ?? "default", lead = num("--lead-ms"), lag = num("--lag-ms"), pw = num("--pair-window-ms"), gap = num("--min-gap-ms");
const shape = val("--shape") ?? "step", noGate = bool("--no-gate"), allowUnpaired = bool("--allow-unpaired");
if (args.length) throw new Error(`unknown argument ${args[0]}`);
if (!["step", "ramp"].includes(shape)) throw new Error(`--shape is step or ramp, got "${shape}"`);
if (!["luma", "flux"].includes(kind)) throw new Error(`--kind is luma or flux, got "${kind}"`);
if (!PROFILES[profile]) throw new Error(`--profile is one of ${Object.keys(PROFILES).join(", ")}, got "${profile}"`);
let audio, sampleRate, audioStartS = 0, visual, visualResampled = false, visualGapMs = 0;
if (vid) { const v = readVideo(vid); audio = v.audio.samples; sampleRate = v.audio.sampleRate; audioStartS = v.audio.startS; visual = kind === "flux" ? v.flux : v.luma; visualResampled = true; visualGapMs = v.sourceGapMs; }
else if (wav && trk) { const w = readWav(readFileSync(wav)); audio = w.samples; sampleRate = w.sampleRate; visual = readTrack(readFileSync(trk, "utf8"), fps); }
else throw new Error("give --video FILE, or --wav FILE with --track FILE");
const r = syncAnalyze({ audio, sampleRate, audioStartS, visual, visualKind: kind, visualShape: shape, profile, events: evs ? readEvents(readFileSync(evs, "utf8")) : undefined,
leadMs: lead, lagMs: lag, pairWindowMs: pw ?? 200, minGapMs: gap, allowUnpaired, visualResampled, visualGapMs });
r.caveat = "Nothing here was heard or seen: two onset lists compared. The metric is not the verdict; see SYNC.md.";
console.log(formatSync(r));
if (json) writeFileSync(json, JSON.stringify(r, null, 1));
process.exit(!noGate && !r.summary.pass ? 1 : 0);
} catch (e) { console.error(`sync: ${e.message}`); process.exit(2); }
}
const cmds = {
sync,
run,
gate() {
const partial = bool("--partial"), report = readJson(args[0]), g = gate(report, readJson(args[1] ?? join(here, "thresholds.json")), { partial });

View file

@ -0,0 +1,7 @@
1,hit0
1.9,hit1
2.8,hit2
3.4,hit3
4.5,hit4
5.2,hit5
6.3,hit6

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,38 @@
// Recipe for fixtures/browser-capture.webm (needs playwright-core and a chromium headless shell; edit the executablePath). Records a real browser A/V clip: WebAudio beeps + canvas flashes at the same scheduled instants, muxed by MediaRecorder. Not the Playground UI.
const { chromium } = require('playwright-core');
const fs = require('fs');
(async () => {
// CHROME=/path/to/chrome-headless-shell node record-browser-capture.cjs (writes clip.webm and events.txt in the cwd)
const browser = await chromium.launch({ executablePath: process.env.CHROME, args: ['--autoplay-policy=no-user-gesture-required'] });
const pg = await (await browser.newContext({ viewport: { width: 320, height: 180 } })).newPage();
await pg.setContent('<canvas id=c width=320 height=180></canvas>');
const res = await pg.evaluate(async () => {
const c = document.getElementById('c'), g = c.getContext('2d'), ctx = new AudioContext(), dest = ctx.createMediaStreamDestination();
await ctx.resume();
const stream = new MediaStream([...c.captureStream(30).getVideoTracks(), ...dest.stream.getAudioTracks()]);
const rec = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp8,opus' }), chunks = [];
rec.ondataavailable = e => chunks.push(e.data);
const hits = [1.0, 1.9, 2.8, 3.4, 4.5, 5.2, 6.3]; // seconds after recording start (intended instants)
let flashes = [], t0, on = 0;
const draw = (now) => {
const t = (now - t0) / 1000; let lit = false;
for (const h of hits) if (t >= h && t < h + 0.12) lit = true;
g.fillStyle = lit ? '#fff' : `rgb(${20 + (Math.random() * 3) | 0},20,20)`; g.fillRect(0, 0, 320, 180);
if (lit && !on) flashes.push(t); on = lit ? 1 : 0;
if (t < 8) requestAnimationFrame(draw); else rec.stop();
};
const done = new Promise(r => rec.onstop = r);
rec.start(100);
t0 = performance.now(); const a0 = ctx.currentTime;
for (const h of hits) { const o = ctx.createOscillator(), gn = ctx.createGain(); o.frequency.value = 880; gn.gain.setValueAtTime(0, a0 + h); gn.gain.linearRampToValueAtTime(0.5, a0 + h + 0.002); gn.gain.exponentialRampToValueAtTime(0.001, a0 + h + 0.15); o.connect(gn); gn.connect(dest); o.start(a0 + h); o.stop(a0 + h + 0.2); }
requestAnimationFrame(draw);
await done;
const blob = new Blob(chunks, { type: 'video/webm' }), buf = new Uint8Array(await blob.arrayBuffer());
let s = ''; for (let i = 0; i < buf.length; i += 8192) s += String.fromCharCode(...buf.subarray(i, i + 8192));
return { b64: btoa(s), hits, flashes, baseLatency: ctx.baseLatency, outputLatency: ctx.outputLatency };
});
fs.writeFileSync('clip.webm', Buffer.from(res.b64, 'base64'));
fs.writeFileSync('events.txt', res.hits.map((h, i) => `${h},hit${i}`).join('\n') + '\n');
console.log(JSON.stringify({ hits: res.hits, flashes: res.flashes, base: res.baseLatency, out: res.outputLatency, bytes: fs.statSync('clip.webm').size }));
await browser.close();
})();

View file

@ -16,6 +16,8 @@ seg(t,t0,d,a,b) = a + (b - a) * clip01((t - t0) / max(0.0001, d));
bez(t,a,b,c,d) = (1.0 - t) * (1.0 - t) * (1.0 - t) * a + 3.0 * (1.0 - t) * (1.0 - t) * t * b + 3.0 * (1.0 - t) * t * t * c + t * t * t * d;
seg_bez(t,t0,d,a,b,c,e) = bez(clip01((t - t0) / max(0.0001, d)), a, b, c, e);
smooth01(x) = clip01(x) * clip01(x) * (3.0 - 2.0 * clip01(x));
smoo_from(pole, x) = loop ~ _ with { loop(prev) = select2(1 - 1', prev * pole + x * (1.0 - pole), x); };
smoo_init(x) = smoo_from(1.0 - 44.1 / ma.SR, x);
seg_smooth(t,t0,d,a,b) = a + (b - a) * smooth01((t - t0) / max(0.0001, d));
seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));
seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));

View file

@ -16,6 +16,8 @@ seg(t,t0,d,a,b) = a + (b - a) * clip01((t - t0) / max(0.0001, d));
bez(t,a,b,c,d) = (1.0 - t) * (1.0 - t) * (1.0 - t) * a + 3.0 * (1.0 - t) * (1.0 - t) * t * b + 3.0 * (1.0 - t) * t * t * c + t * t * t * d;
seg_bez(t,t0,d,a,b,c,e) = bez(clip01((t - t0) / max(0.0001, d)), a, b, c, e);
smooth01(x) = clip01(x) * clip01(x) * (3.0 - 2.0 * clip01(x));
smoo_from(pole, x) = loop ~ _ with { loop(prev) = select2(1 - 1', prev * pole + x * (1.0 - pole), x); };
smoo_init(x) = smoo_from(1.0 - 44.1 / ma.SR, x);
seg_smooth(t,t0,d,a,b) = a + (b - a) * smooth01((t - t0) / max(0.0001, d));
seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));
seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));

View file

@ -16,6 +16,8 @@ seg(t,t0,d,a,b) = a + (b - a) * clip01((t - t0) / max(0.0001, d));
bez(t,a,b,c,d) = (1.0 - t) * (1.0 - t) * (1.0 - t) * a + 3.0 * (1.0 - t) * (1.0 - t) * t * b + 3.0 * (1.0 - t) * t * t * c + t * t * t * d;
seg_bez(t,t0,d,a,b,c,e) = bez(clip01((t - t0) / max(0.0001, d)), a, b, c, e);
smooth01(x) = clip01(x) * clip01(x) * (3.0 - 2.0 * clip01(x));
smoo_from(pole, x) = loop ~ _ with { loop(prev) = select2(1 - 1', prev * pole + x * (1.0 - pole), x); };
smoo_init(x) = smoo_from(1.0 - 44.1 / ma.SR, x);
seg_smooth(t,t0,d,a,b) = a + (b - a) * smooth01((t - t0) / max(0.0001, d));
seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));
seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));

View file

@ -16,6 +16,8 @@ seg(t,t0,d,a,b) = a + (b - a) * clip01((t - t0) / max(0.0001, d));
bez(t,a,b,c,d) = (1.0 - t) * (1.0 - t) * (1.0 - t) * a + 3.0 * (1.0 - t) * (1.0 - t) * t * b + 3.0 * (1.0 - t) * t * t * c + t * t * t * d;
seg_bez(t,t0,d,a,b,c,e) = bez(clip01((t - t0) / max(0.0001, d)), a, b, c, e);
smooth01(x) = clip01(x) * clip01(x) * (3.0 - 2.0 * clip01(x));
smoo_from(pole, x) = loop ~ _ with { loop(prev) = select2(1 - 1', prev * pole + x * (1.0 - pole), x); };
smoo_init(x) = smoo_from(1.0 - 44.1 / ma.SR, x);
seg_smooth(t,t0,d,a,b) = a + (b - a) * smooth01((t - t0) / max(0.0001, d));
seg_exp(t,t0,d,a,b) = exp(log(max(0.00001, a)) + (log(max(0.00001, b)) - log(max(0.00001, a))) * clip01((t - t0) / max(0.0001, d)));
seg_curve(c,t,t0,d,a,b) = select2(c < 0.5, seg_exp(t,t0,d,a,b), seg(t,t0,d,a,b));

View file

@ -0,0 +1,29 @@
// The comparison native-diff.mjs applies to one source: wasm samples against native samples, and the LIMITS that decide
// whether the difference is acceptable. Pure (no render, no file), so test native-diff.test.mjs can trip each limit with
// known perturbations. Nothing here was heard.
import { measure } from "./metrics.js";
// LIMITS sit between the largest deltas seen across 13 sources and three conditions (|LUFS| 0.017, |true peak| 0.152 dB,
// centroid 0.3 %) and a deliberate +1 dB gain (LUFS and true peak 1.0 dB); the sample bound applies only with --smoother imp3.
export const LIMITS = { lufsDb: 0.1, truePeakDb: 0.5, centroidPct: 1, relRmsErrDbImp3: -60 };
export const pick = (m) => ({ samplePeak: m.samplePeak, truePeakDb: m.truePeakDb, loudnessLufs: m.loudnessLufs, centroidMedianHz: m.centroidMedianHz, overSamples: m.overSamples, rmsDb: m.rmsDb, crestDb: m.crestDb, noiseToToneDb: m.noiseToToneDb, noiseToToneADb: m.noiseToToneADb, lowMotion: m.lowMotion });
// Row for one source, or { error } on a length mismatch (a length change is a failure, not something to trim).
export function compareRenders(id, w, n) {
if (w.length !== n.length) return { id, error: `length mismatch: wasm ${w.length}, native ${n.length}` };
const len = w.length; let maxErr = 0, at = 0, sq = 0, sqRef = 0;
for (let i = 0; i < len; i++) { const d = Math.abs(w[i] - n[i]); if (d > maxErr) { maxErr = d; at = i; } sq += d * d; sqRef += w[i] * w[i]; }
const mw = measure(w), mn = measure(n);
return { id, lenWasm: w.length, lenNative: n.length, maxErr, maxErrAt: at, rmsErr: Math.sqrt(sq / len), relRmsErrDb: 10 * Math.log10(sq / Math.max(sqRef, 1e-30)), wasm: pick(mw), native: pick(mn), measures: { wasm: mw, native: mn } };
}
// Names of the LIMITS this row breaks. `mode` is the --smoother mode; the sample bound applies only to "imp3".
export function violationsOf(r, mode) {
const v = [];
if (Math.abs(r.native.loudnessLufs - r.wasm.loudnessLufs) > LIMITS.lufsDb) v.push("loudnessLufs");
if (Math.abs(r.native.truePeakDb - r.wasm.truePeakDb) > LIMITS.truePeakDb) v.push("truePeakDb");
if (100 * Math.abs(r.native.centroidMedianHz - r.wasm.centroidMedianHz) / r.wasm.centroidMedianHz > LIMITS.centroidPct) v.push("centroidMedianHz");
if (mode === "imp3" && r.relRmsErrDb > LIMITS.relRmsErrDbImp3) v.push("relRmsErrDb");
return v;
}

View file

@ -2,9 +2,8 @@
// Faust source, at the same params, 48 kHz and length. Nothing here was heard.
// Both sides compile against their own stdlib (faustwasm bundles libfaust's; native reads AQUASYNTH_FAUST_HOME's share/faust), so a
// difference here can be library text, not the host: the report records the identities. The script exits 1
// on a render error, a length mismatch, or a LIMITS violation. LIMITS sit between the largest deltas seen across 13 sources and
// three conditions (|LUFS| 0.017, |true peak| 0.152 dB, centroid 0.3 %) and a deliberate +1 dB gain (LUFS and true peak 1.0 dB);
// the sample-level bound applies only with --smoother imp3, where the largest error seen is -75.4 dB (dx7-32, unexplained, is -79.5) and a one-sample
// on a render error, a length mismatch, or a LIMITS violation. LIMITS (native-compare.js; the evidence for their values is there, and native-diff.test.mjs trips each) bound the differences;
// the sample-level bound applies only with --smoother imp3, where the largest error seen is -75.4 dB (dx7-32 is -79.5: phasor increment rounding plus si.smoo text, docs/renders/dx7-algorithm-32-native-diff-cause.md) and a one-sample
// shift reads about -4 dB. With the library smoother the waveforms legitimately diverge (thruster -8 to -29 dB), so no sample bound.
// usage: node native-diff.mjs <FaustNativeRender dir|dll> [--tract PATH.dsp] [--out DIR] [--items core|smoother] [--smoother library|old|imp3]
// --items smoother: the 12 catalog sources that call si.smooth/si.smoo (thruster at rpm 1200, 7 patches, 4 Ding instruments, one note at 261.6256 Hz for 1.5 s)
@ -16,11 +15,11 @@ import { spawnSync } from "node:child_process";
import { join, dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import { SR, measure } from "./metrics.js";
import { SR } from "./metrics.js";
import { compareRenders, violationsOf } from "./native-compare.js";
import { gate } from "./gate.js";
import { loadRuntime, compile, renderOnce, writeWav, readText, playground } from "./render.js";
const LIMITS = { lufsDb: 0.1, truePeakDb: 0.5, centroidPct: 1, relRmsErrDbImp3: -60 };
const here = dirname(fileURLToPath(import.meta.url)), args = process.argv.slice(2);
const opt = (k) => { const i = args.indexOf(k); return i < 0 ? null : args[i + 1]; };
const bin = resolve(args[0]), out = resolve(opt("--out") ?? join(tmpdir(), "aqua-feel-native-diff"));
@ -60,22 +59,12 @@ for (const it of items) {
const r = spawnSync("dotnet", [bin.endsWith(".dll") ? bin : join(bin, "FaustNativeRender.dll"), dsp, wav, String(it.seconds), ...Object.entries(it.params).map(([k, v]) => `${k}=${v}`)], { encoding: "utf8" });
if (r.status !== 0) { rows.push({ id: it.id, error: (r.stderr || r.stdout).slice(0, 400) }); continue; }
const n = readF32Wav(wav); writeWav(join(out, `${it.id.replace(/[^A-Za-z0-9._@-]+/g, "_")}.wasm.wav`), w);
if (w.length !== n.length) { rows.push({ id: it.id, error: `length mismatch: wasm ${w.length}, native ${n.length}` }); continue; }
const len = w.length; let maxErr = 0, at = 0, sq = 0, sqRef = 0;
for (let i = 0; i < len; i++) { const d = Math.abs(w[i] - n[i]); if (d > maxErr) { maxErr = d; at = i; } sq += d * d; sqRef += w[i] * w[i]; }
const mw = measure(w), mn = measure(n);
rows.push({ id: it.id, lenWasm: w.length, lenNative: n.length, maxErr, maxErrAt: at, rmsErr: Math.sqrt(sq / len), relRmsErrDb: 10 * Math.log10(sq / Math.max(sqRef, 1e-30)),
wasm: pick(mw), native: pick(mn), flagsWasm: flagsOf(it.id, it.group, mw), flagsNative: flagsOf(it.id, it.group, mn) });
}
function pick(m) { return { samplePeak: m.samplePeak, truePeakDb: m.truePeakDb, loudnessLufs: m.loudnessLufs, centroidMedianHz: m.centroidMedianHz, overSamples: m.overSamples, rmsDb: m.rmsDb, crestDb: m.crestDb, noiseToToneDb: m.noiseToToneDb, noiseToToneADb: m.noiseToToneADb, lowMotion: m.lowMotion }; }
for (const r of rows) {
if (r.error) continue;
r.violations = [];
if (Math.abs(r.native.loudnessLufs - r.wasm.loudnessLufs) > LIMITS.lufsDb) r.violations.push("loudnessLufs");
if (Math.abs(r.native.truePeakDb - r.wasm.truePeakDb) > LIMITS.truePeakDb) r.violations.push("truePeakDb");
if (100 * Math.abs(r.native.centroidMedianHz - r.wasm.centroidMedianHz) / r.wasm.centroidMedianHz > LIMITS.centroidPct) r.violations.push("centroidMedianHz");
if (mode === "imp3" && r.relRmsErrDb > LIMITS.relRmsErrDbImp3) r.violations.push("relRmsErrDb");
const row = compareRenders(it.id, w, n);
if (row.error) { rows.push({ id: it.id, error: row.error }); continue; }
const { measures, ...rest } = row;
rows.push({ ...rest, flagsWasm: flagsOf(it.id, it.group, measures.wasm), flagsNative: flagsOf(it.id, it.group, measures.native) });
}
for (const r of rows) if (!r.error) r.violations = violationsOf(r, mode);
writeFileSync(join(out, "native-diff.json"), JSON.stringify({ libfaustWasm: rt.version, sampleRate: SR, items: set, smoother: mode, rows }, null, 1));
if (rows.some((r) => r.error || r.violations.length)) process.exitCode = 1;
console.log(JSON.stringify({ libfaustWasm: rt.version, items: set, smoother: mode, rows }, null, 1));

View file

@ -0,0 +1,74 @@
// Checks that each native-diff LIMITS entry trips on a known perturbation and stays quiet on a clean or in-tolerance pair.
// The pair is synthetic (a seeded tone-and-noise burst against a perturbed copy); no render, no dotnet, nothing heard.
// Usage: node native-diff.test.mjs
import assert from "node:assert/strict";
import { SR } from "./metrics.js";
import { LIMITS, compareRenders, violationsOf } from "./native-compare.js";
let n = 0;
const t = (name, fn) => { fn(); n++; console.log(`ok ${name}`); };
// Tones at 110/330/990 Hz with a slow envelope plus seeded noise: broadband enough that a one-sample shift is far from silent.
const sig = (() => {
let s = 12345; const r = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296 - 0.5; };
const x = new Float32Array(SR * 3);
for (let i = 0; i < x.length; i++) { const t = i / SR; x[i] = 0.25 * (0.6 * Math.sin(2 * Math.PI * 110 * t) + 0.3 * Math.sin(2 * Math.PI * 330 * t) + 0.2 * Math.sin(2 * Math.PI * 990 * t)) * (0.7 + 0.3 * Math.sin(2 * Math.PI * 1.3 * t)) + 0.05 * r(); }
return x;
})();
const gain = (x, db) => x.map((v) => v * Math.pow(10, db / 20));
const shift = (x, k) => { const y = new Float32Array(x.length); y.set(x.subarray(0, x.length - k), k); return y; };
const smooth = (x) => x.map((v, i) => 0.5 * (v + (x[i - 1] ?? 0))); // two-point average: a mild low-pass that moves the spectral centroid
const trips = (native, mode = "library") => violationsOf(compareRenders("probe", sig, native), mode);
t("identical renders trip nothing in either mode", () => {
assert.deepEqual(trips(sig), []); assert.deepEqual(trips(sig, "imp3"), []);
});
t("a +1 dB gain trips loudness and true peak, and neither the centroid nor (library mode) the sample bound", () => {
assert.deepEqual(trips(gain(sig, 1)).sort(), ["loudnessLufs", "truePeakDb"]);
});
t("a +1 dB gain also trips the sample bound under imp3 (relative error about -18 dB)", () => {
assert.deepEqual(trips(gain(sig, 1), "imp3").sort(), ["loudnessLufs", "relRmsErrDb", "truePeakDb"]);
});
t("loudness trips on its own at +0.2 dB, true peak at +0.6 dB: each limit has its own edge", () => {
assert.deepEqual(trips(gain(sig, 0.2)), ["loudnessLufs"]);
assert.ok(!trips(gain(sig, 0.05)).includes("loudnessLufs"), "+0.05 dB is inside the 0.1 LU limit");
assert.ok(trips(gain(sig, 0.6)).includes("truePeakDb"));
assert.ok(!trips(gain(sig, 0.4)).includes("truePeakDb"), "+0.4 dB is inside the 0.5 dB true-peak limit");
});
t("a spectral change (a two-point low-pass) trips the centroid limit", () => {
const row = compareRenders("probe", sig, smooth(sig));
assert.ok(100 * Math.abs(row.native.centroidMedianHz - row.wasm.centroidMedianHz) / row.wasm.centroidMedianHz > LIMITS.centroidPct);
assert.ok(violationsOf(row, "library").includes("centroidMedianHz"));
});
t("centroid edge, in literal numbers: 1000 Hz vs 1009 Hz (0.9 %) passes, vs 1011 Hz (1.1 %) trips, in both directions", () => {
const base = compareRenders("probe", sig, sig), at = (w, nat) => ({ ...base, wasm: { ...base.wasm, centroidMedianHz: w }, native: { ...base.native, centroidMedianHz: nat } });
for (const [w, nat] of [[1000, 1009], [1000, 991], [1000, 1000]]) assert.deepEqual(violationsOf(at(w, nat), "library"), [], `${w} vs ${nat}`);
for (const [w, nat] of [[1000, 1011], [1000, 989]]) assert.deepEqual(violationsOf(at(w, nat), "library"), ["centroidMedianHz"], `${w} vs ${nat}`);
});
t("a one-sample shift trips only the sample bound, and only under imp3 (library mode has no sample bound)", () => {
const sh = shift(sig, 1), row = compareRenders("probe", sig, sh);
assert.ok(row.relRmsErrDb > LIMITS.relRmsErrDbImp3, `relRmsErrDb ${row.relRmsErrDb}`);
assert.deepEqual(violationsOf(row, "imp3"), ["relRmsErrDb"]);
assert.deepEqual(violationsOf(row, "library"), []);
assert.deepEqual(violationsOf(row, "old"), []);
});
t("an error well inside the sample bound passes under imp3", () => {
const near = sig.map((v, i) => v + (i % 2 ? 1 : -1) * 1e-5);
assert.ok(compareRenders("probe", sig, near).relRmsErrDb < LIMITS.relRmsErrDbImp3);
assert.deepEqual(trips(near, "imp3"), []);
});
t("a length mismatch is an error row, not a trimmed comparison", () => {
const row = compareRenders("probe", sig, sig.subarray(0, sig.length - 512));
assert.match(row.error, /length mismatch: wasm 144000, native 143488/);
assert.equal(row.wasm, undefined);
});
console.log(`${n} passed`);

View file

@ -3,5 +3,5 @@
"private": true,
"type": "module",
"description": "Headless feel meter for AquaSynth: renders every shipped patch and Ding offline and measures them. Measures; does not listen.",
"scripts": { "test": "node test.mjs", "feel": "node feel.mjs", "shelf": "node shelf.mjs build", "shelf:check": "node shelf.mjs check" }
"scripts": { "test": "node test.mjs && node sync.test.mjs && node native-diff.test.mjs", "feel": "node feel.mjs", "shelf": "node shelf.mjs build", "shelf:check": "node shelf.mjs check" }
}

View file

@ -859,7 +859,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {
@ -1106,7 +1106,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {
@ -1265,7 +1265,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {
@ -1415,7 +1415,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {
@ -1440,7 +1440,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {
@ -1565,7 +1565,7 @@
"kind": "start",
"detail": "plays from the moment it is started; no gate, trigger or audio-feature input. Sliders, where listed, are live while it plays."
},
"behaviour": "sustained: still sounding at the end of the render window, runs until stopped",
"behaviour": "decays: dies away inside the render window",
"duration_s": 3,
"duration_note": "the render window, not the effect's length",
"render": {

View file

@ -0,0 +1,39 @@
// Synthetic A/V fixture with a known offset: event times, a mono WAV of tone-burst "hits", and a per-frame luminance track of flashes.
// The audio is the visual delayed by offsetMs (positive = audio late), so syncAnalyze must recover lag = offsetMs. Nothing here is a real capture.
// CLI: node sync-fixture.mjs OUTDIR [offsetMs=80] [fps=60] writes OUTDIR/{fixture.wav,track.csv,events.txt,truth.json}
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { wavFloat32 } from "./render.js";
export const FIXTURE_EVENTS_S = [0.5, 1.3, 2.2, 3.4, 4.1, 5.0];
// bed: steady tones [[hz, amp], ...] under the hits; dc: constant offset; gain: hit amplitude. Events need not sit on frame boundaries.
export function makeFixture({ offsetMs = 80, fps = 60, sampleRate = 48000, seconds = 6, noise = 0.003, events = FIXTURE_EVENTS_S, seed = 7, bed = [], dc = 0, gain = 0.6 } = {}) {
let s = seed >>> 0; const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32 - 0.5; };
const audio = new Float32Array(Math.round(sampleRate * seconds));
for (let i = 0; i < audio.length; i++) { audio[i] = dc + noise * 2 * rand(); for (const [hz, amp] of bed) audio[i] += amp * Math.sin((2 * Math.PI * hz * i) / sampleRate); }
for (const e of events) { // 40 ms decaying 880 Hz burst with a 1 ms ramp: a hit with a sharp but not instantaneous attack
const start = Math.round((e + offsetMs / 1000) * sampleRate);
for (let j = 0; j < 0.04 * sampleRate && start + j < audio.length; j++) {
const t = j / sampleRate; audio[start + j] += gain * Math.min(1, t / 0.001) * Math.exp(-t / 0.012) * Math.sin(2 * Math.PI * 880 * t);
}
}
const n = Math.round(fps * seconds), t = new Float64Array(n), v = new Float64Array(n);
for (let f = 0; f < n; f++) { // frame f is on screen from f/fps; a flash is bright for 4 frames starting at the first frame at or after the event
t[f] = f / fps; v[f] = 0.1 + 0.01 * 2 * rand();
for (const e of events) { const f0 = Math.ceil(e * fps - 1e-9); if (f >= f0 && f < f0 + 4) v[f] = 0.9; }
}
return { audio, sampleRate, visual: { t, v }, events: events.map((e, i) => ({ t: e, label: `hit${i}` })), offsetMs, fps };
}
if (import.meta.url === `file://${process.argv[1]}`) {
const [dir, off = "80", fps = "60"] = process.argv.slice(2);
if (!dir) { console.error("usage: node sync-fixture.mjs OUTDIR [offsetMs=80] [fps=60]"); process.exit(2); }
const fx = makeFixture({ offsetMs: Number(off), fps: Number(fps) }); mkdirSync(dir, { recursive: true });
const wav = wavFloat32(fx.audio); wav.writeUInt32LE(fx.sampleRate, 24); wav.writeUInt32LE(fx.sampleRate * 4, 28); // wavFloat32 writes 48 kHz; same rate here
writeFileSync(join(dir, "fixture.wav"), wav);
writeFileSync(join(dir, "track.csv"), "t,luma\n" + Array.from(fx.visual.t, (x, i) => `${x.toFixed(6)},${fx.visual.v[i].toFixed(5)}`).join("\n") + "\n");
writeFileSync(join(dir, "events.txt"), fx.events.map((e) => `${e.t},${e.label}`).join("\n") + "\n");
writeFileSync(join(dir, "truth.json"), JSON.stringify({ offsetMs: fx.offsetMs, fps: fx.fps, note: "audio = visual delayed by offsetMs; synthetic" }, null, 1));
console.log(`wrote fixture to ${dir} (audio ${fx.offsetMs} ms late)`);
}

323
tools/aqua-feel/sync.mjs Normal file
View file

@ -0,0 +1,323 @@
// aqua-feel sync: audio-visual synchrony check. Zero npm dependencies (node >= 18); ffmpeg/ffprobe only if you hand it a video.
// NOTHING HERE HEARS OR SEES ANYTHING. It compares two onset lists extracted from signals; see SYNC.md for what that cannot tell you.
// Library: syncAnalyze({ audio, sampleRate, visual:{t,v}, events, profile }) -> report. CLI wiring is in feel.mjs (`node feel.mjs sync ...`).
import { readFileSync } from "node:fs";
import { execFileSync, spawnSync } from "node:child_process";
import { fft } from "./metrics.js";
// Lag convention: lag = audio onset time - visual onset time. Positive = audio LATE (after the picture); negative = audio EARLY.
// Windows are [leadMs, lagMs]: audio may lead the picture by up to leadMs and trail it by up to lagMs before the offset is "detectable".
// Sources: see SYNC.md. 'default' is the requested conservative profile; the rest are the published ones, secondary-source figures noted there.
export const PROFILES = {
default: { leadMs: 25, lagMs: 100, note: "conservative; between ATSC IS-191 and ITU-R BT.1359-1" },
"bt1359": { leadMs: 45, lagMs: 125, note: "ITU-R BT.1359-1 (1998) detectability threshold" },
"ebu-r37": { leadMs: 40, lagMs: 60, note: "EBU R37 (2007) emission limit, per secondary source" },
"atsc-is191": { leadMs: 15, lagMs: 45, note: "ATSC IS-191 limit at the encoder input, per secondary source" },
};
// ---------- input readers ----------
export function readWav(buf) {
if (buf.toString("latin1", 0, 4) !== "RIFF" || buf.toString("latin1", 8, 12) !== "WAVE") throw new Error("not a RIFF/WAVE file");
let fmt, data;
for (let p = 12; p + 8 <= buf.length;) {
const id = buf.toString("latin1", p, p + 4), sz = buf.readUInt32LE(p + 4), body = p + 8;
if (id === "fmt ") fmt = { tag: buf.readUInt16LE(body), ch: buf.readUInt16LE(body + 2), sr: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };
if (id === "data") { data = buf.subarray(body, Math.min(buf.length, body + sz)); break; }
p = body + sz + (sz & 1);
}
if (!fmt || !data) throw new Error("WAV has no fmt or data chunk");
if (fmt.tag === 0xfffe) fmt.tag = buf.readUInt16LE(buf.indexOf("fmt ") + 8 + 24); // WAVE_FORMAT_EXTENSIBLE: sub-format tag
const bps = fmt.bits / 8, frames = Math.floor(data.length / (bps * fmt.ch)), out = new Float32Array(frames);
const get = fmt.tag === 3 && fmt.bits === 32 ? (o) => data.readFloatLE(o) : fmt.tag === 3 && fmt.bits === 64 ? (o) => data.readDoubleLE(o)
: fmt.tag === 1 && fmt.bits === 16 ? (o) => data.readInt16LE(o) / 32768 : fmt.tag === 1 && fmt.bits === 24 ? (o) => data.readIntLE(o, 3) / 8388608
: fmt.tag === 1 && fmt.bits === 32 ? (o) => data.readInt32LE(o) / 2147483648 : null;
if (!get) throw new Error(`unsupported WAV format tag ${fmt.tag} / ${fmt.bits} bit`);
for (let i = 0; i < frames; i++) { let s = 0; for (let c = 0; c < fmt.ch; c++) s += get((i * fmt.ch + c) * bps); out[i] = s / fmt.ch; } // mono mix
return { samples: out, sampleRate: fmt.sr, channels: fmt.ch };
}
const NUM = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/, num = (x) => (typeof x === "number" ? x : typeof x === "string" && NUM.test(x.trim()) ? Number(x) : NaN);
// A header is a first data line whose first field does not start like a number; a first field that does (a timecode, a hex number) is an error.
const isHeader = (line, first) => first && !/^[+-]?\.?\d/.test(line);
// Frame-diff track: lines of "t,value" (seconds, strictly increasing) or a single "value" column with fps given. Only the first line may be a header.
// Anything else that does not parse is an error: a silently dropped or shifted row would give a plausible wrong lag.
export function readTrack(text, fps) {
const t = [], v = [];
let first = true, ncols = 0;
text.replace(/^/, "").split(/\r\n|\r|\n/).forEach((raw, ln) => {
const line = raw.trim().replace(/[\s,;]+$/, ""); if (!line) return;
const wasFirst = first; first = false;
const tok = line.split(/[\s,;]+/), f = tok.map(num);
if (f.some((x) => !Number.isFinite(x))) { if (isHeader(line, wasFirst)) return; throw new Error(`track line ${ln + 1} is not numeric: ${raw}`); }
if (f.length > 2) throw new Error(`track line ${ln + 1} has ${f.length} columns; expected "t,value" or one value per line: ${raw}`);
if (ncols && f.length !== ncols) throw new Error(`track line ${ln + 1} has ${f.length} column(s), earlier lines had ${ncols} (an empty cell?): ${raw}`);
ncols = f.length;
if (f.length === 2) { if (t.length && f[0] <= t[t.length - 1]) throw new Error(`track line ${ln + 1}: time ${f[0]} does not increase`); t.push(f[0]); v.push(f[1]); }
else { if (!fps) throw new Error("single-column track needs --fps"); t.push(v.length / fps); v.push(f[0]); }
});
if (v.length < 3) throw new Error("track has fewer than 3 frames");
return { t: Float64Array.from(t), v: Float64Array.from(v) };
}
// Events: JSON array of numbers or {t,label}, or text lines "t[,label]" in seconds ('#' comments; the first line may be a header). Anything else is an error.
export function readEvents(text) {
const s = text.replace(/^/, "").trim(), fin = (x, where) => { if (!Number.isFinite(x)) throw new Error(`event ${where} has no numeric time`); return x; };
let out;
if (s.startsWith("[") || s.startsWith("{")) {
const j = JSON.parse(s), a = Array.isArray(j) ? j : j.events;
if (!Array.isArray(a)) throw new Error("events JSON must be an array or {events:[...]}");
out = a.map((e, i) => {
if (typeof e === "number") return { t: fin(e, i), label: `e${i}` };
if (!e || typeof e !== "object") return fin(NaN, i);
if (e.label !== undefined && typeof e.label !== "string") throw new Error(`event ${i} label must be a string`);
return { t: fin(num(e.t), i), label: e.label ?? `e${i}` };
});
} else {
out = []; let first = true;
s.split(/\r\n|\r|\n/).forEach((raw, ln) => {
const l = raw.trim(); if (!l || l.startsWith("#")) return;
const wasFirst = first; first = false;
const m = l.match(/^([^,;\s]+)(?:[,;\s]+(.*))?$/), t = num(m[1]);
if (!Number.isFinite(t)) { if (isHeader(l, wasFirst)) return; throw new Error(`events line ${ln + 1} does not start with a time in seconds: ${raw}`); }
out.push({ t, label: m[2]?.trim() || `e${out.length}` });
});
}
if (!out.length) throw new Error("the events log has no events");
return out;
}
// From the presentation times in ffmpeg's showinfo output: the frame rate (median gap, rounded, within [24, 120]; 30 when fewer than two frames)
// and the 95th-percentile gap between source frames, which bounds how stale a displayed frame can be in a variable-frame-rate capture.
export function sourceFrames(showinfo) {
const pts = [...String(showinfo).matchAll(/pts_time:\s*(-?\d+(?:\.\d+)?)/g)].map((m) => Number(m[1]));
const gaps = pts.slice(1).map((x, i) => x - pts[i]).filter((g) => g > 0).sort((a, b) => a - b);
if (!gaps.length) return { fps: 30, gapMs: 0 };
return { fps: Math.min(120, Math.max(24, Math.round(1 / median(gaps)))), gapMs: 1000 * gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] };
}
// Video via ffmpeg: audio as mono f32 at 48 kHz, video as 64x36 gray frames; per-frame mean luminance and mean |frame diff| (motion flux).
// Stream start_time offsets are applied so both clocks are the container's clock; video is resampled to constant frame rate by pts.
export function readVideo(path, { ffmpeg = process.env.FFMPEG ?? "ffmpeg", targetFps } = {}) {
// ffmpeg only (no ffprobe: static builds ship without it). `ffmpeg -i` lists the streams; the first decoded frame of each stream says when it starts.
const run = (a) => { const r = spawnSync(ffmpeg, a, { encoding: "utf8", maxBuffer: 1 << 26 }); if (r.error?.code === "ENOENT") throw new Error("ffmpeg is not on PATH (set FFMPEG=/path/to/ffmpeg); give --wav and --track instead"); if (r.error) throw new Error(`ffmpeg failed (${r.error.code}): its frame list may be truncated, so the capture's stalls would be under-measured`); return String(r.stderr ?? ""); };
const lines = run(["-hide_banner", "-i", path]).split("\n"), find = (kind) => lines.find((l) => new RegExp(`Stream #\\d+:\\d+.*: ${kind}:`).test(l));
const vl = find("Video"), al = find("Audio");
if (!vl || !al) throw new Error("file needs one video and one audio stream");
const idx = (l) => Number(l.match(/Stream #\d+:(\d+)/)[1]), fpsm = vl.match(/(\d+(?:\.\d+)?) fps/) ?? vl.match(/(\d+(?:\.\d+)?) tbr/);
const W = 64, H = 36, vi = idx(vl), ai = idx(al);
// A browser capture declares no frame rate (`1k tbr`). The stream's own frame times then say what rate to resample at; guessing 30 fps widened every interval to 51 ms.
const src = sourceFrames(run(["-hide_banner", "-i", path, "-map", `0:${vi}`, "-an", "-vf", "showinfo", "-f", "null", "-"]));
const fps = targetFps ?? (fpsm ? Number(fpsm[1]) : src.fps);
// Time of a stream's first frame on the container clock (ffmpeg shifts every stream by the earliest start, so these are relative to that).
const first = (flags) => { const m = run(["-hide_banner", "-i", path, ...flags, "-f", "null", "-"]).match(/pts_time:\s*(-?\d+(?:\.\d+)?)/); if (!m) throw new Error("could not read a stream start time from ffmpeg"); return Number(m[1]); };
const _vStart = first(["-map", `0:${vi}`, "-an", "-frames:v", "1", "-vf", "showinfo"]), aStart = first(["-map", `0:${ai}`, "-vn", "-frames:a", "1", "-af", "ashowinfo"]);
const out = (a) => execFileSync(ffmpeg, ["-v", "error", "-i", path, ...a, "-"], { maxBuffer: 1 << 30 });
const audioRaw = out(["-map", `0:${ai}`, "-vn", "-ac", "1", "-ar", "48000", "-f", "f32le"]);
// Resample to constant frame rate by presentation time (a variable-frame-rate source, e.g. a browser capture, repeats frames). ffmpeg pads the cfr
// video from the container start (the earliest stream start), so frame f is at f/fps whatever the video's own start_time: the video start is
// already in the padding and is not added again (adding it was a 2x-offset bug); the audio, written unpadded, carries its start as startS.
const videoRaw = out(["-map", `0:${vi}`, "-an", "-vf", `fps=${fps},scale=${W}:${H}:flags=area,format=gray`, "-f", "rawvideo"]);
const frames = Math.floor(videoRaw.length / (W * H)), t = new Float64Array(frames), lum = new Float64Array(frames), flux = new Float64Array(frames);
for (let f = 0; f < frames; f++) {
let s = 0, df = 0; for (let i = 0; i < W * H; i++) { const p = videoRaw[f * W * H + i]; s += p; if (f) df += Math.abs(p - videoRaw[(f - 1) * W * H + i]); }
t[f] = f / fps; lum[f] = s / (W * H) / 255; flux[f] = f ? df / (W * H) / 255 : 0;
}
const a = new Float32Array(audioRaw.buffer.slice(audioRaw.byteOffset, audioRaw.byteOffset + audioRaw.length - (audioRaw.length % 4)));
return { audio: { samples: a, sampleRate: 48000, startS: aStart }, luma: { t, v: lum }, flux: { t, v: flux }, fps, sourceGapMs: src.gapMs, resampled: true, videoStartS: _vStart };
}
// ---------- onset detection ----------
const median = (a) => { const s = Float64Array.from(a).sort(); const n = s.length; return n ? (n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2) : 0; };
// Pick onsets from a nonnegative novelty curve nov[i] at times tt[i]. A peak is a local maximum above max(floor, med + k*1.4826*MAD) and
// at least minGapS from the previous kept peak (the larger wins). The onset is the first sample of the rise that reaches riseFrac of the peak.
function pickOnsets(nov, tt, { k, floor, minGapS, riseFrac }) {
const med = median(nov), mad = median(nov.map((x) => Math.abs(x - med))), thr = Math.max(floor, med + k * 1.4826 * mad);
const peaks = [];
for (let i = 0; i < nov.length; i++) {
if (nov[i] < thr || (i && nov[i] < nov[i - 1]) || (i + 1 < nov.length && nov[i] <= nov[i + 1])) continue;
const last = peaks[peaks.length - 1];
if (last && tt[i] - tt[last] < minGapS) { if (nov[i] > nov[last]) peaks[peaks.length - 1] = i; continue; }
peaks.push(i);
}
return {
threshold: thr,
onsets: peaks.map((p) => {
let i = p; while (i > 0 && nov[i - 1] >= riseFrac * nov[p] && tt[p] - tt[i - 1] < 0.1) i--;
return { t: tt[i], peakT: tt[p], strength: nov[p] };
}),
};
}
// Audio: log-magnitude spectral flux, 1024 window / 128 hop (2.7 ms at 48 kHz), half-wave rectified, summed over 60 Hz..Nyquist.
export function audioOnsets(x, sr, { startS = 0, k = 8, minGapS = 0.05 } = {}) {
const N = 1024, HOP = 128, win = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));
const lo = Math.ceil((60 * N) / sr), hi = N / 2, frames = Math.max(0, Math.floor((x.length - N) / HOP) + 1);
const flux = new Float64Array(frames), tt = new Float64Array(frames), prev = new Float64Array(hi + 1), re = new Float64Array(N), im = new Float64Array(N);
for (let f = 0; f < frames; f++) {
for (let i = 0; i < N; i++) { re[i] = x[f * HOP + i] * win[i]; im[i] = 0; }
fft(re, im);
let s = 0;
for (let b = lo; b <= hi; b++) { const m = Math.log1p(1e3 * Math.hypot(re[b], im[b]) / N); if (f) s += Math.max(0, m - prev[b]); prev[b] = m; }
flux[f] = s; tt[f] = startS + (f * HOP + N / 2) / sr; // a frame is stamped at its centre
}
// The window centre sits half a window after the first audible sample's frame start; the rise-start pick lands within one window of the true onset.
const r = pickOnsets(flux, tt, { k, floor: 1e-3 * hi, minGapS, riseFrac: 0.25 });
// The flux frame is only good to a window; refine each onset on the samples. DC and the steady bed are estimated from the stretch before the
// search window (block peaks of |x - median|, their median, so a previous hit's tail in one block does not count); the onset is the first sample
// whose deviation exceeds max(10% of the local peak, 2.5x the bed). Search: from one window before the rise start (the window centre can sit up to
// N/2 early of a click inside it) to one window after the flux peak (over a loud bed the rise start can sit far before the real onset). If nothing clears the bar the flux time stands.
for (const o of r.onsets) {
const c = Math.round((o.t - startS) * sr), cp = Math.round((o.peakT - startS) * sr), a0 = Math.max(0, c - N), a1 = Math.min(x.length, cp + N), b0 = Math.max(0, a0 - 8 * 512), blocks = [];
const dc = median(Array.from(x.subarray(b0, a1)));
for (let q = b0; q + 512 <= a0; q += 512) { let m = 0; for (let i = q; i < q + 512; i++) m = Math.max(m, Math.abs(x[i] - dc)); blocks.push(m); }
const bed = blocks.length ? median(blocks) : 0;
let pk = 0; for (let i = a0; i < a1; i++) pk = Math.max(pk, Math.abs(x[i] - dc));
const bar = Math.max(0.1 * pk, 2.5 * bed);
for (let i = a0; i < a1; i++) if (Math.abs(x[i] - dc) >= bar && bar < pk) { o.t = startS + i / sr; break; }
}
// Two flux peaks can refine to the same sample onset (a step in the bed plus the hit): keep one per refined time within the minimum gap.
r.onsets = r.onsets.reduce((acc, o) => { const l = acc[acc.length - 1]; if (l && o.t - l.t < minGapS) { if (o.strength > l.strength) acc[acc.length - 1] = { ...o, t: Math.min(o.t, l.t) }; } else acc.push(o); return acc; }, []);
r.resolutionMs = (1000 * HOP) / sr; r.windowMs = (1000 * N) / sr;
return r;
}
// Visual: onset = frame where the track rises. Luminance uses the positive frame-to-frame step; motion flux is already a change measure.
export function visualOnsets(track, { kind = "luma", k = 8, minGapS = 0.1 } = {}) {
const { t, v } = track, nov = new Float64Array(v.length);
for (let i = 1; i < v.length; i++) nov[i] = kind === "luma" ? Math.max(0, v[i] - v[i - 1]) : Math.max(0, v[i]);
const range = Math.max(...v) - Math.min(...v);
const r = pickOnsets(nov, t, { k, floor: 0.1 * range + 1e-12, minGapS, riseFrac: 0.5 });
const dts = []; for (let i = 1; i < t.length; i++) dts.push(t[i] - t[i - 1]);
r.framePeriodMs = 1000 * median(dts);
return r;
}
// Visual, ramp-shaped response (a slow brightening or swell over hundreds of ms, no step): the track's rise over `riseS` is the novelty; each peak of it
// is one response. From the quiet level before it (the last sample within 2 noise sigmas of the minimum of the 0.6 s before the peak) to the top, the
// onset is the foot of the line through the 20% and 80% crossings, clamped to [valley, 20% crossing]. The start is only known to lie in
// [valley - (valley to 20% time) - one frame, crossing20S]: a ramp has no first frame, so the onset carries that span and the verdict is read off it, not off the foot.
export function visualRampOnsets(track, { minGapS = 0.5, riseS = 0.3, k = 6 } = {}) {
const { t, v } = track, n = v.length, dts = []; for (let i = 1; i < n; i++) dts.push(t[i] - t[i - 1]);
const period = median(dts), at = (x) => { let lo = 0, hi = n - 1; while (lo < hi) { const m = (lo + hi) >> 1; if (t[m] < x) lo = m + 1; else hi = m; } return lo; };
// Moving average over +-60 ms of TIME (not of samples: a variable-frame-rate track must not stretch it), by prefix sums.
const cs = new Float64Array(n + 1); for (let i = 0; i < n; i++) cs[i + 1] = cs[i] + v[i];
const sm = new Float64Array(n); for (let i = 0; i < n; i++) { const a = at(t[i] - 0.06), b = at(t[i] + 0.06 + 1e-9); const hi = t[b] <= t[i] + 0.06 + 1e-9 ? b : b - 1; sm[i] = (cs[Math.max(hi, i) + 1] - cs[a]) / (Math.max(hi, i) + 1 - a); }
const range = Math.max(...v) - Math.min(...v), d1 = Float64Array.from(v.slice(1), (x, i) => Math.abs(x - v[i])), sigma = 1.4826 * median(d1) / Math.SQRT2 + 1e-12;
const nov = new Float64Array(n); for (let i = 0; i < n; i++) nov[i] = Math.max(0, sm[Math.min(n - 1, at(t[i] + riseS))] - sm[i]);
const r = pickOnsets(nov, t, { k, floor: Math.max(0.15 * range, k * sigma), minGapS, riseFrac: 1 });
r.framePeriodMs = 1000 * period;
r.onsets = r.onsets.map((o) => {
const p = at(o.peakT), b0 = at(o.peakT - 0.6); let mn = Infinity; for (let i = b0; i <= p; i++) mn = Math.min(mn, sm[i]);
let m = p; while (m > b0 && sm[m] > mn + 2 * sigma) m--;
let top = m; for (let i = m; i < Math.min(n, at(o.peakT + riseS + 0.3)); i++) if (sm[i] > sm[top]) top = i;
const A = sm[top] - sm[m], cross = (f) => { let i = m; while (i < top && sm[i] < sm[m] + f * A) i++; return i; };
const i20 = cross(0.2), i80 = cross(0.8), foot0 = t[i20] - (t[i80] - t[i20]) / 3;
// The upper bound on the start comes from the raw samples, not the smoothed ones (a centred average crosses before the picture does): the first raw
// frame at or above the quiet level plus 20% of the rise, and no less than 4 noise sigmas, was stamped after the change began.
let hi = m; while (hi < n - 1 && v[hi] < sm[m] + Math.max(0.2 * A, 4 * sigma)) hi++;
const foot = Math.min(t[hi], Math.max(t[m], foot0));
// Over a decaying tail the minimum of the sum lands after the true start (a slow ramp cancels the decay before it turns the curve): the lower bound backs off
// by the valley-to-crossing time. It is a heuristic, not a bound (a slow start can begin much earlier), and the verdict does not lean on it.
return { t: foot, loS: t[m] - (t[hi] - t[m]) - period, hiS: t[hi], peakT: t[top], strength: A };
});
return r;
}
// ---------- pairing and verdict ----------
// One-to-one greedy matching of onsets to anchors (events, or audio onsets) by distance, within windowS. Returns Map anchorIndex -> onsetIndex.
function match(anchors, onsets, windowS) {
const edges = [];
anchors.forEach((a, i) => onsets.forEach((o, j) => { const d = Math.abs(o.t - a); if (d <= windowS) edges.push([d, i, j]); }));
edges.sort((x, y) => x[0] - y[0]);
const ai = new Map(), oj = new Set();
for (const [, i, j] of edges) if (!ai.has(i) && !oj.has(j)) { ai.set(i, j); oj.add(j); }
return ai;
}
// Nearest-onset pairing is right only if the true lag is under half the spacing of that train's onsets. The caller declares the largest lag it
// considers plausible (the pairing window); a pair whose neighbouring onset lies closer than twice that cannot be told from a swap.
const crowded = (list, o, windowS) => list.some((x) => x !== o && Math.abs(x.t - o.t) < 2 * windowS);
// Frame quantisation: a visual change at time tau first shows in the frame stamped at or after tau, so visual - tau is in [0, framePeriod) and the
// measured lag (audio - visual) is biased LOW by up to a frame period. The truth therefore lies in [lag - audioHop/2, lag + framePeriod + audioHop/2];
// a pair is judged on that interval, not on a point.
export function syncAnalyze({ audio, sampleRate, audioStartS = 0, visual, visualKind = "luma", visualShape = "step", events, profile = "default", leadMs, lagMs, pairWindowMs = 200, minGapMs, allowUnpaired = false, visualResampled = false, visualGapMs = 0 }) {
if (!PROFILES[profile]) throw new Error(`unknown profile ${profile}`);
const prof = { ...PROFILES[profile] }, custom = leadMs !== undefined || lagMs !== undefined;
if (leadMs !== undefined) prof.leadMs = leadMs;
if (lagMs !== undefined) prof.lagMs = lagMs;
if (custom) { prof.note = `profile ${profile} with the window overridden on the command line`; }
for (const [n, x] of [["leadMs", prof.leadMs], ["lagMs", prof.lagMs], ["pairWindowMs", pairWindowMs]]) if (!Number.isFinite(x) || x < 0 || (n === "pairWindowMs" && x === 0)) throw new Error(`${n} must be a ${n === "pairWindowMs" ? "positive" : "non-negative"} number`);
const gap = minGapMs === undefined ? {} : { minGapS: minGapMs / 1000 };
const a = audioOnsets(audio, sampleRate, { startS: audioStartS, ...gap }), v = visualShape === "ramp" ? visualRampOnsets(visual, gap.minGapS === undefined ? {} : { minGapS: gap.minGapS }) : visualOnsets(visual, { kind: visualKind, ...gap });
// A video resampled to constant frame rate by `fps` snaps each frame to the nearest source frame: half a period more slack on each side.
const hopMs = a.resolutionMs, periodMs = Math.max(v.framePeriodMs, visualGapMs), win = pairWindowMs / 1000, snapMs = visualResampled ? periodMs / 2 : 0;
const classify = (lo, hi, ramp) => {
// A ramp is never given a gate-failing verdict. Two Soul passes falsified every claim a ramp could make: its start cannot be bounded below (a slow start sits under the noise),
// and any upper bound read from the raw frames is moved earlier by one outlier frame, and the pairing by a bed that swells near the hit. The intervals are printed as estimates.
if (ramp) return "borderline";
if (lo >= -prof.leadMs && hi <= prof.lagMs) return "inside-window";
if (lo > prof.lagMs) return "audio-late-detectable";
if (hi < -prof.leadMs) return "audio-early-detectable";
return "borderline";
};
const pairs = [], usedA = new Set(), usedV = new Set();
const row = (label, eventS, ao, vo, ambiguous) => {
const r = { label, eventS, audioS: ao?.t ?? null, visualS: vo?.t ?? null, audioVsEventMs: ao && eventS !== null ? (ao.t - eventS) * 1e3 : null, visualVsEventMs: vo && eventS !== null ? (vo.t - eventS) * 1e3 : null, lagMs: ao && vo ? (ao.t - vo.t) * 1e3 : null };
if (r.lagMs !== null) {
// A step has its change in (visual - period, visual]. A ramp's start lies anywhere in [loS, hiS] (its quiet level to its 20% crossing).
const hiT = vo.hiS ?? vo.t, loT = vo.loS ?? vo.t - periodMs / 1000;
r.lagLowMs = (ao.t - hiT) * 1e3 - hopMs / 2 - snapMs; r.lagHighMs = (ao.t - loT) * 1e3 + hopMs / 2 + snapMs;
}
r.verdict = r.lagMs === null ? (ao ? "no-visual-onset" : vo ? "no-audio-onset" : "no-onsets") : ambiguous ? "ambiguous-pairing" : classify(r.lagLowMs, r.lagHighMs, vo.hiS !== undefined);
return r;
};
if (events) {
const et = events.map((e) => e.t), ma = match(et, a.onsets, win), mv = match(et, v.onsets, win);
events.forEach((e, i) => {
const ao = ma.has(i) ? a.onsets[ma.get(i)] : undefined, vo = mv.has(i) ? v.onsets[mv.get(i)] : undefined;
if (ao) usedA.add(ma.get(i)); if (vo) usedV.add(mv.get(i));
pairs.push(row(e.label, e.t, ao, vo, (ao && crowded(a.onsets, ao, win)) || (vo && crowded(v.onsets, vo, win))));
});
} else {
const m = match(a.onsets.map((o) => o.t), v.onsets, win);
a.onsets.forEach((ao, i) => {
if (!m.has(i)) return;
const vo = v.onsets[m.get(i)]; usedA.add(i); usedV.add(m.get(i));
pairs.push(row(`a${i}`, null, ao, vo, crowded(a.onsets, ao, win) || crowded(v.onsets, vo, win)));
});
}
const lags = pairs.map((p) => p.lagMs).filter((x) => x !== null);
const count = (f) => pairs.filter(f).length;
const summary = {
pairs: lags.length, audioOnsets: a.onsets.length, visualOnsets: v.onsets.length,
unpairedAudio: a.onsets.length - usedA.size, unpairedVisual: v.onsets.length - usedV.size,
medianLagMs: lags.length ? median(lags) : null, minLagMs: lags.length ? Math.min(...lags) : null, maxLagMs: lags.length ? Math.max(...lags) : null,
// Spread of the lags: a constant offset is a latency (fixable by a delay), a wide spread is jitter (not fixable by one number).
spreadMs: lags.length ? Math.max(...lags) - Math.min(...lags) : null,
outsideWindow: count((p) => /detectable$/.test(p.verdict)), borderline: count((p) => p.verdict === "borderline"), ambiguous: count((p) => p.verdict === "ambiguous-pairing"),
missing: count((p) => p.lagMs === null),
};
const unpaired = summary.unpairedAudio + summary.unpairedVisual;
summary.pass = summary.pairs > 0 && summary.outsideWindow === 0 && summary.missing === 0 && summary.ambiguous === 0 && (allowUnpaired || unpaired === 0);
return {
schema: "aqua-feel.sync.v1", lagConvention: "lagMs = audio onset - visual onset; positive = audio late, negative = audio early. Truth lies in [lagLowMs, lagHighMs] (visual onsets are quantised up to the next frame)",
profile: { name: custom ? `${profile}+override` : profile, ...prof }, allowUnpaired, pairWindowMs, visualResampled, visualKind, visualShape, audioResolutionMs: hopMs, framePeriodMs: periodMs, visualGapMs,
audioOnsets: a.onsets, visualOnsets: v.onsets, pairs, summary,
};
}
export function formatSync(r) {
const f = (x, d = 1) => (x === null || x === undefined ? " - " : x.toFixed(d).padStart(7));
const L = [`profile ${r.profile.name}: audio may lead by ${r.profile.leadMs} ms, lag by ${r.profile.lagMs} ms (${r.profile.note})`,
`lag = audio - visual (+ = audio late). The visual onset is quantised up to the next frame (period ${r.framePeriodMs.toFixed(1)} ms${r.visualGapMs > 0 && r.framePeriodMs === r.visualGapMs ? ": the capture\'s source frames are up to that far apart" : ""}), so the true lag lies in [lag - ${(r.audioResolutionMs / 2 + (r.visualResampled ? r.framePeriodMs / 2 : 0)).toFixed(1)}, lag + ${(r.framePeriodMs * (r.visualResampled ? 1.5 : 1) + r.audioResolutionMs / 2).toFixed(1)}] ms${r.visualResampled ? " (video resampled to constant frame rate)" : ""}`,
...(r.visualShape === "ramp" ? ["--shape ramp: the visual column is the foot of the line through the 20% and 80% crossings of each rise. A ramp has no first frame, so each interval runs from before the quiet minimum to the 20% crossing and is far wider than a step's."] : []),
"", "label event s audio s visual s a-ev ms v-ev ms lag ms verdict"];
for (const p of r.pairs) L.push(`${String(p.label).padEnd(10).slice(0, 10)} ${f(p.eventS, 3)} ${f(p.audioS, 3)} ${f(p.visualS, 3)} ${f(p.audioVsEventMs)} ${f(p.visualVsEventMs)} ${f(p.lagMs)} ${p.verdict}`);
const s = r.summary, rng = s.minLagMs === null ? "-" : `${s.minLagMs.toFixed(1)}..${s.maxLagMs.toFixed(1)}`;
L.push("", `${s.pairs} paired, ${s.unpairedAudio} audio and ${s.unpairedVisual} visual onsets unpaired${r.allowUnpaired ? " (allowed)" : " (fails the check unless --allow-unpaired)"}; median lag ${s.medianLagMs === null ? "-" : s.medianLagMs.toFixed(1)} ms, range ${rng} ms (spread ${s.spreadMs === null ? "-" : s.spreadMs.toFixed(1)} ms)`,
`${s.outsideWindow} outside the window, ${s.borderline} borderline, ${s.ambiguous} ambiguous (neighbouring onset closer than ${2 * r.pairWindowMs} ms), ${s.missing} without both onsets. ${s.pass ? (s.borderline ? `NOT DETECTABLY OUTSIDE THE WINDOW (${s.borderline} borderline: the interval straddles the edge)` : "WITHIN WINDOW") : "NOT WITHIN WINDOW"} by this metric.`,
"A metric over two onset lists, not a verdict: a person still has to watch and listen (SYNC.md).");
return L.join("\n");
}

View file

@ -0,0 +1,352 @@
// Checks of `aqua-feel sync` on synthetic fixtures with known offsets. No real capture is used. Usage: node sync.test.mjs
import assert from "node:assert/strict";
import { formatSync, syncAnalyze, readWav, readTrack, readEvents, audioOnsets, visualOnsets, visualRampOnsets, sourceFrames, PROFILES } from "./sync.mjs";
import { readFileSync } from "node:fs";
import { wavFloat32 } from "./render.js";
import { makeFixture, FIXTURE_EVENTS_S } from "./sync-fixture.mjs";
let n = 0;
const t = (name, fn) => { fn(); n++; console.log(`ok ${name}`); };
const run = (o, extra = {}) => { const fx = makeFixture(o); return { fx, r: syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, events: fx.events, ...extra }) }; };
// The truth must lie in the interval each pair reports ([lagLowMs, lagHighMs]); the interval is the claim, a point estimate is not.
const inInterval = (p, truth) => p.lagLowMs - 1e-9 <= truth && truth <= p.lagHighMs + 1e-9;
const OFFGRID = [0.5042, 1.3117, 2.2209, 3.4033, 4.1161, 5.0087]; // events between frame boundaries at 30 and 60 fps
for (const fps of [30, 60]) for (const off of [-60, -20, 0, 40, 80, 150, 190]) {
t(`${fps} fps, ${off} ms offset: the truth is inside every pair's interval, events on and off the frame grid`, () => {
for (const events of [FIXTURE_EVENTS_S, OFFGRID]) {
const { r } = run({ offsetMs: off, fps, events });
assert.equal(r.pairs.length, events.length);
for (const p of r.pairs) assert.ok(inInterval(p, off), `${p.label}: [${p.lagLowMs}, ${p.lagHighMs}] vs ${off}`);
assert.equal(r.summary.unpairedVisual, 0, "no spurious visual onsets"); assert.equal(r.summary.unpairedAudio, 0, "no spurious audio onsets");
}
});
}
t("the interval is no wider than one frame period plus one audio hop (it is a measurement, not a shrug)", () => {
const { r } = run({ offsetMs: 80, fps: 60 }), p = r.pairs[0];
assert.ok(p.lagHighMs - p.lagLowMs <= r.framePeriodMs + r.audioResolutionMs + 1e-9);
});
t("verdict classes follow the default window (lead 25, lag 100) judged on the interval", () => {
const v = (off, o = {}) => run({ offsetMs: off, ...o }).r;
assert.equal(v(0).summary.pass, true);
assert.equal(v(60).summary.pass, true, "60 ms late is inside the 100 ms lag window");
assert.equal(v(150).pairs[0].verdict, "audio-late-detectable");
assert.equal(v(-60).pairs[0].verdict, "audio-early-detectable");
assert.equal(v(95).pairs[0].verdict, "borderline", "the interval straddles the 100 ms edge");
assert.equal(v(95).summary.pass, true, "borderline is not detectably outside, so it does not fail the gate");
assert.match(formatSync(v(95)), /borderline/, "but the report says so");
assert.match(formatSync(v(0)), /WITHIN WINDOW/); assert.doesNotMatch(formatSync(v(95)), /WITHIN WINDOW/);
assert.equal(v(85, { fps: 120 }).pairs[0].verdict, "inside-window", "a finer frame clock narrows the interval");
assert.equal(v(85, { fps: 30 }).pairs[0].verdict, "borderline", "a coarser one widens it");
});
t("the profile changes the verdict, not the measurement", () => {
const a = run({ offsetMs: 70 }, { profile: "default" }).r, b = run({ offsetMs: 70 }, { profile: "ebu-r37" }).r;
assert.equal(a.pairs[0].lagMs, b.pairs[0].lagMs);
assert.equal(a.summary.pass, true); assert.equal(b.summary.pass, false);
assert.match(run({ offsetMs: 70 }, { lagMs: 200 }).r.profile.note, /overridden/, "an overridden window is not reported as the default profile");
assert.ok(PROFILES.default.leadMs === 25 && PROFILES.default.lagMs === 100);
});
t("without an events log, onsets pair by proximity and the offset is still recovered", () => {
const fx = makeFixture({ offsetMs: 60 }), r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual });
assert.equal(r.pairs.length, FIXTURE_EVENTS_S.length);
for (const p of r.pairs) assert.ok(inInterval(p, 60));
});
t("jitter shows as spread, not as a median: alternate events 0 and 90 ms late", () => {
const fx = makeFixture({ offsetMs: 0 }), clean = makeFixture({ offsetMs: 90 }), a = Float32Array.from(fx.audio);
const s0 = Math.round(FIXTURE_EVENTS_S[1] * 48000) - 100, s1 = Math.round(FIXTURE_EVENTS_S[1] * 48000) + 4800;
for (let i = s0; i < s1; i++) a[i] = clean.audio[i]; // event 1 comes from the 90 ms-late render
const r = syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events });
assert.ok(r.summary.spreadMs > 80 && r.summary.spreadMs < 100, `spread ${r.summary.spreadMs}`);
});
t("an event with no sound is reported, not paired to a neighbour", () => {
const fx = makeFixture({ offsetMs: 0 }), a = Float32Array.from(fx.audio);
for (let i = Math.round(2.0 * 48000); i < Math.round(2.6 * 48000); i++) a[i] = 0; // silence the 2.2 s hit
const r = syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events });
const p = r.pairs.find((x) => x.eventS === 2.2);
assert.equal(p.verdict, "no-audio-onset"); assert.equal(p.lagMs, null); assert.equal(r.summary.pass, false);
});
t("an offset past the 200 ms pairing window is reported as missing, not as a longer lag", () => {
const { r } = run({ offsetMs: 250 });
assert.equal(r.pairs[0].verdict, "no-audio-onset"); assert.equal(r.summary.pass, false);
});
t("sparse events (0.7 s or more apart) pair without ambiguity at a +80 ms lag; the same lag at 0.3 s spacing is ambiguous", () => {
assert.equal(run({ offsetMs: 80 }).r.summary.ambiguous, 0);
const ev = [0.5, 0.8, 1.1, 1.4, 1.7];
const { r } = run({ offsetMs: 80, events: ev });
assert.equal(r.summary.ambiguous, ev.length); assert.equal(r.summary.pass, false);
});
// ---- regressions from the Soul pass on PR #32 ----
t("a noise bed, a steady-tone bed or a DC offset under the hits does not move the audio onset (refinement is relative to the bed)", () => {
for (const o of [{ noise: 0.03 }, { bed: [[220, 0.05], [330, 0.03]] }, { dc: 0.25 }, { gain: 0.03, noise: 0.003 }, { dc: -0.3, noise: 0.02 }]) {
const { r } = run({ offsetMs: 50, ...o });
assert.equal(r.pairs.length, 6, JSON.stringify(o));
for (const p of r.pairs) assert.ok(inInterval(p, 50), `${JSON.stringify(o)} ${p.label}: ${p.lagMs}`);
}
});
t("dense hits: events 120 ms apart with a +80 ms lag are not silently paired to the previous hit", () => {
const ev = [0.5, 0.62, 0.74, 0.86, 0.98, 1.1, 1.22];
const { r } = run({ offsetMs: 80, events: ev });
// Either the pairing is right, or it is flagged; it is never a confident wrong lag with a pass.
for (const p of r.pairs) assert.ok(inInterval(p, 80) || p.verdict === "ambiguous-pairing" || p.lagMs === null, `${p.label}: ${p.lagMs} ${p.verdict}`);
assert.equal(r.summary.pass, false, "overlapping candidates inside the pairing window cannot pass");
assert.ok(r.summary.ambiguous > 0);
});
t("an audio onset is never reused by two events", () => {
const { r } = run({ offsetMs: 200, events: [0.5, 0.58, 0.66, 0.74] });
const used = r.pairs.map((p) => p.audioS).filter((x) => x !== null);
assert.equal(new Set(used).size, used.length);
});
t("a narrower --pair-window-ms resolves dense hits that the default calls ambiguous", () => {
const ev = [0.5, 0.62, 0.74, 0.86, 0.98];
const { r } = run({ offsetMs: 30, events: ev }, { pairWindowMs: 50 });
for (const p of r.pairs) assert.ok(inInterval(p, 30), `${p.label}: ${p.lagMs}`);
assert.equal(r.summary.ambiguous, 0);
});
t("flashes closer than the visual minimum gap merge, and then an event goes unpaired rather than getting another flash's lag", () => {
const { r } = run({ offsetMs: 0, events: [0.5, 0.56, 0.62, 1.5] });
assert.equal(r.summary.pass, false);
for (const p of r.pairs) assert.ok(p.lagMs === null || inInterval(p, 0) || p.verdict === "ambiguous-pairing", `${p.label}: ${p.lagMs} ${p.verdict}`);
});
t("a stray sound or flash fails the check unless --allow-unpaired is given", () => {
const fx = makeFixture({ offsetMs: 0 }), a = Float32Array.from(fx.audio), click = makeFixture({ offsetMs: 0, events: [2.8] }).audio;
for (let i = 134000; i < 137500; i++) a[i] += click[i];
const run2 = (o) => syncAnalyze({ audio: a, sampleRate: 48000, visual: fx.visual, events: fx.events, ...o });
assert.equal(run2({}).summary.unpairedAudio, 1); assert.equal(run2({}).summary.pass, false);
assert.equal(run2({ allowUnpaired: true }).summary.pass, true);
});
t("bad options fail loudly: NaN window, unknown profile", () => {
const fx = makeFixture({});
assert.throws(() => syncAnalyze({ audio: fx.audio, sampleRate: 48000, visual: fx.visual, lagMs: NaN }), /non-negative/);
assert.throws(() => syncAnalyze({ audio: fx.audio, sampleRate: 48000, visual: fx.visual, profile: "nope" }), /unknown profile/);
});
t("parsers refuse input that would give a plausible wrong answer", () => {
assert.throws(() => readEvents("0:00.5\n0:01.2\n"), /does not start with a time/);
assert.throws(() => readEvents("time,label\nfoo,bar\n"), /line 2/);
assert.deepEqual(readEvents("time,label\n0.5,a\n1.5,b, loud\n").map((e) => e.label), ["a", "b, loud"], "a header on line 1 is skipped; commas stay in the label");
assert.throws(() => readEvents("[0.5, null]"), /no numeric time/);
assert.throws(() => readEvents('[{"time":2}]'), /no numeric time/);
assert.throws(() => readEvents("# only a comment\n"), /no events/);
assert.throws(() => readTrack("0,0,0.1\n1,0.1,0.2\n2,0.2,0.3\n"), /3 columns/);
assert.throws(() => readTrack("0.0,0.1\n0.0167,\n0.0333,0.3\n"), /earlier lines had 2/);
assert.throws(() => readTrack("0,0.1\n0.5,0.2\n0.4,0.3\n"), /does not increase/);
assert.throws(() => readEvents('[{"t":null}]'), /no numeric time/); assert.throws(() => readEvents('[{"t":""},1]'), /no numeric time/);
assert.throws(() => readEvents('[{"t":true}]'), /no numeric time/); assert.throws(() => readEvents("0x10\n"), /does not start with a time/);
assert.throws(() => readEvents('[{"t":1,"label":{"a":1}}]'), /label must be a string/);
assert.throws(() => readEvents("0:01.5\n"), /does not start with a time/);
});
t("valid layouts are accepted: header after blank or comment lines, semicolons, trailing commas, CRLF, BOM", () => {
assert.equal(readTrack("\n\nt,luma\r\n0,0.1,\r\n0.1;0.2\r\n0.2 0.3\r\n").v.length, 3);
assert.equal(readTrack("\uFEFF0,0.1\n0.1,0.2\n0.2,0.3\n").v.length, 3);
assert.equal(readEvents("0.5,a\r1.0,b\r").length, 2, "CR-only line ends");
assert.equal(readTrack("t0,luma_0to1\n0,0.1\n0.1,0.2\n0.2,0.3\n").v.length, 3, "a header may contain digits");
assert.deepEqual(readEvents("# list\ntime (s);label\n0.5;kick\n1.0;snare, loud\n").map((e) => [e.t, e.label]), [[0.5, "kick"], [1, "snare, loud"]]);
});
t("zero-width windows are expressible: --lag-ms 0 makes any positive lag outside", () => {
assert.equal(run({ offsetMs: 40 }, { lagMs: 0 }).r.summary.pass, false);
});
t("silence and a flat track yield no onsets and no pass", () => {
const r = syncAnalyze({ audio: new Float32Array(48000 * 2), sampleRate: 48000, visual: { t: Float64Array.from({ length: 120 }, (_, i) => i / 60), v: new Float64Array(120).fill(0.5) } });
assert.equal(r.summary.audioOnsets, 0); assert.equal(r.summary.visualOnsets, 0); assert.equal(r.summary.pass, false);
});
t("a sine-bed with a swell rather than a click still gives one audio onset near its start", () => {
const sr = 48000, x = new Float32Array(sr * 3);
for (let i = Math.round(1 * sr); i < x.length; i++) { const tt = (i - sr) / sr; x[i] = 0.5 * Math.min(1, tt / 0.01) * Math.sin(2 * Math.PI * 440 * tt); }
const o = audioOnsets(x, sr).onsets;
assert.equal(o.length, 1); assert.ok(Math.abs(o[0].t - 1.0) < 0.012, `${o[0].t}`);
});
t("motion-flux track: a step in flux is an onset at its frame", () => {
const tt = Float64Array.from({ length: 90 }, (_, i) => i / 30), v = new Float64Array(90); v[30] = 0.4; v[31] = 0.3;
const o = visualOnsets({ t: tt, v }, { kind: "flux" }).onsets;
assert.equal(o.length, 1); assert.ok(Math.abs(o[0].t - 1.0) < 1e-9);
});
t("readWav reads 16-bit PCM and 32-bit float, mixes stereo to mono, and rejects non-WAV", () => {
const f = wavFloat32(Float32Array.from([0, 0.5, -0.5])), w = readWav(f);
assert.equal(w.sampleRate, 48000); assert.deepEqual(Array.from(w.samples), [0, 0.5, -0.5]);
const b = Buffer.alloc(44 + 8); b.write("RIFF", 0); b.writeUInt32LE(44, 4); b.write("WAVEfmt ", 8); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(2, 22);
b.writeUInt32LE(44100, 24); b.writeUInt32LE(176400, 28); b.writeUInt16LE(4, 32); b.writeUInt16LE(16, 34); b.write("data", 36); b.writeUInt32LE(8, 40);
b.writeInt16LE(16384, 44); b.writeInt16LE(-16384, 46); b.writeInt16LE(8192, 48); b.writeInt16LE(8192, 50);
const s = readWav(b); assert.equal(s.sampleRate, 44100); assert.deepEqual(Array.from(s.samples), [0, 0.25]);
assert.throws(() => readWav(Buffer.from("not a wav file at all")));
});
t("readTrack takes header + t,value rows or a single column with fps; readEvents takes lines or JSON", () => {
const a = readTrack("t,luma\n0,0.1\n0.1,0.2\n0.2,0.3\n"); assert.deepEqual(Array.from(a.t), [0, 0.1, 0.2]);
const b = readTrack("0.1\n0.2\n0.3\n", 10); assert.ok(Math.abs(b.t[2] - 0.2) < 1e-12);
assert.throws(() => readTrack("0.1\n0.2\n0.3\n"), /fps/);
assert.deepEqual(readEvents("# hits\n0.5,kick\n1.25\n").map((e) => e.t), [0.5, 1.25]);
assert.deepEqual(readEvents('[{"t":2,"label":"x"},3]').map((e) => e.label), ["x", "e1"]);
});
t("sourceFrames: the rate is the median frame gap, the stale-frame bound is the 95th-percentile gap", () => {
const si = (ts) => ts.map((x, i) => `[Parsed_showinfo_0 @ 0x1] n:${i} pts:${x * 1000} pts_time:${x} duration:1`).join("\n");
const cfr = Array.from({ length: 40 }, (_, i) => i / 50);
{ const c = sourceFrames(si(cfr)); assert.equal(c.fps, 50); assert.ok(Math.abs(c.gapMs - 20) < 1e-6); }
const vfr = []; let x = 0; for (let i = 0; i < 100; i++) { vfr.push(x); x += i % 10 === 9 ? 0.1 : 0.0167; } // mostly 60 fps, one 100 ms stall in ten
const r = sourceFrames(si(vfr)); assert.equal(r.fps, 60); assert.ok(Math.abs(r.gapMs - 100) < 1, `gap ${r.gapMs}`);
assert.deepEqual(sourceFrames(si([0])), { fps: 30, gapMs: 0 });
assert.equal(sourceFrames(si([0, 1, 2])).fps, 24); assert.equal(sourceFrames(si([0, 0.001, 0.002])).fps, 120);
});
// Ramp-shaped responses: a brightening that starts at the event and takes hundreds of ms to peak, then decays over about a second; a drifting bed and noise.
// shapes: linear ramp, exponential approach (steepest at the start), smoothstep (slowest at the start). Truth is the instant the change begins.
const SHAPES = { linear: (u) => Math.min(1, u), exponential: (u) => 1 - Math.exp(-4 * Math.min(1, u)), smoothstep: (u) => { const x = Math.min(1, u); return x * x * (3 - 2 * x); }, quadratic: (u) => Math.min(1, u) ** 2 };
const rampFixture = ({ shape, rampS, fps, offsetMs = 40, events = [0.5042, 1.9117, 3.2209, 4.6033, 5.9161, 7.2087, 8.5], noise = 0.002, decayS = 0.8 }) => {
const fx = makeFixture({ offsetMs, fps, seconds: 10, events }), nf = Math.round(fps * 10), tt = new Float64Array(nf), vv = new Float64Array(nf); let s = 11;
const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32 - 0.5; };
for (let f = 0; f < nf; f++) {
const x = f / fps; let y = 0.1 + 0.005 * Math.sin(x * 0.7) + noise * 2 * rand();
for (const e of events) if (x >= e) { const u = (x - e) / rampS; y += 0.3 * (u < 1 ? SHAPES[shape](u) : Math.exp(-(u - 1) * rampS / decayS)); }
tt[f] = x; vv[f] = y;
}
return { ...fx, visual: { t: tt, v: vv }, events: events.map((e, i) => ({ t: e, label: `r${i}` })) };
};
for (const shape of Object.keys(SHAPES)) for (const [rampS, fps] of [[0.25, 60], [0.45, 60], [0.35, 30]]) {
t(`ramp (${shape}, ${rampS * 1000} ms to peak, ${fps} fps): every response is found, and the true start lies in each pair's interval`, () => {
const fx = rampFixture({ shape, rampS, fps }), r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, visualShape: "ramp", events: fx.events });
assert.equal(r.pairs.length, fx.events.length); assert.equal(r.summary.unpairedVisual, 0);
for (const p of r.pairs) assert.ok(inInterval(p, fx.offsetMs), `${shape}/${rampS}/${fps} ${p.label}: [${p.lagLowMs}, ${p.lagHighMs}] vs ${fx.offsetMs}`);
for (const p of r.pairs) assert.ok(Math.abs(p.visualVsEventMs) <= 0.45 * rampS * 1000 + 1e3 / fps, `${p.label}: foot ${p.visualVsEventMs} ms from the true start`);
});
}
for (const offsetMs of [-60, 0, 150]) t(`ramp: a known ${offsetMs} ms offset stays inside the interval for every shape (30 and 60 fps)`, () => {
for (const shape of Object.keys(SHAPES)) for (const fps of [30, 60]) {
const fx = rampFixture({ shape, rampS: 0.3, fps, offsetMs }), r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, visualShape: "ramp", events: fx.events });
assert.equal(r.pairs.length, fx.events.length, `${shape}/${fps}`);
for (const p of r.pairs) assert.ok(inInterval(p, offsetMs), `${shape}/${fps}/${offsetMs} ${p.label}: [${p.lagLowMs}, ${p.lagHighMs}]`);
}
});
t("ramp: the interval is wide and says so (a ramp has no first frame); it is judged on the whole interval", () => {
const fx = rampFixture({ shape: "smoothstep", rampS: 0.45, fps: 60, offsetMs: 0 }), r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, visualShape: "ramp", events: fx.events });
for (const p of r.pairs) { assert.ok(p.lagHighMs - p.lagLowMs > 100, `interval ${p.lagHighMs - p.lagLowMs} ms`); assert.equal(p.verdict, "borderline"); }
const late = rampFixture({ shape: "linear", rampS: 0.3, fps: 60, offsetMs: 400 }), rl = syncAnalyze({ audio: late.audio, sampleRate: late.sampleRate, visual: late.visual, visualShape: "ramp", pairWindowMs: 450, events: late.events });
assert.ok(rl.pairs.every((p) => p.verdict === "borderline" && p.lagMs > 300), "a ramp 400 ms ahead of the sound is measured but never given a verdict that fails the gate");
});
// A ramp verdict may be silent but not wrong. Soul found (a) a centred 60 ms average crosses before a fast picture does, so 'late' was claimed at true lags inside the window,
// and (b) slow-start shapes begin far before they look like they do, so 'early' or 'inside' was claimed at true lags of 0 to 40 ms. Truth is known in every case.
t("ramp: a fast rise or a step is never called detectably late", () => {
for (const [rampS, off] of [[0.04, 98], [0.04, 60], [0.001, 60], [0.08, 90]]) for (const fps of [30, 60]) {
const fx = rampFixture({ shape: "linear", rampS, fps, offsetMs: off, events: [0.5042, 1.9117, 3.2209, 4.6033, 5.9161, 7.2087, 8.5] });
const r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, visualShape: "ramp", events: fx.events });
for (const p of r.pairs) assert.notEqual(p.verdict, "audio-late-detectable", `${rampS * 1000} ms rise, ${fps} fps, true lag ${off}: [${p.lagLowMs}, ${p.lagHighMs}]`);
}
});
t("ramp: a variable-frame-rate track does not stretch the smoothing or the bound (gaps up to 100 ms)", () => {
const fx = rampFixture({ shape: "linear", rampS: 0.1, fps: 60, offsetMs: 40 }); let s = 3; const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32; };
const keep = []; let next = 0; for (let i = 0; i < fx.visual.t.length; i++) if (fx.visual.t[i] >= next) { keep.push(i); next = fx.visual.t[i] + (rand() < 0.3 ? 0.1 * rand() : 0.017); }
const visual = { t: Float64Array.from(keep, (i) => fx.visual.t[i]), v: Float64Array.from(keep, (i) => fx.visual.v[i]) };
const r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual, visualShape: "ramp", events: fx.events, allowUnpaired: true });
assert.ok(r.pairs.length >= 5);
for (const p of r.pairs) assert.ok(p.verdict !== "audio-late-detectable", `[${p.lagLowMs}, ${p.lagHighMs}] verdict ${p.verdict} at true lag 40`);
});
t("ramp: sweep of 120 shapes, rises (40-800 ms), decays, frame rates, noise and offsets: a ramp is never given a claim", () => {
let s = 19; const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32; }, pick = (a) => a[Math.floor(rand() * a.length)];
for (let k = 0; k < 120; k++) {
const shape = pick(Object.keys(SHAPES)), rampS = pick([0.04, 0.08, 0.15, 0.3, 0.5, 0.8]), fps = pick([24, 30, 60, 120]), off = pick([-80, -40, 0, 20, 40, 98, 130, 200]), decayS = pick([0.3, 0.8, 2]), noise = pick([0.001, 0.004, 0.01]);
const fx = rampFixture({ shape, rampS, fps, offsetMs: off, decayS, noise, events: [0.5042, 2.1117, 3.7209, 5.3033, 6.9161, 8.5087] });
const r = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: fx.visual, visualShape: "ramp", pairWindowMs: 250, allowUnpaired: true, events: fx.events });
for (const p of r.pairs) {
assert.ok(["borderline", "ambiguous-pairing", "no-visual-onset"].includes(p.verdict), `${shape}/${rampS}/${fps}fps/${off}: a ramp gets no gate-failing or inside verdict, got ${p.verdict} [${p.lagLowMs}, ${p.lagHighMs}]`);
}
}
});
// The two cases the second Soul pass broke (a raw outlier frame before the true start, and a bed that swells near a hit): the detector may be fooled, the verdict may not follow.
t("ramp: one outlier frame before a hit, or a swelling bed near it, cannot produce a gate-failing verdict", () => {
const fx = rampFixture({ shape: "linear", rampS: 0.02, fps: 60, offsetMs: 80 }), v = Float64Array.from(fx.visual.v), tt = fx.visual.t;
for (const e of fx.events) { const i = Math.round((e.t - 0.2) * 60); v[i] += 0.07; } // one bright frame 200 ms before each hit
const spiked = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: { t: tt, v }, visualShape: "ramp", events: fx.events, allowUnpaired: true });
const bed = Float64Array.from(fx.visual.v, (x, i) => x + 0.2 * Math.max(0, Math.sin(2 * Math.PI * tt[i]))); // a 1 Hz swell under the hits
const swelling = syncAnalyze({ audio: fx.audio, sampleRate: fx.sampleRate, visual: { t: tt, v: bed }, visualShape: "ramp", events: fx.events, allowUnpaired: true });
for (const r of [spiked, swelling]) { assert.ok(r.pairs.length > 0); assert.ok(r.pairs.every((p) => !/detectable$/.test(p.verdict)), JSON.stringify(r.pairs.map((p) => p.verdict))); assert.equal(r.summary.outsideWindow, 0); }
});
t("ramp: noise, a steady drift and a lone step give no ramp onsets from noise or drift", () => {
const nf = 600, tt = Float64Array.from({ length: nf }, (_, i) => i / 60); let s = 5; const rand = () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32 - 0.5; };
assert.equal(visualRampOnsets({ t: tt, v: Float64Array.from(tt, () => 0.2 + 0.01 * rand()) }).onsets.length, 0, "noise");
assert.equal(visualRampOnsets({ t: tt, v: Float64Array.from(tt, (x) => 0.1 + 0.03 * x + 0.004 * rand()) }).onsets.length, 0, "a drift over the whole clip is not a response");
});
// The video path needs ffmpeg (FFMPEG=/path or on PATH); skipped, and said so, when there is none.
{
const { readVideo } = await import("./sync.mjs"), { execFileSync } = await import("node:child_process"), require_fs = await import("node:fs"), { tmpdir } = await import("node:os"), { join } = await import("node:path");
const ff = process.env.FFMPEG ?? "ffmpeg";
let have = true; try { execFileSync(ff, ["-version"], { stdio: "ignore" }); } catch { have = false; }
if (!have) console.log("skip video path: no ffmpeg (set FFMPEG)");
if (have) for (const [vOff, aOff, vfps] of [[0, 0, 60], [0.06, 0, 60], [0, 0.08, 60], [0.25, 0.1, 60], [0.5, 0.5, 60], [0.1, 0, 15], [0.1, 0, 24], [0, 0.1, 15]]) {
const { mkdtempSync, writeFileSync } = await import("node:fs"), { tmpdir } = await import("node:os"), { join } = await import("node:path");
const dir = mkdtempSync(join(tmpdir(), "sync-clip-")), fx = makeFixture({ offsetMs: 0, fps: 60, seconds: 4, events: [0.5, 1.4, 2.3, 3.2] });
const wavP = join(dir, "a.wav"), rawP = join(dir, "v.gray"), outP = join(dir, "clip.mkv");
writeFileSync(wavP, wavFloat32(fx.audio));
writeFileSync(rawP, Buffer.concat(Array.from(fx.visual.v, (x) => Buffer.alloc(64 * 36, Math.round(255 * x)))));
// encode each stream alone, then mux with -itsoffset and stream copy: that is what puts a start_time on the stream in the file
const vP = join(dir, "v.mkv"), aP = join(dir, "a.mka");
execFileSync(ff, ["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "gray", "-s", "64x36", "-r", "60", "-i", rawP, "-vf", `fps=${vfps}:round=up`, "-c:v", "ffv1", vP]);
execFileSync(ff, ["-v", "error", "-y", "-i", wavP, "-c:a", "pcm_s16le", aP]);
execFileSync(ff, ["-v", "error", "-y", "-itsoffset", String(vOff), "-i", vP, "-itsoffset", String(aOff), "-i", aP, "-map", "0:v", "-map", "1:a", "-c", "copy", outP]);
const v = readVideo(outP, { ffmpeg: ff }), truth = (aOff - vOff) * 1000; // audio = visual shifted by (aOff - vOff)
// events are on the container clock, which ffmpeg shifts so the earliest stream starts at 0
const r = syncAnalyze({ audio: v.audio.samples, sampleRate: v.audio.sampleRate, audioStartS: v.audio.startS, visual: v.luma, events: fx.events.map((e) => ({ t: e.t + vOff - Math.min(vOff, aOff), label: e.label })), visualResampled: v.resampled });
n++; console.log(`ok ffmpeg clip, video (${vfps} fps) starts ${vOff * 1000} ms, audio ${aOff * 1000} ms: true lag ${truth} ms inside every interval`);
for (const p of r.pairs) assert.ok(p.lagLowMs - 1e-6 <= truth && truth <= p.lagHighMs + 1e-6, `video@${vOff}/${vfps}fps audio@${aOff}: [${p.lagLowMs}, ${p.lagHighMs}] vs ${truth}`);
assert.equal(r.pairs.length, 4);
}
if (have) t("a real browser capture (VFR vp8+opus webm): every logged hit pairs, and the lag is a constant (spread under one frame)", () => {
const v = readVideo(new URL("./fixtures/browser-capture.webm", import.meta.url).pathname, { ffmpeg: ff });
const ev = readEvents(readFileSync(new URL("./fixtures/browser-capture.events.txt", import.meta.url), "utf8"));
const r = syncAnalyze({ audio: v.audio.samples, sampleRate: v.audio.sampleRate, audioStartS: v.audio.startS, visual: v.luma, events: ev });
assert.equal(r.pairs.length, 7); assert.equal(r.summary.missing, 0);
assert.ok(r.summary.spreadMs < 1000 / v.fps, `spread ${r.summary.spreadMs}`);
assert.equal(r.summary.unpairedAudio + r.summary.unpairedVisual, 0);
for (const p of r.pairs) assert.ok(p.visualVsEventMs >= 0 && p.visualVsEventMs <= 1000 / v.fps, `flash ${p.visualVsEventMs} ms off its logged instant`);
});
if (have) t("a Perlines v2 capture declares no frame rate (1k tbr): the rate comes from its frame times, and the interval is no narrower than its worst frame gaps", () => {
const v = readVideo(new URL("./fixtures/perlines-aurora-vfr.webm", import.meta.url).pathname, { ffmpeg: ff });
assert.ok(v.fps >= 50, `resampled at ${v.fps} fps, not the 30 fps fallback`);
assert.ok(v.sourceGapMs > 1000 / v.fps * 1.5, `source gap ${v.sourceGapMs} ms is a stalled capture, wider than one frame`);
const r = syncAnalyze({ audio: v.audio.samples, sampleRate: v.audio.sampleRate, audioStartS: v.audio.startS, visual: v.luma, allowUnpaired: true, visualResampled: true, visualGapMs: v.sourceGapMs });
assert.ok(r.pairs.length >= 3);
for (const p of r.pairs) assert.ok(p.lagHighMs - p.lagLowMs >= v.sourceGapMs * 1.5, `interval ${p.lagHighMs - p.lagLowMs} ms narrower than the capture's own stalls`);
assert.match(formatSync(r), /source frames are up to that far apart/);
});
if (have) t("a real ramp-shaped response (Perlines v2 Vector trails, off-grid hits): the step detector finds none, the ramp detector pairs at least 3 of 5, each with a wide interval", () => {
const v = readVideo(new URL("./fixtures/perlines-trails-ramp.webm", import.meta.url).pathname, { ffmpeg: ff });
const go = (visualShape) => syncAnalyze({ audio: v.audio.samples, sampleRate: v.audio.sampleRate, audioStartS: v.audio.startS, visual: v.luma, visualShape, allowUnpaired: true, visualResampled: true, visualGapMs: v.sourceGapMs });
assert.equal(go("step").pairs.length, 0);
const r = go("ramp"); assert.ok(r.pairs.length >= 3, `${r.pairs.length} paired`);
for (const p of r.pairs) assert.ok(p.lagHighMs - p.lagLowMs > 100, `interval ${p.lagHighMs - p.lagLowMs} ms`);
});
if (have) t("the CLI carries the capture's frame gaps into its report (feel.mjs plumbing)", () => {
const { mkdtempSync, readFileSync: rf } = require_fs, out = join(mkdtempSync(join(tmpdir(), "sync-cli-")), "r.json");
execFileSync("node", [new URL("./feel.mjs", import.meta.url).pathname, "sync", "--video", new URL("./fixtures/perlines-aurora-vfr.webm", import.meta.url).pathname, "--allow-unpaired", "--no-gate", "--json", out], { env: { ...process.env, FFMPEG: ff }, stdio: "ignore" });
const r = JSON.parse(rf(out, "utf8"));
assert.ok(r.visualGapMs > 1000 / 59 * 1.5, `visualGapMs ${r.visualGapMs}`); assert.equal(r.framePeriodMs, r.visualGapMs);
});
if (have) t("a failed ffmpeg read (e.g. output buffer overflow) is an error, not a quietly shorter frame list", () => {
const { mkdtempSync, writeFileSync: wf, chmodSync } = require_fs, d = mkdtempSync(join(tmpdir(), "sync-stub-")), stub = join(d, "ffmpeg");
wf(stub, "#!/bin/sh\nhead -c 70000000 /dev/zero | tr '\\0' 'x' >&2\n"); chmodSync(stub, 0o755);
assert.throws(() => readVideo(new URL("./fixtures/perlines-aurora-vfr.webm", import.meta.url).pathname, { ffmpeg: stub }), /ffmpeg failed \(ENOBUFS\)/);
});
}
console.log(`${n} sync checks passed. Fixtures only (synthetic, plus one browser capture when ffmpeg is present); nothing was heard or seen.`);

View file

@ -123,32 +123,5 @@
"why": "PRC SYNTH1 peaked at 2.10 before the 2026-11-05 gain trim to 0.67; this holds it under 0.9"
}
],
"waivers": [
{
"id": "sfxr-classic-classic-sfxr-abstract-golf",
"metric": "truePeakDb",
"reason": "renders 0.99 sample peak and +0.9 dBTP inter-sample",
"followUp": "aqua-body:follow_up:sfxr-golf-hot",
"max": 1.0
},
{
"id": "sfxr-classic-classic-sfxr-abstract-golf",
"metric": "loudnessLufs",
"reason": "-5.3 LUFS integrated over the 3 s render",
"followUp": "aqua-body:follow_up:sfxr-golf-hot",
"max": -5.0
},
{
"id": "sfxr-classic-classic-sfxr-abstract-golf",
"metric": "lowMotion",
"reason": "3 s of steady bright noise, 4 dB level range; may be longer than the render window",
"followUp": "aqua-body:follow_up:sfxr-golf-hot"
},
{
"id": "sfxr-explosion",
"metric": "lowMotion",
"reason": "3 s of steady noise, 1 dB level range, no decay inside the render window; an explosion that does not decay is worth a listener's check",
"followUp": "aqua-body:follow_up:sfxr-explosion-static"
}
]
"waivers": []
}

1
tools/aqua-listen/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
__pycache__/

View file

@ -1,8 +1,8 @@
# aqua-listen
A listening-test kit: a folder of sound clips and a manifest become **one HTML file** you can send to a listener. They open it, listen, say keep / fix / drop for each sound, and send back two small files.
A listening-test kit: a folder of sound clips and a manifest become **one HTML file** you can send to a listener. They open it, listen, say keep / fix / drop for each sound, and send back your answers.
**Status:** the page was driven in headless Chromium (consent gate, autosave across reload, export, zero network requests) and `node test.mjs` covers validation, ordering and the export shape. Nobody has listened with it yet, and the headless browser played nothing audibly; real playback on a phone or other browser is untried.
**Status:** the page was driven in headless Chromium, desktop and a mobile-emulated context (touch, 412 px viewport, Android Chrome user agent; `MOBILE=1 node smoke.mjs`): consent gate, autosave across reload, the export panel with its copy button and read-only textarea, zero network requests. It has not run on a real Android device and `node test.mjs` covers validation, ordering and the export shape. Nobody has listened with it yet, and the headless browser played nothing audibly; real playback on a phone or other browser is untried.
## For the listener (no technical knowledge needed)
@ -16,15 +16,15 @@ A listening-test kit: a folder of sound clips and a manifest become **one HTML f
5. Some sounds come as a pair, **A** and **B**. Rate both, then say which you prefer, or that there is no difference.
6. The sounds are in a random order and their names are hidden on purpose. Please don't hunt for them.
7. Your answers save themselves in your browser as you go. You can close the tab and come back to the same file later.
8. When done, press **Export**. Two files land in your downloads: `verdict.json` and `verdict.md`. Send both to whoever gave you the page. That is the only way anything leaves your computer.
8. When done, press **Export my answers**. Your answers appear in a text box. Press **Copy answers (JSON)** and paste them into a message to whoever gave you the page (or press **Share**, or **Select all** and use your phone's Copy). **Download verdict.json** and **Download verdict.md** are separate buttons, one file per tap, for browsers that allow downloads. Nothing leaves your computer except what you copy, share or download.
Privacy: the page has no network access at all (the browser is told to refuse it), no account, no tracking. "Erase my answers" at the bottom wipes what the page saved.
Privacy: the page has no network access at all (the browser is told to refuse it), no account, no tracking. "Erase this kit's saved answers" at the bottom removes what this page saved in this browser for this kit, including an older saved copy of it that the page would otherwise adopt; other pages are not touched.
## For the person building a kit
```
node build.mjs --manifest kit.json --clips ./clips --out ./dist # writes dist/listen.html
node test.mjs # 16 checks, no dependencies, no browser
node test.mjs # 23 checks, no dependencies, no browser
node smoke.mjs dist/listen.html # optional browser smoke, see below
```
@ -39,10 +39,11 @@ node smoke.mjs dist/listen.html # optional
```
- `id`, `file` (wav, mp3, ogg or flac, relative to `--clips`), `title`, `feel` (intended feel; shown to the listener), `group`: required. `pair`: optional, must name another clip whose `pair` names this one. Anything wrong stops the build with the full list of problems.
- Title, id and group are hidden from the listener and appear only in the export. The intended feel is shown, since "did it land" needs it.
- Title, id and group are not shown beside a clip, but they are in the page's bytes and in the export, which a listener can press at any time: they are not hidden. Keep a title a short neutral label; nothing a listener should not read goes in a title. The intended feel is shown, since "did it land" needs it.
- Order is shuffled from a random seed kept with the listener's answers (it is in the export). A pair is shuffled as one unit, with A/B position shuffled inside it.
- Audio is embedded as-is (base64), so the page is about 1.4x the clip bytes. The build warns over 100 MB.
- Autosave key is the kit id plus a hash of the manifest and clip bytes: a rebuilt kit with changed clips starts fresh instead of mixing answers.
- Autosave key is the kit id plus the sorted clip ids (`aqua-listen.v2:<kit id>:<ids>`), not the content hash: a rebuilt page (edited note, re-rendered clip) keeps the listener's answers, and a kit with a different clip-id set starts fresh while the old entry stays in the browser. Saved state is the shuffle seed, answers by clip id and pair choices by `idA|idB`; a pair's A/B/same value is positional (A is the first of the pair in the seed's order), so it holds only while the manifest's clip order is unchanged. When the new key is empty, the page adopts the fullest earlier `aqua-listen:<kit id>:<hash>` save whose answers name only this kit's clips; a save already under the new key is never overwritten. The save also records `pairSig`, the manifest's clip ids in manifest order: on load, a save whose `pairSig` is missing or different keeps its seed and answers and drops its pair picks, so reordering or re-pairing clips never reassigns a pick (an adopted hash-keyed save has no signature and cannot be checked, so its pairs are kept and stamped with the current one). A save missing `pairs`, or with `answers` that is not an object, is normalised to empty rather than crashing the page. "Erase this kit's saved answers" removes the new key and any adoptable hash-keyed save of this kit.
- Known limits: a clip re-rendered under the same id inherits the verdict given to its earlier version, because answers are keyed by id. A stale cached copy of an old page keeps writing to its old hash key, which the new page does not read after it has adopted its copy.
### Export
@ -52,8 +53,19 @@ The blank verdict files this was meant to match were not found under `/opt/commo
### Browser smoke
`PLAYWRIGHT_CORE=/path/to/playwright-core CHROME=/path/to/chrome node smoke.mjs dist/listen.html` ticks through consent, answers a clip, reloads, exports, and fails on any network request or page error. It is not in `node test.mjs` because the repo carries no browser dependency.
`PLAYWRIGHT_CORE=/path/to/playwright-core CHROME=/path/to/chrome node smoke.mjs dist/listen.html` ticks through consent, answers a clip, reloads, exports, then serves the page over a local http server, rebuilds it with a different content hash and checks that answers survive, that a hash-keyed save is adopted, and that erase leaves nothing to resurrect; it fails on any network request or page error. It is not in `node test.mjs` because the repo carries no browser dependency.
### Kits in the repo
`kits/voice-source` is the voice-source kit: one phrase, five pairs, each pair changing one source parameter (`pulse=`, `noise=`, `noise_hp=` on the scaffold's `source_port`, set through `WordRender --source`); `predictions.md` was committed before any clip was rendered, `hnr.py` names the noise settings in dB, `clips.py` makes the clip files. `kits/tract-weak-spots` and `kits/tract-stops` hold a `kit.json`, the `phones/*.json` that WordRender reads, and a `render.sh` that renders the clips (`render.sh <repo-root> <out-root>`; needs CULTLIB_ROOT and AQUASYNTH_FAUST_HOME, see the script header). Build a page from the rendered clips:
`node tools/aqua-listen/build.mjs --manifest tools/aqua-listen/kits/tract-stops/kit.json --clips <out-root>/clips --out <out-root>/dist`. The titles in `kits/tract-weak-spots` and `kits/tract-stops` still carry measured figures, a prediction and a falsifier, and the page does not hide them (they are in its bytes and in the export), so those pages are not blind to them. The `kits/voice-source` titles are neutral condition labels; its figures, predictions and falsifiers are in `predictions.md`.
### Pictures and burst notes (for a reader who cannot listen)
`clip_images.py <clips> <images> [--kit kit.json --renders <out-root>]` writes `<stem>.spec.png` (spectrogram, Hann 512 / hop 128, 0-8 kHz, -90..0 dB re the clip peak) and `<stem>.wave.png` (fixed +-0.5) for every wav, byte-identical between runs, and with `--kit --renders` also `burst-notes.md` and `burst-notes.json` next to the images: per plosive closure start, release (start of the with-minus-without `--no-burst` difference above 1/20 of its peak), burst end and the window to look in. Both kits' `render.sh` end with it. Requirement: `python3` with numpy and matplotlib (Agg), set `PYTHON=` to one that has them; no scipy, nothing for the dotnet build. Test: `python3 -I test_clip_images.py`.
`build.mjs --images <images>` embeds a clip's two pictures in a collapsed "Pictures of this sound" block (matched by the wav's stem) and lets the page's policy admit `data:` images, only then. The burst notes are never read by the build and never enter `listen.html` or `kit.json`: give the page to the listener and the notes to whoever reads the pictures.
## Files
`logic.cjs` validation, ordering, export shape (shared by build, page, tests) · `build.mjs` assembles the page · `web/` page template, glue and styles · `test.mjs` · `smoke.mjs`
`clip_images.py` + `test_clip_images.py` pictures and burst notes · `kits/` · `logic.cjs` validation, ordering, export shape (shared by build, page, tests) · `build.mjs` assembles the page · `web/` page template, glue and styles · `test.mjs` · `smoke.mjs`

View file

@ -1,10 +1,11 @@
#!/usr/bin/env node
// Builds one self-contained listening page. Usage:
// node build.mjs --manifest kit.json --clips DIR --out DIR (writes DIR/listen.html; --clips defaults to the manifest's folder)
// node build.mjs --manifest kit.json --clips DIR --out DIR [--images DIR] (writes DIR/listen.html; --clips defaults to the manifest's folder)
// --images: clip_images.py's output; a clip whose wav stem has <stem>.spec.png and <stem>.wave.png there gets both in a collapsed block on its card.
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from "node:fs";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { dirname, extname, join, resolve } from "node:path";
import { basename, dirname, extname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
@ -12,7 +13,7 @@ const L = createRequire(import.meta.url)("./logic.cjs");
const MIME = { ".wav": "audio/wav", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".flac": "audio/flac" };
// Throws one Error listing every manifest problem and every missing file. Returns {html, hash, bytes}.
export function buildKit(manifest, clipsDir) {
export function buildKit(manifest, clipsDir, imagesDir) {
const errs = L.validateManifest(manifest);
if (errs.length === 0) for (const c of manifest.clips) {
const f = resolve(clipsDir, c.file);
@ -27,13 +28,20 @@ export function buildKit(manifest, clipsDir) {
h.update(buf);
audio[c.id] = { mime: MIME[extname(c.file).toLowerCase()], b64: buf.toString("base64") };
}
const images = {};
if (imagesDir) for (const c of manifest.clips) {
const stem = basename(c.file, extname(c.file)), pics = [["spectrogram", "spec"], ["waveform", "wave"]].map(([label, k]) => [label, resolve(imagesDir, `${stem}.${k}.png`)]);
if (!pics.every(([, f]) => existsSync(f))) continue;
images[c.id] = pics.map(([label, f]) => { const buf = readFileSync(f); h.update(buf); return { label, b64: buf.toString("base64") }; });
}
const hash = h.digest("hex").slice(0, 8);
const data = JSON.stringify({ manifest, hash, audio }).replace(/</g, "\\u003c");
const data = JSON.stringify({ manifest, hash, audio, images }).replace(/</g, "\\u003c");
const logic = `globalThis.AquaListen=(()=>{const module={exports:{}};${readFileSync(join(here, "logic.cjs"), "utf8")}\nreturn module.exports})();`;
const part = (n) => readFileSync(join(here, "web", n), "utf8");
const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;");
// data: images only when the page carries pictures; the page without them keeps the tighter policy
// function replacers: no `$` patterns in the substituted text are interpreted
const html = part("index.html")
const html = part("index.html").replace("media-src blob:", () => Object.keys(images).length ? "media-src blob:; img-src data:" : "media-src blob:")
.replace("/*TITLE*/", () => esc(manifest.kit.title)).replace("/*STYLES*/", () => part("styles.css"))
.replace("/*DATA*/", () => data).replace("/*LOGIC*/", () => logic.replace(/<\/script/gi, "<\\/script")).replace("/*PAGE*/", () => part("page.js").replace(/<\/script/gi, "<\\/script"));
return { html, hash, bytes: Buffer.byteLength(html) };
@ -42,10 +50,10 @@ export function buildKit(manifest, clipsDir) {
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const a = process.argv.slice(2), opt = (n) => { const i = a.indexOf(n); return i < 0 ? undefined : a[i + 1]; };
const mf = opt("--manifest"), out = opt("--out");
if (!mf || !out) { console.error("usage: node build.mjs --manifest kit.json --clips DIR --out DIR"); process.exit(2); }
if (!mf || !out) { console.error("usage: node build.mjs --manifest kit.json --clips DIR --out DIR [--images DIR]"); process.exit(2); }
try {
const manifest = JSON.parse(readFileSync(mf, "utf8"));
const r = buildKit(manifest, resolve(opt("--clips") ?? dirname(resolve(mf))));
const r = buildKit(manifest, resolve(opt("--clips") ?? dirname(resolve(mf))), opt("--images") && resolve(opt("--images")));
mkdirSync(out, { recursive: true });
writeFileSync(join(out, "listen.html"), r.html);
console.log(`built ${join(out, "listen.html")}\nclips ${manifest.clips.length} bytes ${r.bytes} hash ${r.hash}`);

View file

@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""A spectrogram and a waveform PNG for every clip of a kit, and (with --kit and --renders) the burst notes.
python3 -I clip_images.py <clips-dir> <images-dir> [--kit kit.json --renders <out-root>]
Needs numpy and matplotlib (Agg); no scipy. Writes <images-dir>/<wav stem>.spec.png and .wave.png for each *.wav in <clips-dir> (sorted).
The images are deterministic: fixed figure size, dpi and STFT (Hann 512, hop 128, 0-8 kHz, -90..0 dB re the clip's loudest bin), no PNG
metadata, so two runs give identical bytes. Nothing in the pictures marks a time; the notes do, and they are written next to <images-dir>
(burst-notes.md and burst-notes.json) and are not read by build.mjs.
--renders is the out-root of a kit's render.sh (out/<w>/script.aqua and out/<w>/<w>.wav, outnb/<w>/<w>.wav). For each clip of --kit the
note gives, for each plosive gesture of the word's script: closure start (the gesture's start), release = start of the with-minus-without
(--no-burst) waveform difference above 1/20 of its peak in the gesture's window (the definition PlosiveBurstExistsOnlyAroundItsOwnRelease
uses), burst end = last such sample of the same burst, and the window to look at. A --no-burst clip says 'no burst expected'.
"""
import argparse, json, re, sys, wave
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
WIN, HOP, FMAX = 512, 128, 8000.0
DB_LO = -90.0
def read_wav(path):
with wave.open(str(path), "rb") as w:
assert w.getsampwidth() == 2 and w.getnchannels() == 1, f"{path}: expected 16-bit mono"
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float64) / 32768.0, w.getframerate()
def stft_db(x, sr):
"""dB re the loudest bin of the clip; rows are frequency 0..FMAX, columns are frames (Hann window, numpy.fft)."""
x = np.concatenate([x, np.zeros(max(0, WIN - len(x)))])
n = 1 + (len(x) - WIN) // HOP
idx = np.arange(WIN)[None, :] + HOP * np.arange(n)[:, None]
mag = np.abs(np.fft.rfft(x[idx] * np.hanning(WIN)[None, :], axis=1)).T
f = np.fft.rfftfreq(WIN, 1.0 / sr)
mag = mag[f <= FMAX]
return 20 * np.log10(np.maximum(mag, 1e-12) / max(mag.max(), 1e-12)), f[f <= FMAX], (np.arange(n) * HOP + WIN / 2) / sr
def save(fig, path):
fig.savefig(path, dpi=100, metadata={"Software": None})
plt.close(fig)
def images(wav, out):
x, sr = read_wav(wav)
db, f, t = stft_db(x, sr)
fig, ax = plt.subplots(figsize=(8, 3.2))
im = ax.imshow(np.clip(db, DB_LO, 0), origin="lower", aspect="auto", cmap="magma", vmin=DB_LO, vmax=0,
extent=[t[0] - HOP / 2 / sr, t[-1] + HOP / 2 / sr, f[0], f[-1]])
ax.set_xlabel("time (s)"); ax.set_ylabel("Hz"); ax.set_title(f"spectrogram, Hann {WIN} hop {HOP}, 0-8 kHz", fontsize=9)
fig.colorbar(im, ax=ax, label="dB re clip peak")
fig.tight_layout(); save(fig, out / f"{wav.stem}.spec.png")
fig, ax = plt.subplots(figsize=(8, 2.4))
ax.plot(np.arange(len(x)) / sr, x, lw=0.5, color="black")
ax.set_ylim(-0.5, 0.5); ax.set_xlim(0, len(x) / sr); ax.set_xlabel("time (s)"); ax.set_ylabel("amplitude (full scale 1.0)")
ax.set_title("waveform, fixed range +-0.5", fontsize=9); ax.grid(alpha=0.3)
fig.tight_layout(); save(fig, out / f"{wav.stem}.wave.png")
PLOSIVE_IPA = set("pbtdkgɡcɟqɢʔ")
def plosives(script):
"""(start, dur) of every plosive phoneme_gesture in a render's script.aqua (WordRender writes ipa=, no descriptor)."""
out = []
for line in script.read_text(encoding="utf-8").splitlines():
if line.startswith("phoneme_gesture"):
kv = dict(p.split("=", 1) for p in line.split()[1:] if "=" in p)
if kv.get("ipa") in PLOSIVE_IPA: out.append((float(kv["start"]), float(kv["dur"])))
return out
def burst_note(root, stem):
"""Notes for one render stem: the with-minus-without difference of out/<stem> and outnb/<stem>, per plosive."""
script = root / "out" / stem / "script.aqua"
if not script.exists():
return {"burst": "not measured: no render of this word under out/"}
ps = plosives(script)
if not ps:
return {"burst": "none: the word has no plosive"}
twin = root / "outnb" / stem / f"{stem}.wav"
if not twin.exists():
return {"burst": "not measured: no --no-burst twin render of this word"}
a, sr = read_wav(root / "out" / stem / f"{stem}.wav")
b, _ = read_wav(twin)
n = min(len(a), len(b)); d = np.abs(a[:n] - b[:n])
rows = []
for start, dur in ps:
lo, hi = int(start * sr), min(n, int((start + dur + 0.12) * sr))
peak = d[lo:hi].max() if hi > lo else 0.0
hot = np.flatnonzero(d[lo:hi] > peak / 20) + lo if peak > 0 else np.array([], dtype=int)
if not len(hot):
rows.append({"closure_start_s": start, "release_s": None, "burst_end_s": None, "look_s": None, "note": "no difference between the renders"})
continue
end = hot[0]
for i in hot[1:]: # the first burst: stop at a gap over 5 ms
if i - end > 0.005 * sr: break
end = i
rel, fin = hot[0] / sr, end / sr
rows.append({"closure_start_s": round(start, 4), "release_s": round(rel, 4), "burst_end_s": round(fin, 4),
"difference_peak": round(float(peak), 4), "look_s": [round(max(0.0, rel - 0.03), 4), round(fin + 0.05, 4)]})
return {"burst": rows}
def render_of(root, clip):
"""The out/<w> render a clip file was copied from (byte-identical wav), or None: two clip ids can be one render."""
data = clip.read_bytes() if clip.exists() else None
for d in sorted((root / "out").glob("*/")):
w = d / f"{d.name}.wav"
if data is not None and w.exists() and w.read_bytes() == data: return d.name
return None
def notes(kit, root, clips):
out = []
for c in kit["clips"]:
stem = Path(c["file"]).stem
if stem.endswith("_noburst"):
out.append({"id": c["id"], "file": c["file"], "word": stem[:-8], "burst": "no burst expected"}); continue
word = render_of(root, clips / c["file"]) or stem
out.append({"id": c["id"], "file": c["file"], "word": word, **burst_note(root, word)})
return out
def notes_md(rows):
lines = ["# Burst notes", "", "Times in seconds from the clip start. Release = start of the with-minus-without difference above 1/20 of its peak. Look in the spectrogram at 2-8 kHz inside the window.", ""]
lines += ["| clip id | file | closure start | release | burst end | look in |", "|---|---|---|---|---|---|"]
for r in rows:
if isinstance(r["burst"], str):
lines.append(f"| {r['id']} | {r['file']} | {r['burst']} | | | |"); continue
for p in r["burst"]:
look = f"{p['look_s'][0]} to {p['look_s'][1]}" if p.get("look_s") else p.get("note", "")
lines.append(f"| {r['id']} | {r['file']} | {p['closure_start_s']} | {p['release_s']} | {p['burst_end_s']} | {look} |")
return "\n".join(lines) + "\n"
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("clips"); ap.add_argument("images"); ap.add_argument("--kit"); ap.add_argument("--renders")
a = ap.parse_args()
clips, out = Path(a.clips), Path(a.images)
if bool(a.kit) != bool(a.renders): ap.error("--kit and --renders go together")
wavs = sorted(clips.glob("*.wav"))
if not wavs: sys.exit(f"no .wav files in {clips}")
out.mkdir(parents=True, exist_ok=True)
for w in wavs: images(w, out)
print(f"{len(wavs)} clips, {2 * len(wavs)} images in {out}")
if a.kit:
rows = notes(json.loads(Path(a.kit).read_text(encoding="utf-8")), Path(a.renders), clips)
(out.parent / "burst-notes.json").write_text(json.dumps(rows, indent=1) + "\n", encoding="utf-8")
(out.parent / "burst-notes.md").write_text(notes_md(rows), encoding="utf-8")
print(f"burst notes for {len(rows)} clips in {out.parent}")
if __name__ == "__main__":
main()

View file

@ -0,0 +1,78 @@
{
"kit": {
"id": "tract-stops-1",
"title": "Articulatory vocal tract: stops and the lateral",
"note": "Short synthetic words from the tract model. Tell us what you hear; there are no wrong answers. Some are pairs: rate both, then say which you prefer."
},
"clips": [
{
"id": "stop-t",
"file": "ata.wav",
"group": "stop",
"title": "/ɑtɑ/ at 140 Hz. Measured: closure -24.9 dB re the flanking vowels (/p/ -20.4), burst peak 0.39 of the vowel peak, burst spectral peak 3950 Hz (inside 3.5-7 kHz; CW14 5216), burst only around its own release. PREDICTION: heard as 'ah-tah', a crisp tongue-tip tap-and-release with a sharp click on the release; the twin without the burst loses that click and sounds softer, like a stop with no edge. FALSIFIED if heard as 'ah-kah' or 'ah-pah', or if the burst is not audible against the no-burst twin.",
"feel": "'ah-tah': the tongue tip taps behind the teeth between two open vowels",
"pair": "stop-t-noburst"
},
{
"id": "stop-t-noburst",
"file": "ata_noburst.wav",
"group": "stop",
"title": "/ɑtɑ/ rendered with --no-burst (plosive release_flow splines dropped), otherwise the same word. Measured: no burst energy by construction (the release_flow splines are dropped); closure and transitions as in the burst render. PREDICTION: still a stop by closure and formant transitions, but soft, with no click at the release. FALSIFIED if it sounds the same as the burst twin.",
"feel": "the same word with a gentler, softer release",
"pair": "stop-t"
},
{
"id": "stop-d",
"file": "ada.wav",
"group": "stop",
"title": "/ɑdɑ/ at 140 Hz. Measured: voice bar -28.9 dB re the following vowel (/t/ -38.7, /b/ -29.2, /p/ -40.1), burst spectral peak 3950 Hz, same as /t/ (CW14 d 4878), burst peak 0.0603 at the release and none before or after; the 7 consonant splines are identical to /t/'s. PREDICTION: 'ah-dah': a tongue-tip stop with voicing through the closure, a softer release than /t/. FALSIFIED if heard as /t/ or /n/ or /l/, or if no voicing is audible in the closure.",
"feel": "'ah-dah': the tongue tip taps behind the teeth, with the voice kept humming",
"pair": "stop-d-noburst"
},
{
"id": "stop-d-noburst",
"file": "ada_noburst.wav",
"group": "stop",
"title": "/ɑdɑ/ rendered with --no-burst, otherwise the same word. Measured: voice bar unchanged at the closure; no burst energy. PREDICTION: the voice bar still marks a stop, but the release is smooth. FALSIFIED if it sounds the same as the burst twin.",
"feel": "the same word with a gentler, softer release",
"pair": "stop-d"
},
{
"id": "stop-k",
"file": "aka.wav",
"group": "stop",
"title": "/ɑkɑ/ at 140 Hz. Measured: burst peak 0.45 of the vowel peak, burst spectral peak 3100 Hz (Chodroff and Wilson 2014: 2868 Hz; /t/ 3950 Hz by the same measure), burst only at its own release; closure -14.9 dB re vowels against /p/ -20.4, so the closure is NOT at or under /p/ (the voicing the voiceless source still carries leaks through it). PREDICTION: 'ah-kah', a back-of-the-tongue stop with a duller, lower burst than /t/; the closure is audibly less empty than in /apa/. FALSIFIED if heard as /t/ or /p/, or if the closure carries a clear hum that makes it sound like /g/.",
"feel": "'ah-kah': the back of the tongue lifts to the roof of the mouth between two open vowels",
"pair": "stop-k-noburst"
},
{
"id": "stop-k-noburst",
"file": "aka_noburst.wav",
"group": "stop",
"title": "/ɑkɑ/ rendered with --no-burst, otherwise the same word. Measured: no burst energy; closure unchanged from the burst render. PREDICTION: a softer, less distinct stop whose place is carried by the transitions alone. FALSIFIED if it sounds the same as the burst twin, or if the place is lost altogether.",
"feel": "the same word with a gentler, softer release",
"pair": "stop-k"
},
{
"id": "stop-l",
"file": "ala.wav",
"group": "lateral",
"title": "/ɑlɑ/ at 140 Hz, a lateral with a closed side stub (midline narrowed to 0.06 cm, not closed: the ladder cannot hold parallel side channels). Measured: level -5.0 dB re the flanking vowels, F1 263 Hz (design 250-400: met), F2 725 Hz (design 1000-1300: NOT MET, F2 is about 300 Hz too low), side stub notch 13.4 dB at 2.8 kHz against the same render with the stub shut, no burst. PREDICTION: heard as a liquid between the vowels, possibly dark ('ahl-ah' as in a dark /l/) because F2 is low; may be heard as a nasal or /w/ rather than /l/. FALSIFIED if heard as a plain vowel glide with no consonant, or as a stop.",
"feel": "'ah-lah': the tongue tip touches behind the teeth while the sound flows past the sides"
},
{
"id": "stop-p",
"file": "apa.wav",
"group": "stop",
"title": "/ɑpɑ/ at 140 Hz, the labial reference. Measured: closure -20.4 dB re the flanking vowels (-19.9 in the burst-site probe), burst enters at the glottal end (pinned labial burst), /p/ voice bar -40.1 dB. PREDICTION: 'ah-pah', a lip stop; the reference against which /t/ and /k/ are judged. FALSIFIED if heard as /b/ (voiced), or if the lip closure sounds leaky.",
"feel": "'ah-pah': the lips close and pop open between two open vowels"
},
{
"id": "stop-b",
"file": "aba.wav",
"group": "stop",
"title": "/ɑbɑ/ at 140 Hz, the voiced labial reference. Measured: voice bar -29.2 dB re the following vowel (/p/ -40.1). PREDICTION: 'ah-bah', lips close with voicing kept through the closure; softer than /p/. FALSIFIED if heard as /p/ or as /m/.",
"feel": "'ah-bah': the lips close and open with the voice humming"
}
]
}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑbɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "b", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑdɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "d", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑkɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "k", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑlɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "l", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑpɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "p", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑtɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "t", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1,22 @@
#!/bin/bash
# Renders the tract-stops kit (WordRender, 140 Hz, 48 kHz mono 16-bit): /apa aba ata ada aka ala/ (the vowel is /ɑ/) and the
# --no-burst twins of ata ada aka, whose release_flow splines are dropped so a pair isolates the burst.
# render.sh <repo-root> <out-root> [jobs]
# Needs CULTLIB_ROOT at the admitted CultLib revision and AQUASYNTH_FAUST_HOME. Under load each render is minutes (a Faust compile).
# <out-root>/out/<w>/<w>.wav <out-root>/outnb/<w>/<w>.wav (--no-burst) <out-root>/clips/*.wav the files kit.json names
# <out-root>/images, burst-notes.* clip_images.py: PNGs per clip and the burst times (needs numpy + matplotlib: PYTHON=<python with both>)
# Build the page: node tools/aqua-listen/build.mjs --manifest tools/aqua-listen/kits/tract-stops/kit.json --clips <out-root>/clips --out <out-root>/dist [--images <out-root>/images]
set -eu
REPO=$(cd "$1" && pwd); OUT=$2; JOBS=${3:-4}; HERE=$REPO/tools/aqua-listen/kits/tract-stops
dotnet build "$REPO/tools/WordRender" -c Release -v q -o "$OUT/wr" | grep -E "rror\(s\)"
mkdir -p "$OUT/out" "$OUT/outnb" "$OUT/clips"
job() { n=$1; o=$2; f=$3; shift 3; dotnet "$OUT/wr/WordRender.dll" "$OUT/$o/$n" "$n" "$f" "$HERE/phones/$n.json" "$@" > "$OUT/$o/$n.log" 2>&1 && echo "$n $o ok" || echo "$n $o FAILED (see $OUT/$o/$n.log)"; }
export -f job; export OUT HERE
{
for n in ata ada aka ala apa aba; do echo "$n out 140"; done
for n in ata ada aka apa aba; do echo "$n outnb 140 --no-burst"; done # apa aba twins feed the burst notes only, no clip
} | xargs -P "$JOBS" -L1 bash -c 'job "$@"' _
C=$OUT/clips
for n in ata ada aka ala apa aba; do cp "$OUT/out/$n/$n.wav" "$C/$n.wav"; done
for n in ata ada aka; do cp "$OUT/outnb/$n/$n.wav" "$C/${n}_noburst.wav"; done
${PYTHON:-python3} -I "$REPO/tools/aqua-listen/clip_images.py" "$C" "$OUT/images" --kit "$HERE/kit.json" --renders "$OUT"

View file

@ -0,0 +1,117 @@
{
"kit": {
"id": "tract-weak-spots-1",
"title": "Articulatory vocal tract: stress, release, nasals, lax vowels",
"note": "Short synthetic words from the tract model. Tell us what you hear; there are no wrong answers. Some are pairs: rate both, then say which you prefer."
},
"clips": [
{
"id": "stress-nibu-flat",
"file": "nibu_flat.wav",
"group": "stress",
"pair": "stress-nibu",
"title": "nibu, no stress marks. Measured: /i/ 150-250 ms rms vs the stressed render +0.21 dB; unstressed vowel 180 ms, f0 139.9 Hz. PREDICTION: reads as an even two-syllable word with no strong first syllable. FALSIFIED if listeners hear it as stressed on a syllable or cannot tell it from the stressed twin.",
"feel": "a made-up two-syllable word, 'nee-boo', both syllables even"
},
{
"id": "stress-nibu",
"file": "nibu.wav",
"group": "stress",
"pair": "stress-nibu-flat",
"title": "nibu with primary stress on /i/ (NI-bu). Measured: /i/ 247 ms vs 180 ms (+75 ms; design +68), f0 148.1 vs 139.9 Hz (x1.059), amplitude factor 1.30; level of /i/ in the 150-250 ms window only +0.21 dB (five-vowel mean +1.93 dB, per vowel +1.2 to +3.0). PREDICTION: first syllable heard as the prominent one, mostly through length and pitch, little through loudness; B should be picked as 'stressed on the first syllable'. FALSIFIED if it sounds no more prominent than the flat twin, if it sounds like a question or a pitch accent rather than stress, or if the level is what is heard (then the f0-scatter question is wrong).",
"feel": "the same made-up word, with the first syllable stronger: 'NEE-boo'"
},
{
"id": "stress-i-flat",
"file": "v_i.wav",
"group": "stress",
"pair": "stress-i",
"title": "isolated /i/ 180 ms at 140 Hz, no stress. Measured: level 100-170 ms is the reference. PREDICTION: plain short vowel. FALSIFIED if it already sounds emphasised.",
"feel": "a single short 'ee' vowel, plain"
},
{
"id": "stress-i",
"file": "v_i_s.wav",
"group": "stress",
"pair": "stress-i-flat",
"title": "isolated /i/ with primary stress: 247 ms, f0 x1.06, amplitude 1.30. Measured against the flat /i/: +1.22 dB total (f0 rise alone -0.80 dB, the amplitude and the rest +2.02 dB). PREDICTION: heard as longer and a little higher; the 1.2 dB louder is under what a listener can judge, so 'longer and higher' is the answer, 'louder' is not. FALSIFIED if it sounds the same length and pitch, or clearly louder.",
"feel": "the same 'ee' vowel, held longer and said with emphasis"
},
{
"id": "leak-nibu-flat-before",
"file": "nibu_flat_before.wav",
"group": "release-leak",
"pair": "leak-nibu-flat-after",
"title": "nibu (flat) rendered at main c0e6b98, before the release_flow fix. Measured: burst-gain leak vs the fixed render, peak 0.0688 and rms 0.0067 in the leading /n/ (0-95 ms; the /n/ itself is rms 0.0058, so the hiss is louder than the murmur), peak 0.0504 over /i/ onset 95-150 ms, 0.0019 after; whole-render peak 0.487 vs 0.399. PREDICTION: an audible hiss or click as the /n/ opens into the vowel, the first sound of the word being a noisy 'sn'-like or 'tsh' onset instead of a clean nasal hum. FALSIFIED if the two are indistinguishable (then the leak is inaudible and the fix is cosmetic).",
"feel": "a made-up word that should start with a clean, smooth hum into the vowel: 'nee-boo'"
},
{
"id": "leak-nibu-flat-after",
"file": "nibu_flat_after.wav",
"group": "release-leak",
"pair": "leak-nibu-flat-before",
"title": "nibu (flat) after the fix: release_flow is zero outside its own plosive. Same audio as stress-nibu-flat, kept as its own clip so the before/after pair is one-to-one. Measured: leak 0.0 from 275 ms on, burst of the b itself unchanged (bin 0.0226 at 81 ms before and after). PREDICTION: clean hum into the vowel, no noisy onset; preferred over 'before' if the leak is audible. FALSIFIED if 'before' is preferred or no difference is heard.",
"feel": "a made-up word that should start with a clean, smooth hum into the vowel: 'nee-boo'"
},
{
"id": "burst-ba-off",
"file": "ba_noburst.wav",
"group": "burst",
"pair": "burst-ba-on",
"title": "ba with the release_flow splines dropped (WordRender --no-burst). Measured: closure peak 0.0078 (voice bar), release (voicing breaking through) peak 0.1087 = -6.3 dB re vowel peak 0.2247, no burst noise. PREDICTION: a soft, voiced 'b' with the vowel starting smoothly; may sound slightly 'w'-like or lack the pop. FALSIFIED if listeners cannot hear any difference from the burst twin (then burst gain 0.06 is inaudible).",
"feel": "the syllable 'bah' with a soft start"
},
{
"id": "burst-ba-on",
"file": "ba.wav",
"group": "burst",
"pair": "burst-ba-off",
"title": "ba with the plosive burst (gain 0.06, a design value). Measured: burst alone peaks 0.0142 at 85 ms = -24.0 dB re vowel peak, falls to a tenth in 17 ms, burst rms in the 30 ms after its peak -31.0 dB re vowel rms. PREDICTION: a slightly crisper, more 'b'-like onset than B/off; the burst is quiet and short so the difference is small, 'a little pop' at most. FALSIFIED if it sounds like a hiss, a click, or a separate noise after the vowel started, or if no difference is heard.",
"feel": "the syllable 'bah' with a clean, crisp 'b' at the start"
},
{
"id": "burst-bun-off",
"file": "bun_noburst.wav",
"group": "burst",
"pair": "burst-bun-on",
"title": "bun, /bʊn/, no burst. Measured: closure peak 0.0043, release peak 0.1074 = -5.9 dB re vowel peak 0.2126. PREDICTION: soft 'b' then a short back vowel then a nasal; the final /n/ is a clean hum (no leak since the fix). FALSIFIED as for burst-ba-off.",
"feel": "a short word like 'bunn' or 'boon' said quickly, soft start"
},
{
"id": "burst-bun-on",
"file": "bun.wav",
"group": "burst",
"pair": "burst-bun-off",
"title": "bun, /bʊn/, with burst. Measured: burst peak 0.0130 at 81 ms = -24.3 dB re vowel peak, tenth in 15 ms; tail leak after the fix 0.0 (was 0.0126 at the end before). PREDICTION: slightly crisper onset than off; final /n/ clean. FALSIFIED as for burst-ba-on.",
"feel": "a short word like 'bunn' or 'boon' said quickly, crisp 'b' start"
},
{
"id": "nasal-m",
"file": "ama.wav",
"group": "nasal",
"title": "/ɑmɑ/. Measured: murmur -11.81 dB re the flanking vowels (design band -16..-8), Burg N1 295 Hz, band levels 0-400/400-800/800-1600/1600-3200 Hz of the murmur 36.3/23.6/21.3/2.7 dB. PREDICTION: heard as 'ah-mah', a lip-closed hum between the vowels, clearly softer than the vowels. FALSIFIED if heard as 'abah' or 'awah', if the hum is as loud as the vowels, or if there is a gap or click.",
"feel": "'ah-mah': lips close for a soft hum between two open vowels"
},
{
"id": "nasal-n",
"file": "ana.wav",
"group": "nasal",
"title": "/ɑnɑ/. Measured: murmur -9.64 dB re the flanking vowels (2.17 dB above /m/; the gap is 2.01/2.17/2.05/1.61 dB at f0 110/140/170/200 Hz, so not harmonic sampling), Burg N1 332 Hz, bands 38.4/28.2/16.8/0.9 dB. PREDICTION: heard as 'ah-nah', a tongue-tip hum, a shade stronger than the /m/ one; the 2 dB is not expected to be noticed. FALSIFIED if heard as 'ama' or 'anga', if it sounds much louder than the /m/ clip, or if there is hiss.",
"feel": "'ah-nah': the tongue touches behind the teeth for a soft hum between two open vowels"
},
{
"id": "lax-ih",
"file": "v_ih.wav",
"group": "lax",
"title": "isolated /ɪ/ 180 ms, 140 Hz. Measured: Burg F1/F2 375/2024 Hz; tube chain 346/1987 (+8.5/+1.8 %); Hillenbrand 1995 male 429/2034 (-12.5/-0.5 %); Peterson & Barney 392/1993 (-4.3/+1.5 %). Present in the DSL table and renderable. PREDICTION: heard as the vowel of 'bit' (or a slightly high, 'ee'-leaning version of it). FALSIFIED if heard as 'ee' of 'beet', as 'eh' of 'bet', or as a different phone.",
"feel": "the short vowel in 'bit'"
},
{
"id": "lax-oo-short",
"file": "v_oo_short.wav",
"group": "lax",
"title": "isolated /ʊ/ 180 ms, 140 Hz. Measured: Burg F1/F2 486/894 Hz; tube chain 478/850 (+1.7/+5.2 %); Hillenbrand 469/1123 (+3.7/-20.4 %); Peterson & Barney 437/1023 (+11.3/-12.6 %). Present in the DSL table and renderable. PREDICTION: heard as the vowel of 'book', probably darker or rounder than a natural one (F2 20 % under the population mean, the back-vowel gap). FALSIFIED if heard as 'oo' of 'boot', 'o' of 'boat' or 'uh' of 'but'.",
"feel": "the short vowel in 'book'"
}
]
}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑmɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "m", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑnɑ", "phones": [{"ipa": "ɑ", "stress": "none"}, {"ipa": "n", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ba", "phones": [{"ipa": "b", "stress": "none"}, {"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "bɪn", "phones": [{"ipa": "b", "stress": "none"}, {"ipa": "ɪ", "stress": "primary"}, {"ipa": "n", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "bʊn", "phones": [{"ipa": "b", "stress": "none"}, {"ipa": "ʊ", "stress": "primary"}, {"ipa": "n", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ˈnibu", "phones": [{"ipa": "n", "stress": "none"}, {"ipa": "i", "stress": "primary"}, {"ipa": "b", "stress": "none"}, {"ipa": "u", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ˈnibu", "phones": [{"ipa": "n", "stress": "none"}, {"ipa": "i", "stress": "none"}, {"ipa": "b", "stress": "none"}, {"ipa": "u", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ɑ", "phones": [{"ipa": "ɑ", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ˈɑ", "phones": [{"ipa": "ɑ", "stress": "primary"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "e", "phones": [{"ipa": "e", "stress": "none"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "ˈe", "phones": [{"ipa": "e", "stress": "primary"}]}

View file

@ -0,0 +1 @@
{"language": "en-US", "source": "i", "phones": [{"ipa": "i", "stress": "none"}]}

Some files were not shown because too many files have changed in this diff Show more