Compare commits

..
95 changed files with 291 additions and 3610 deletions

View file

@ -1,7 +1,5 @@
# 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` =
@ -33,15 +31,15 @@ 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
- Where: `src/AquaSynth.Dings/DingCatalog.cs:22-28` (four instruments), built by the
private `Instrument(...)` at `:48-50`, 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.
`muted-pluck`), case-insensitive dictionary (`:28`). Events are a separate keyed
dictionary (`:9-20`, 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`,
- Writer: whoever edits the file. `ValidateCuration` (`:31-46`) is the only gate.
- Readers: `Host/DingsPlaybackHost.cs:66-67`, `Mcp/DingService.cs:9-10`,
`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
@ -49,15 +47,12 @@ code. The grouping above follows who writes the key.
## 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.
The Host does not pass the catalog id through. It builds the daemon's identity fields
itself, 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"]`.
- `Host/AquaDaemonClient.cs:20` per note: `patchId = "dings." + instrument.Id`,
`faustName = "dings_" + instrument.Id.Replace('-', '_')`, `revision = 1` (a literal),
`durationSeconds = 1.5f`, `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
@ -89,14 +84,13 @@ builds more keys from them.
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`.)
- The `dings_<id>` rule is written three times: `AquaDaemonClient.cs:20` and
`tools/AquaLower/Program.cs:19`, and
`DingCatalogTests.cs:45` (`LoweredDingsFedToTheFeelMeterMatchTheCatalog` builds the
name with the same expression). Nothing ties the three together except the test.
- 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
- `Host/AquaDaemonClient.cs:23-28` returns the WAV path from the receipt. The Host
never asks the daemon which patch rendered it.
## C. MCP `AgentInstrumentRegistry`
@ -116,11 +110,10 @@ builds more keys from them.
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`.
- Also decides: `DingService.PlayAsync` (`Mcp/DingService.cs:9-11`) re-validates event,
instrument and gain, and the Host validates the same three again
(`DingsPlaybackHost.cs:66-68`). Two gates on one decision; they agree today because
both read `DingCatalog`.
## D. `tools/dings-voices` sender voices
@ -150,7 +143,7 @@ builds more keys from them.
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` |
| id | catalog root / decay (`DingCatalog.cs:24-27`) | workshop `rootHz` / `decay` |
|---|---|---|
| warm-bell | 261.6256 / 1.15 | 261.6256 / 0.55 |
| glass-chime | 261.6256 / 0.85 | 329.6276 / 0.45 |
@ -184,14 +177,12 @@ builds more keys from them.
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.
5. **Derivation written three times.** `dings_<id>` in `AquaDaemonClient.cs:20`,
`AquaLower/Program.cs:19`, and the test; and the `dings.<id>` patch id appears in
`StoreFileNameTests` as a literal. A rename rule changed in one place breaks
store-file naming in another without a compile error.
6. **Double validation.** `DingService.cs:9-11` and `DingsPlaybackHost.cs:66-68` each
decide whether an id is valid. Safe while both read one dictionary.
## The Host pipe protocol, as read from source
@ -252,7 +243,7 @@ response `Version` (`:46`). Connect timeout 350 ms; on `TimeoutException` or
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`).
by `DingService.EnsureSuccess` (`DingService.cs:22-26`).
**MCP side, for completeness.** Tools (`Mcp/DingTools.cs`): `play_ding`,
`get_agent_instrument`, `claim_instrument`, `list_ding_events`, `list_instruments`,
@ -268,22 +259,18 @@ user. Any process of that user can send `Play`. There is no per-caller identity
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)
## PROPOSED: one owner (a recommendation for the stewarding decision, not decided)
**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
the daemon (`AquaLower` and the test need 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
the catalog function. `AquaLower/Program.cs:19` and `DingCatalogTests.cs:45` call only the faust-name slice of 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
@ -303,15 +290,32 @@ End state versus this change: the content revision named above is deferred (step
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).
**Migration order** (each step independent and reversible):
1. Add the catalog function; switch `AquaDaemonClient.cs:20` and `AquaLower` onto it;
delete the test's private copy (see the oracle risk below). Pure refactor while
`revision` stays the literal 1: the compile key, and so the session id, stay equal
for unchanged scripts, which is checkable by comparing receipts before and after.
2. Decide the agent-identity question (below); change the registry key. Wire-visible:
existing sessions lose their hashed assignment.
3. Content revision: DEFERRED, not scheduled here. Replacing the literal `revision = 1`
with a catalog hash changes every compile key and session id (and the
`sessions/<...>.cc` file names), so it breaks step 1's equality check by design. It
needs its own decision on what feeds the hash and whether old session files are
left or removed.
4. Remove the duplicate gates in `DingService.cs:9-11` or have the Host's gate be the
single one (the bridge then only forwards). Keep whichever side the tests
(`DingsBridgeTests`) need for fail-fast, but one of them must be the owner.
5. Point the neutral fallback and Earcon Workshop at the catalog.
**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.
- Oracle loss in step 1: deleting the test's private `"dings_" + id` copy makes
`LoweredDingsFedToTheFeelMeterMatchTheCatalog` compare the shared function against
itself. The test should keep an independent expected value (a literal per instrument
or the checked-in `.dsp` header) so a wrong rule still fails.
- 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
@ -334,24 +338,3 @@ what the MCP bridge can learn about its caller.
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

@ -1,76 +0,0 @@
# 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

@ -1,231 +0,0 @@
{
"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

@ -1,32 +0,0 @@
# 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

@ -125,43 +125,11 @@ 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`), 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.
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.
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
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
(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,20 +12,25 @@ 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`: 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.
- `heimdall-body:follow_up:ratatoskr-creature-projection-v2`: `huginn view`
from instance `aqua` still answers `absent` (re-checked 2026-11-02; `absent` from Eureka's mind on 2026-11-05), and a
search of the Heimdall checkout found no file mentioning it. Section 2 takes
its constraints as relayed in `aqua-body:follow_up:chat-s946-948`: rule O1
(a Neutral participant gets no orbit and no voice), the `estate` split,
coarse size buckets with a separate neutral flag, activity fed by the
Heimdall session. Section 2 must be reconciled against that follow-up's
actual field list once it can be read.
- `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.
Context actually read: `docs/gamecult/ratatoskr-target.md` in `GameCult/Ratatoskr`
at `b33d8de` (the agreement that one activity vocabulary drives both sound and
@ -53,22 +58,15 @@ cannot read it plays nothing and draws nothing.
| field | type | values | note |
|---|---|---|---|
| `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) |
| `mind` | id | participant identity | stable identity, not a run/session label; for a human, the member's stable id |
| `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 |
`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).
| `kind` | enum, 7 (humans: 3) | `Idle`, `Reading`, `Thinking`, `Working`, `Speaking`, `Waiting`, `Alert` | coarse; absent when `neutral`; see below |
| `energy` | enum, 4 (humans: 3) | `Low`, `Mid`, `High`, `Peak` | coarse bucket of rate/intensity, never a float; absent when `neutral`; see below |
| `size` | 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; when set, `kind`, `energy` and `size` are all omitted, see O1 |
| `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, 2 | `None`, `Muted` | see rules O2, O3; Neutral is the `neutral` flag, not an override value |
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
@ -92,37 +90,30 @@ the other fields may carry (per
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.
Reconcile the subset against the projection-v2 field list.
- **`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.
`size` is three coarse buckets (`Small`, `Medium`, `Large`) for every estate
except a `neutral` participant, whose frame omits it (O1).
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.
Rules:
- **A1. Source.** The frame comes from the Heimdall session and only from it.
Neither consumer infers activity from Matrix presence, typing, message
traffic, audio, or the room member list. Activity is a stub fed by the Heimdall
traffic, audio, or room membership. 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).*
for Minds.) *Reconcile the exact kind list against the projection-v2
follow-up before use.*
- **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 `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,
- **A3. Member-safe.** The frame carries `mind`, `estate`, `kind`, `energy`,
`size`, `neutral`, `seq`, `at` and `override`, and nothing else; when
`neutral` is set, `kind`, `energy` and `size` are stripped (O1). 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`: no voice, and the orbit at rest. Silence is the default
@ -131,21 +122,20 @@ Rules:
### Overrides
- **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
- **O1. `neutral`** (the flag, set by the session or by the member's own
setting): a Neutral participant gets **no orbit and no voice**, and the
frame **strips `kind`, `energy` and `size` as well**: the producer omits all
three, 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
"neutral pose" to render. Neutral overrides every `size` bucket: none is drawn or carried. 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.
- **O2. `Muted`**: no voice, orbit unchanged. Lets a listener silence one Mind
without hiding its motion.
- **O3.** `neutral` and `override` 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.)
## 3. Mapping tables (shape only)
@ -157,20 +147,20 @@ when values exist.
|---|---|---|---|
| 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 |
| creature scale | orbit renderer | `sizeBucket` | per-bucket scales are renderer placeholders, not fixed here |
| creature scale | orbit renderer | `size` | 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 | `id` | never `kind`; section 4 |
| voice **identity** (which instrument) | voice scheduler | `mind` | never `kind`; section 4 |
The one rule that ties the two consumers: **`id` selects identity, `kind`
The one rule that ties the two consumers: **`mind` 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; the Mimir harvest gives it no support or contradiction, see 4.1): voices that share a niche in
(recalled, to be confirmed by the Mimir harvest): 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
@ -191,7 +181,7 @@ niches. Axes:
Rules:
- **V1. Identity is stable.** The niche (axes 1-4) is a function of `id`
- **V1. Identity is stable.** The niche (axes 1-4) is a function of `mind`
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
@ -212,66 +202,6 @@ 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
@ -279,7 +209,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 `id` into a preallocated table; the scheduler thread reads
latest frame per `mind` 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
@ -287,9 +217,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 `id`, only the newest frame by the feed envelope's ordering matters (the frame itself carries none; see section 2). Intermediate
- **S1. Latest wins.** Per `mind`, only the newest `seq` matters. Intermediate
frames missed during a stall are not replayed.
- **S2. Staleness.** A frame whose envelope age exceeds **10 s** (*proposed*) is treated as
- **S2. Staleness.** A frame older than **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
@ -321,8 +251,10 @@ allocation, or a lock.
None run. To be done before the grammar leaves draft:
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.
1. Reconcile section 2 with `heimdall-body:follow_up:ratatoskr-creature-projection-v2`
(field list, the human `kind` subset in section 2, the size and neutral fields,
the stripping of `kind`, `energy` and `size` under `neutral`).
2. Reconcile section 4 with the Mimir harvest.
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.
@ -330,5 +262,5 @@ None run. To be done before the grammar leaves draft:
## 8. Status
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
Draft. Not implemented. No code changed. No audio was produced and none is
claimed.

View file

@ -30,13 +30,6 @@ 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) =>
@ -54,7 +47,6 @@ 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)
@ -96,15 +88,6 @@ 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)
@ -130,12 +113,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")}{Injected(0)}) * {loss};");
: $" '{member.R(0)} = ({member.L(0)} * {F(LadderGlottalReflection)} + {(inputs.TryGetValue(member.Path.Name, out var input) ? input : "0.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)}){Injected(i)}) * {loss};");
: $" '{member.R(i)} = ({member.R(i - 1)} - {member.Refl(i)} * ({member.R(i - 1)} + {member.L(i)})) * {loss};");
}
for (var i = 0; i < last; i++)

View file

@ -45,15 +45,6 @@ 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));");
@ -161,7 +152,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) : smoo_init";
var publicControl = $"hslider(\"{Escape(surface.Path)}\", {F(surface.DefaultNormalized)}, 0, 1, 0.001) : si.smoo";
var boundControl = parameters.TryBindingExpression(surface.FieldPath, out var bindingExpression)
? $"clip01(({bindingExpression} - {F(surface.MinValue)}) / max(0.000001, {F(surface.MaxValue - surface.MinValue)}))"
: publicControl;
@ -181,7 +172,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) : smoo_init;");
source.AppendLine($"{depth} = hslider(\"/splines/{Escape(spline.Name)}/depth\", 1, 0, 1, 0.001) : si.smoo;");
terms.Add($"(({splineId}_value - {F(surface.DefaultNormalized)}) * {depth})");
}
@ -206,11 +197,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) : smoo_init;");
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}_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) : smoo_init;");
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}_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) : smoo_init;");
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;");
}
if (points.Length == 1)
@ -617,7 +608,6 @@ 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;
@ -628,24 +618,13 @@ public static partial class FaustEmitter
.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 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 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)
@ -671,7 +650,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, injections, admittances, parameters, warnings);
: EmitVocalLadder(source, patch, network, name, members, inputs, admittances, parameters, warnings);
foreach (var member in members)
{
@ -748,9 +727,7 @@ 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.
// 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 pitchRatio = $"({parameters.Expression(OwnerField(owner, "pitch_ratio"), port.PitchRatio)} : si.smooth(ba.tau2pole(0.01)))";
var load = $"{voiceName}_primitive_source_{safe}_load_pressure";
var voiced = $"{voiceName}_primitive_source_{safe}_voiced";
var flow = $"{voiceName}_primitive_source_{safe}_flow";
@ -758,22 +735,15 @@ 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))";
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)};");
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)};");
keepAlive.Add(load);
keepAlive.Add(voiced);
keepAlive.Add(flow);
return flow;
}
// 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(
private static string PrimitiveContactExpression(
StringBuilder source,
SynthPatch patch,
string voiceName,
@ -800,7 +770,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,33 +222,7 @@ public static class IpaGestureExperiment
start += duration;
}
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
""";
return Scaffold(lines, Math.Clamp(start + tailSeconds, 0.15f, 4f), frequency);
}
private static string GestureLine(IpaGestureExperimentTarget target, float start, float duration, float intensity) =>
@ -263,7 +237,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, bool sideStub = false) => $$"""
private static string Scaffold(IReadOnlyList<string> gestureLines, float sustain, float frequency) => $$"""
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}}
@ -276,9 +250,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
{{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
vocal_network name=voice paths=oral_path,nasal_path sources=folds contacts=contact branches=velopharynx radiation=mouth,nostril probe=flow
{{string.Join("\n", gestureLines)}}
vocal network=voice freq={{Format(frequency)}} gain=.7 attack=.012 sustain={{Format(sustain)}}
vocal network=voice freq={{Format(frequency)}} gain=.7 sustain={{Format(sustain)}}
""";
private static IReadOnlyList<IpaGestureMetricSummary> SummarizeMetrics(IReadOnlyList<IpaGestureExperimentMetric> metrics) =>

View file

@ -474,17 +474,7 @@ public sealed record SourcePort(
float Impedance = 0.35f,
float FlowScale = 0.02f,
float Tilt = 0.5f,
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
}
float PitchRatio = 1f);
public sealed record ConstrictionContact(
string Name,

View file

@ -8,26 +8,6 @@ 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.
@ -45,12 +25,8 @@ 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",
@ -63,11 +39,6 @@ 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();
@ -968,9 +939,7 @@ 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"),
ParseGlottalPulse(GetAny(fields, ["pulse", "glottal_pulse"], "saw"), line),
Math.Clamp(GetFloat(fields, line, 0f, "noise_highpass", "noise_hp"), 0f, 8000f));
GetBoundFloat(fields, line, 1f, $"/vocal/sources/{_sourcePorts.Count}/pitch_ratio", "pitch_ratio", "f0_ratio"));
_sourcePorts.Add(port);
_sourcePortsByName[name] = port;
RegisterSourcePortSurfaces(_sourcePorts.Count - 1, port);
@ -1512,58 +1481,11 @@ 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);
@ -1582,7 +1504,7 @@ public static class PatchScript
}
}
private void EmitPhonemeGestureSplines(string name, string descriptor, float start, float duration, float intensity, int line, float pitchRatio = 1f)
private void EmitPhonemeGestureSplines(string name, string descriptor, float start, float duration, float intensity, float pitchRatio = 1f)
{
var tokens = DescriptorTokens(descriptor);
var voiced = tokens.Contains("voiced") || tokens.Contains("vowel") || tokens.Contains("nasal") || tokens.Contains("approximant");
@ -1591,6 +1513,7 @@ 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));
@ -1604,18 +1527,17 @@ public static class PatchScript
if (tokens.Contains("vowel"))
{
EmitVowelGesture(name, descriptor, start, duration, line);
EmitVowelGesture(name, descriptor, start, duration);
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);
HoldOnSurface($"{name}_constriction_index", "/vocal/areas/0/area/constriction_index", start, duration, place * (sections - 1) / control.IndexScale);
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);
}
else
{
@ -1625,26 +1547,14 @@ 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 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)));
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)));
if (tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial") || tokens.Contains("rounded"))
{
// 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));
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));
}
if (tokens.Contains("nasal"))
@ -1654,19 +1564,11 @@ public static class PatchScript
}
else if (tokens.Contains("plosive") || tokens.Contains("stop"))
{
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));
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));
// 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). 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);
// it by the stored pressure and the opening (see PrimitiveContactExpression).
HoldOnSurface($"{name}_release_flow", "/vocal/contacts/0/release_flow", start, duration, PlosiveBurstGain);
AddAuthoredSpline($"{name}_velum", "/vocal/branches/0/opening", start, duration, (0, VelumClosed), (1, VelumClosed));
}
else if (tokens.Contains("fricative"))
@ -1679,25 +1581,13 @@ 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. 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)
// 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)
{
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)
{
@ -1737,62 +1627,6 @@ 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"], "");
@ -1827,79 +1661,40 @@ 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;
// 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)
// 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)
{
foreach (var place in Places)
{
if (place.Tokens.Any(tokens.Contains)) return place;
}
return null;
if (tokens.Contains("bilabial") || tokens.Contains("labiodental") || tokens.Contains("labial")) return 1;
if (tokens.Contains("alveolar")) return 1 - AlveolarRidgeCentimetersFromLips / lengthCentimeters;
return placeFraction;
}
internal static bool TryPlaceDistanceCentimeters(string descriptor, out float centimeters)
private static float PlaceTarget(HashSet<string> tokens)
{
centimeters = FindPlace(DescriptorTokens(descriptor))?.CentimetersFromLips ?? float.NaN;
return !float.IsNaN(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;
}
// 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;
@ -2889,17 +2684,12 @@ 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, line, pitchRatio);
EmitPhonemeGestureSplines(name, descriptor, start, duration, intensity, pitchRatio);
}
private void AddControlCurve(IReadOnlyDictionary<string, string> fields, int line)
@ -4445,13 +4235,6 @@ 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

@ -4,25 +4,8 @@ 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

@ -22,8 +22,7 @@ public sealed record FaustValidation(string Command, bool Success, int? StatusCo
public sealed record FaustWebAssemblyCompileOptions(
string OutputDirectory,
string BaseName = "aquasynth_patch",
bool Stereo = false,
int SampleRate = 48000);
bool Stereo = false);
public sealed record FaustWebAssemblyManifest(
string Name,
@ -90,7 +89,7 @@ public static class FaustCompiler
string? faustPath = null,
CancellationToken cancellationToken = default)
{
var export = FaustEmitter.Emit(patch, new FaustExportOptions(options.BaseName, options.Stereo, SampleRate: options.SampleRate));
var export = FaustEmitter.Emit(patch, new FaustExportOptions(options.BaseName, options.Stereo));
return await CompileWebAssemblySourceAsync(export.Source, options, faustPath, cancellationToken);
}
@ -100,7 +99,7 @@ public static class FaustCompiler
string? faustPath = null,
CancellationToken cancellationToken = default)
{
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(options.BaseName, options.Stereo, SampleRate: options.SampleRate));
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(options.BaseName, options.Stereo));
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", SampleRate: options.SampleRate)).Source;
return FaustEmitter.EmitScript(source.ToString(), new FaustExportOptions("aquasynth_speech_loss")).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 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 timeline = ProbeTimelineReport.Build(patch, "voice", Math.Max(1, options.TimelineBlocks));
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

@ -9,34 +9,6 @@ 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()
{
@ -62,30 +34,6 @@ 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]
@ -94,7 +42,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(PinnedFaustNames[instrument.Id])).Source;
var expected = FaustEmitter.EmitScript(instrument.Script, new FaustExportOptions("dings_" + instrument.Id.Replace('-', '_'))).Source;
Assert.Equal(expected, File.ReadAllText(Path.Combine(dir, instrument.Id + ".dsp")));
}
@ -112,18 +60,6 @@ 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,20 +31,6 @@ 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

@ -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, string extra = "") => $$"""
private static string Script(float tilt, float pitch) => $$"""
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}} {{extra}}
source_port name=folds path=oral_path pressure=.7 tension=.55 opening=.45 noise=0 impedance=.3 tilt={{tilt}}
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, string extra = "")
private float[]? Render(float tilt, float pitch = Pitch, int skip = 4800)
{
var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch, extra)), new FaustExportOptions("glottal_spectrum")).Source;
var source = FaustEmitter.Emit(PatchScript.Parse(Script(tilt, pitch)), 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,133 +122,4 @@ 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[^1].Value; // a held place: the last point is the gesture's value whether or not a boundary ramp precedes it
patch.ControlSplines.Single(spline => spline.Name.StartsWith(namePrefix, StringComparison.Ordinal) && spline.SurfacePath == surfacePath).Points[0].Value;
// 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,8 +91,7 @@ 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. 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/).
// The earlier surface semantics are kept for hand-written scripts: the place fraction is the normalized spline value itself.
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
@ -108,7 +107,7 @@ public sealed class NasalCouplingTests
vocal network=voice freq=150 gain=.2 sustain=.6
""");
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);
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"));
}
}

View file

@ -577,26 +577,6 @@ 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

@ -1,84 +0,0 @@
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

@ -1,143 +0,0 @@
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,14 +28,4 @@ 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

@ -1,183 +0,0 @@
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,24 +11,25 @@ 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);
@ -56,52 +57,52 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output)
return (double)Rate / bestLag;
}
[FaustFact]
[Fact]
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 F0(x, 0.2, 0.5);
return x is null ? double.NaN : 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);
}
[FaustFact]
[Fact]
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 Rms(x, 0.3, 0.5);
return x is null ? double.NaN : Rms(x, 0.3, 0.5);
}
var unity = Level(1f);
var amplitude = WeksaWordPlan.CueFor(WeksaStress.Primary).Amplitude;
var stressed = Level(amplitude);
var stressed = Level(1.26f);
if (double.IsNaN(unity)) return;
var db = 20 * Math.Log10(stressed / unity);
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);
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);
}
[FaustFact]
[Fact]
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 vowelFrom = 0.095;
var releaseFrom = ReleaseAt(0, vowelFrom);
const double releaseFrom = 0.095 * 0.65, vowelFrom = 0.095;
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);
@ -113,95 +114,12 @@ 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)");
}
// 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)], 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)
private (float[]? Samples, double From, double To) VowelConsonantVowel(string ipa, float frequency = 140)
{
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);
[(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);
}
// 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
@ -220,12 +138,13 @@ 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).
[FaustTheory]
[Theory]
[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);
@ -234,7 +153,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.
[FaustFact]
[Fact]
public void PrimaryStressRendersAboutTwoDecibelsLouderOnAverageOverVowels()
{
var cue = WeksaWordPlan.CueFor(WeksaStress.Primary);
@ -245,10 +164,11 @@ 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 Rms(x, 0.12, 0.22);
return x is null ? double.NaN : 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);
@ -270,368 +190,17 @@ 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.
[FaustTheory]
[Theory]
[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 (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);
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);
}
}
// 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

@ -68,77 +68,6 @@ 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()
{
@ -148,10 +77,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[^1].Value);
var ih = patch.ControlSplines.Where(s => s.Name.StartsWith("x_1_ɪ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[0].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[^1].Value);
var oo = patch.ControlSplines.Where(s => s.Name.StartsWith("x_4_ʊ_vowel_", StringComparison.Ordinal)).ToDictionary(s => s.SurfacePath, s => s.Points[0].Value);
Assert.Equal(1f, oo["/vocal/areas/0/area/vowel_oo_short"]);
Assert.Equal(0f, oo["/vocal/areas/0/area/vowel_u"]);
}
@ -190,7 +119,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[^1].Value;
p.ControlSplines.Single(sp => sp.Name.StartsWith(prefix, StringComparison.Ordinal) && sp.SurfacePath == surface).Points[0].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);
@ -206,7 +135,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[] { "ŋ", "θ", "ɹ" })
foreach (var ipa in new[] { "ŋ", "θ", "ɹ", "l" })
Assert.False(PatchScript.TryIpaDescriptor(ipa, out _));
}
}

View file

@ -16,8 +16,7 @@ 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))
{
// 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));
var export = FaustEmitter.EmitScript(ins.Script, new FaustExportOptions("dings_" + ins.Id.Replace('-', '_')));
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");
@ -43,7 +42,6 @@ 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,8 +17,7 @@ public sealed class AquaDaemonClient : IAsyncDisposable
{
EnsureStarted();
var id = $"ding-{Guid.NewGuid():N}";
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 } };
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 } };
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.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];
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.");
var playbackId = $"ding-{Guid.NewGuid():N}";
foreach (var note in dingEvent.Notes)
{

View file

@ -6,9 +6,6 @@ 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, challenge.SampleRate);
: ProbeTimelineReport.Build(patch, timelineNetwork.Name, 12);
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,17 +8,10 @@ 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> [--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)
// 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)
const int Rate = 48000, Frames = 512;
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; }
if (args.Length != 4) { Console.Error.WriteLine("usage: WordRender <outDir> <label> <freq-hz> <phones.json>"); return 2; }
var outDir = Path.GetFullPath(args[0]);
var label = args[1];
var freq = float.Parse(args[2], System.Globalization.CultureInfo.InvariantCulture);
@ -41,33 +34,6 @@ 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();
@ -75,13 +41,7 @@ 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.
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;
var source = FaustEmitter.Emit(PatchScript.Parse(script), new FaustExportOptions(label)).Source;
File.WriteAllText(Path.Combine(outDir, "source.dsp"), source);
if (!compiler.TryCompileSource(new AquaSynthCompileIdentity(label, label, ""), source, seconds, out var patch0, out var cerr))
{
@ -123,7 +83,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, 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,
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,
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

@ -1,18 +0,0 @@
#!/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

@ -16,8 +16,6 @@ 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,8 +16,6 @@ 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,8 +16,6 @@ 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,8 +16,6 @@ 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

@ -1 +0,0 @@
__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 your answers.
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.
**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.
**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.
## 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 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.
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.
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.
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.
## For the person building a kit
```
node build.mjs --manifest kit.json --clips ./clips --out ./dist # writes dist/listen.html
node test.mjs # 23 checks, no dependencies, no browser
node test.mjs # 16 checks, no dependencies, no browser
node smoke.mjs dist/listen.html # optional browser smoke, see below
```
@ -39,11 +39,10 @@ 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 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.
- 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.
- 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 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.
- 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.
### Export
@ -53,19 +52,8 @@ 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, 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.
`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.
## Files
`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`
`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,11 +1,10 @@
#!/usr/bin/env node
// Builds one self-contained listening page. Usage:
// 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.
// node build.mjs --manifest kit.json --clips DIR --out DIR (writes DIR/listen.html; --clips defaults to the manifest's folder)
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from "node:fs";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { basename, dirname, extname, join, resolve } from "node:path";
import { dirname, extname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
@ -13,7 +12,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, imagesDir) {
export function buildKit(manifest, clipsDir) {
const errs = L.validateManifest(manifest);
if (errs.length === 0) for (const c of manifest.clips) {
const f = resolve(clipsDir, c.file);
@ -28,20 +27,13 @@ export function buildKit(manifest, clipsDir, imagesDir) {
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, images }).replace(/</g, "\\u003c");
const data = JSON.stringify({ manifest, hash, audio }).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").replace("media-src blob:", () => Object.keys(images).length ? "media-src blob:; img-src data:" : "media-src blob:")
const html = part("index.html")
.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) };
@ -50,10 +42,10 @@ export function buildKit(manifest, clipsDir, imagesDir) {
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 [--images DIR]"); process.exit(2); }
if (!mf || !out) { console.error("usage: node build.mjs --manifest kit.json --clips DIR --out DIR"); process.exit(2); }
try {
const manifest = JSON.parse(readFileSync(mf, "utf8"));
const r = buildKit(manifest, resolve(opt("--clips") ?? dirname(resolve(mf))), opt("--images") && resolve(opt("--images")));
const r = buildKit(manifest, resolve(opt("--clips") ?? dirname(resolve(mf))));
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

@ -1,161 +0,0 @@
#!/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

@ -1,78 +0,0 @@
{
"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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,22 +0,0 @@
#!/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

@ -1,117 +0,0 @@
{
"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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,31 +0,0 @@
#!/bin/bash
# Renders the tract-weak-spots kit and the renders tools/formant-check/weak_spots.py measures (WordRender, 140 Hz, 48 kHz mono 16-bit).
# render.sh <repo-root> <out-root> [<pre-fix-repo-root>] [jobs]
# <pre-fix-repo-root> is a checkout of main c0e6b98 (before the release_flow fix); without it the leak-nibu-flat-before clip is not made.
# 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 140 Hz renders; v_<vowel>_s is the vowel with primary stress, nibu has it on /i/
# <out-root>/out148/v_<vowel> the unstressed vowel at 148.4 Hz (140 x 1.06: the f0 rise of primary stress alone)
# <out-root>/outnb/<w> the same word with --no-burst (plosive release_flow splines dropped)
# <out-root>/images, burst-notes.* clip_images.py: PNGs per clip and the burst times (needs numpy + matplotlib: PYTHON=<python with both>)
# <out-root>/clips/*.wav the files kit.json names; weak_spots.py <out-root> measures the rest
set -eu
REPO=$(cd "$1" && pwd); OUT=$2; PRE=${3:-}; JOBS=${4:-4}; HERE=$REPO/tools/aqua-listen/kits/tract-weak-spots
dotnet build "$REPO/tools/WordRender" -c Release -v q -o "$OUT/wr" | grep -E "rror\(s\)"
mkdir -p "$OUT/out" "$OUT/out148" "$OUT/outnb" "$OUT/clips" "$OUT/pre"
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 nibu nibu_flat v_i v_i_s bin bun ba ama ana v_ih v_oo_short v_ah v_ah_s v_e v_e_s v_o v_o_s v_u v_u_s; do echo "$n out 140"; done
for n in bin ba bun nibu nibu_flat; do echo "$n outnb 140 --no-burst"; done
for v in i e ah o u ih oo_short; do echo "v_$v out148 148.4"; done
} | xargs -P "$JOBS" -L1 bash -c 'job "$@"' _
if [ -n "$PRE" ]; then
dotnet build "$PRE/tools/WordRender" -c Release -v q -o "$OUT/wr-pre" | grep -E "rror\(s\)"
dotnet "$OUT/wr-pre/WordRender.dll" "$OUT/pre/nibu_flat" nibu_flat 140 "$HERE/phones/nibu_flat.json" > "$OUT/pre/nibu_flat.log" 2>&1
cp "$OUT/pre/nibu_flat/nibu_flat.wav" "$OUT/clips/nibu_flat_before.wav"
fi
C=$OUT/clips
cp "$OUT/out/nibu_flat/nibu_flat.wav" "$C/nibu_flat.wav"; cp "$OUT/out/nibu_flat/nibu_flat.wav" "$C/nibu_flat_after.wav" # one render, two ids: the before/after pair is one-to-one
for n in nibu v_i v_i_s v_ih v_oo_short ama ana ba bun; do cp "$OUT/out/$n/$n.wav" "$C/$n.wav"; done
for n in ba bun; 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

@ -1,28 +0,0 @@
#!/usr/bin/env python3
"""Turns the six voice-source renders into the kit's clip files and measures them.
clips.py <out-root> reads out/<label>/<label>.wav, writes clips/*.wav and measures.txt
ros_matched is ros multiplied by (saw rms / ros rms) over the whole clip; every other clip is a byte copy of a render, and a clip used in two pairs is
written once per pair under its own file name, so each pair is a unit the page can shuffle. Needs numpy."""
import sys, wave, shutil, pathlib
import numpy as np
sys.path.insert(0, str(pathlib.Path(__file__).parent))
from hnr import read, hnr
out = pathlib.Path(sys.argv[1]); clips = out / "clips"; clips.mkdir(exist_ok=True)
w = lambda n: out / "out" / n / f"{n}.wav"
x = {n: read(str(w(n)))[0] for n in ["ref", "ros", "w20", "h20", "h25", "h15"]}
rms = lambda a: float(np.sqrt(np.mean(a * a)))
gain = rms(x["ref"]) / rms(x["ros"])
with wave.open(str(w("ros"))) as src, wave.open(str(clips / "ros_matched.wav"), "wb") as dst:
dst.setparams(src.getparams())
dst.writeframes((np.clip(x["ros"] * gain, -1, 1) * 32767).astype("<i2").tobytes())
files = {"saw_a.wav": "ref", "ros.wav": "ros", "saw_b.wav": "ref", "clean.wav": "ref", "w20.wav": "w20", "w20_b.wav": "w20", "h20.wav": "h20", "h25.wav": "h25", "h15.wav": "h15"}
for f, n in files.items():
shutil.copyfile(w(n), clips / f)
lines = [f"{'clip':14s} {'HNR dB':>7s} {'rms':>8s} {'peak':>7s}"]
for name in sorted(p.name for p in clips.glob("*.wav")):
a, _ = read(str(clips / name))
lines.append(f"{name:14s} {hnr(a, 48000)[0]:7.1f} {rms(a):8.4f} {np.abs(a).max():7.3f}")
lines.append(f"ros_matched gain {gain:.3f} ({20 * np.log10(gain):.2f} dB)")
(out / "measures.txt").write_text("\n".join(lines) + "\n")
print("\n".join(lines))

View file

@ -1,43 +0,0 @@
#!/usr/bin/env python3
"""Harmonics-to-noise ratio of a clip, Boersma (1993) autocorrelation method, so a noise setting can be named in dB instead of in engine units.
hnr.py CLIP.wav [f0-hz] prints median HNR over the voiced frames, and the frame count
Frames of 40 ms at a 10 ms hop; a frame counts when its rms is above a tenth of the loudest frame's. r = the window-corrected normalised
autocorrelation peak within +-25 % of f0 (default 140); HNR = 10 log10(r / (1 - r)). Reads 16-bit mono wav; needs numpy only.
It is a measurement of the periodic share of the rendered output, not of the source alone: the tract shapes both.
"""
import sys, wave
import numpy as np
def read(path):
with wave.open(path) as w:
assert w.getsampwidth() == 2 and w.getnchannels() == 1
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(float) / 32768, w.getframerate()
def hnr(x, fs, f0=140.0, win=0.04, hop=0.01):
n, h = int(win * fs), int(hop * fs)
w = np.hanning(n)
nfft = 1 << (2 * n - 1).bit_length()
wac = np.fft.irfft(np.abs(np.fft.rfft(w, nfft)) ** 2)[:n]
wac /= wac[0]
lo, hi = int(fs / (f0 * 1.25)), int(fs / (f0 * 0.75))
frames = [x[i:i + n] for i in range(0, len(x) - n, h)]
rms = np.array([np.sqrt(np.mean(f * f)) for f in frames])
out = []
for f, e in zip(frames, rms):
if e < 0.1 * rms.max():
continue
f = (f - f.mean()) * w
if not f.any():
continue
ac = np.fft.irfft(np.abs(np.fft.rfft(f, nfft)) ** 2)[:n]
r = float(np.clip((ac[lo:hi] / ac[0] / wac[lo:hi]).max(), 1e-6, 1 - 1e-6))
out.append(10 * np.log10(r / (1 - r)))
return float(np.median(out)), len(out)
if __name__ == "__main__":
x, fs = read(sys.argv[1])
v, k = hnr(x, fs, float(sys.argv[2]) if len(sys.argv) > 2 else 140.0)
print(f"{v:.1f} dB over {k} frames")

View file

@ -1,89 +0,0 @@
{
"kit": {
"id": "voice-source-1",
"title": "Synthetic voice: one source change at a time",
"note": "The same short phrase, five pairs. In each pair only one thing about the voice's sound source differs. Tell us what you hear in the voice itself: buzz, edge, kazoo, breath, hiss. There are no wrong answers; 'no difference' is a real answer."
},
"clips": [
{
"id": "pulse-saw",
"file": "saw_a.wav",
"group": "pulse",
"pair": "pulse-rosenberg",
"title": "saw pulse, scaffold noise",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "pulse-rosenberg",
"file": "ros.wav",
"group": "pulse",
"pair": "pulse-saw",
"title": "Rosenberg pulse, scaffold noise",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "pulsematch-saw",
"file": "saw_b.wav",
"group": "pulsematch",
"pair": "pulsematch-rosenberg",
"title": "saw pulse, scaffold noise",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "pulsematch-rosenberg",
"file": "ros_matched.wav",
"group": "pulsematch",
"pair": "pulsematch-saw",
"title": "Rosenberg pulse, level matched to the saw",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "noise-clean",
"file": "clean.wav",
"group": "noise",
"pair": "noise-hnr20",
"title": "scaffold noise",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "noise-hnr20",
"file": "w20.wav",
"group": "noise",
"pair": "noise-clean",
"title": "white noise, level .33",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "colour-white20",
"file": "w20_b.wav",
"group": "colour",
"pair": "colour-hp20",
"title": "white noise, level .33",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "colour-hp20",
"file": "h20.wav",
"group": "colour",
"pair": "colour-white20",
"title": "noise high-passed at 2 kHz, level .33",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "aspiration-hp25",
"file": "h25.wav",
"group": "aspiration",
"pair": "aspiration-hp15",
"title": "noise high-passed at 2 kHz, level .165",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
},
{
"id": "aspiration-hp15",
"file": "h15.wav",
"group": "aspiration",
"pair": "aspiration-hp25",
"title": "noise high-passed at 2 kHz, level .6",
"feel": "the short made-up phrase 'ah-mee' in a synthetic voice; listen to the voice itself (buzz, edge, breath), not the words"
}
]
}

View file

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

View file

@ -1,45 +0,0 @@
# voice-source-1: predictions, written before any clip was rendered
Phrase: /ɑmi/ (WordRender, 140 Hz, 48 kHz). Meta's verdict on tract-weak-spots-1 heard "a kazoo with a two pack a day smoking habit", "reedy ... pink trombone", "a basketball buzzer" for /m/ and /n/; the voice source (a band-limited saw through a one-pole lowpass, plus 0.08 x noise x white) is the shared suspect. Each pair below changes ONE source parameter, everything else is the scaffold's.
Source-side numbers (computed from the two source formulas alone, harmonics of 140 Hz after the same tilt lowpass at 1131 Hz; the tract is not in them): Rosenberg minus saw, per harmonic: H1 +1.2 dB, H2 +0.3, H3 -6.3, H5 -10.5, H8 -17.2, H10 -17.8, H15 -22.0, H20 -24.5, H28 -27.4. Source rms differs +0.4 dB.
| pair | A | B | what changes | prediction | falsified if |
|---|---|---|---|---|---|
| pulse | saw | rosenberg | `pulse=` | B is darker and rounder: less buzz, less edge, F2 of /i/ weaker (the harmonics near 2 kHz are ~22 dB lower). Loudness the same (rms within 0.5 dB). | no difference heard; or B heard as buzzier/brighter; or B heard as the same "kazoo" quality. |
| noise level | saw, noise at scaffold (effective level .05: the gesture splines hold noise at .05 and win over the slider's base value) | saw, white noise raised to HNR 20 dB | `noise=` | B has audible breath/hiss under the voice; a listener who called A a "kazoo" or "buzzer" hears B as less pure-tone, but still a machine. | B is not noisier; or the noise is heard as a separate hiss stream not fused with the voice; or A and B are both still a kazoo to the same degree (then purity of the periodicity is not what makes it a kazoo). |
| noise colour | white noise, HNR 20 dB | noise high-passed at 2 kHz, HNR 20 dB | `noise_hp=` (noise level re-set to keep HNR 20) | B reads as hiss/"s"-like air, more separable from the voice than A; A reads as roughness/breathy voice. | no difference; or B heard as less hissy than A. |
| aspiration level | high-passed noise, HNR 25 dB | high-passed noise, HNR 15 dB | `noise=` | B is clearly hissy; A is at most faintly airy and may be called "no difference" from a clean voice. | A is already clearly hissy, or B is not hissier than A. |
Measured HNR (hnr.py, Boersma autocorrelation, median over voiced frames) is reported next to each clip after rendering; a target missed by more than 2 dB is stated as missed, and the noise value is not retuned to the answer.
What this kit cannot say: LF (the Liljencrants-Fant model) is not tested; the pulse is Rosenberg C with fixed open phase 0.4 and return 0.16. One listener, one phrase, one f0, one device.
## Added after the calibration renders, before the kit renders
Sixteen calibration renders of the same phrase were made in two rounds of eight (14:32 and 14:43 on 2026-11-13; nobody listened to them). The figures below are from the second round plus the Rosenberg render of the first; the first round's other five renders were made and their results are not reported here. They gave: noise 0 -> HNR 30.8 dB (the method's ceiling on this phrase), white noise .1/.16/.25 -> 27.7/25.2/22.2, noise high-passed at 2 kHz .2/.4/.7/1.0 -> 24.5/18.4/13.6/10.6, and Rosenberg at the scaffold's noise -> 29.1 dB. They also showed the Rosenberg render is 2.5 dB lower in output rms (measured -2.54 dB on the final render) and 6.8 dB lower in peak than the saw, although the SOURCE rms is matched: the tract passes the saw's strong upper harmonics and the pulse has none. The first prediction row's "loudness the same" is therefore already known to be false at the output; it stays in the table as written.
A fifth pair is added so loudness cannot carry the answer: the Rosenberg render scaled up by its measured rms deficit against the saw (a gain on the clip, applied by the kit's render script), against the same saw render. Prediction: the same darker, rounder B as the pulse pair, and B is no longer the quieter one. FALSIFIED if B at matched rms is no longer heard as darker/rounder (then loudness, not shape, carried the first pair), or if it is heard as louder or brighter.
Targets chosen from the calibration fit: white .33 -> HNR 20 dB; high-passed .33 -> 20 dB, .165 -> 25 dB, .6 -> 15 dB.
## Measured on main ca6af1d
Figures for the ten kit clips, taken on main `ca6af1d` (PR #52) with `hnr.py` and `clips.py` (`measures.txt`). Removed from the clip titles, which the listener can see through the export.
| clip id | file | HNR dB | output rms | peak | note |
|---|---|---|---|---|---|
| pulse-saw | saw_a.wav | 30.3 | 0.0537 | 0.227 | scaffold: band-limited saw through the tilt lowpass |
| pulse-rosenberg | ros.wav | 29.5 | 0.0401 (-2.5 dB re saw) | 0.102 (-6.9 dB) | rms deficit is a fact at the output; the prediction row's "loudness the same" is already falsified there |
| pulsematch-saw | saw_b.wav | 30.3 | 0.0537 | 0.227 | byte copy of pulse-saw's render |
| pulsematch-rosenberg | ros_matched.wav | 29.5 | 0.0537 (matched to the saw) | 0.137 | ros times 1.341 (+2.55 dB) |
| noise-clean | clean.wav | 30.3 | 0.0537 | 0.227 | the scaffold's noise floor, 0.05; noise 0 measured 30.8 before the tract fix, the method's ceiling here |
| noise-hnr20 | w20.wav | 19.9 | 0.0539 | 0.242 | white noise raised to level 0.33 |
| colour-white20 | w20_b.wav | 19.9 | 0.0539 | 0.242 | byte copy of noise-hnr20's render |
| colour-hp20 | h20.wav | 19.9 | 0.0540 | 0.238 | noise high-passed at 2 kHz (2nd order), level 0.33 |
| aspiration-hp25 | h25.wav | 25.8 | 0.0538 | 0.231 | high-passed noise, level 0.165 |
| aspiration-hp15 | h15.wav | 14.9 | 0.0546 | 0.250 | high-passed noise, level 0.6 |
Band energy re total, 0-0.5 / 0.5-1.5 / 1.5-3 / 3-6 kHz, from the render before the tract fix of PR #52: saw -2.3 / -4.0 / -24.0 / -24.9 dB, Rosenberg -0.3 / -12.4 / -43.7 / -40.3 dB. These were not re-taken with the original method. A whole-file Hann periodogram on the new render gives saw -2.2 / -4.0 / -24.0 / -25.0 and Rosenberg -0.3 / -12.5 / -43.2 / -40.2, within 0.5 dB; a different FFT estimate of the new render differs by under 1 dB, and an independent check found the figures depend on the estimator (Welch differs by up to 1.6 dB, a raw periodogram by up to 3.1 dB). Read them as estimates to about 1 to 3 dB. The HNR figure is the Boersma autocorrelation method of `hnr.py` on the rendered output; Praat's autocorrelation HNR is within 0.5 dB for the noisy clips, and the clean clip sits at this method's ceiling.
Record corrections after the Soul pass (2026-11-14): the noise pair's table cell said the scaffold's noise was .04, the effective level is .05 (the cell was edited; the pair, the prediction and the falsifier are unchanged); the calibration addendum's count of renders was eight and is sixteen.

View file

@ -1,20 +0,0 @@
#!/bin/bash
# Renders the voice-source-1 kit: the phrase /ɑmi/ (WordRender, 140 Hz, 48 kHz mono 16-bit), six renders that differ from the scaffold in ONE source field each:
# ref (noise=.05, the scaffold's own effective level: byte-identical to a render with no --source) ros (pulse=rosenberg) w20 (noise=.33, white, HNR ~20) h20 (noise_hp=2000 noise=.33) h25 (noise_hp=2000 noise=.165) h15 (noise_hp=2000 noise=.6)
# then ros_matched: ros scaled by the measured output-rms ratio saw/rosenberg, so a pair can be heard without the level difference.
# 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/<label>/<label>.wav <out-root>/clips/*.wav the files kit.json names <out-root>/measures.txt HNR, rms, peak per clip
# Build the page: node tools/aqua-listen/build.mjs --manifest tools/aqua-listen/kits/voice-source/kit.json --clips <out-root>/clips --out <out-root>/dist
set -eu
REPO=$(cd "$1" && pwd); OUT=$2; JOBS=${3:-6}; HERE=$REPO/tools/aqua-listen/kits/voice-source
PY=${PYTHON:-python3}
dotnet build "$REPO/tools/WordRender" -c Release -v q -o "$OUT/wr" | grep -E "rror\(s\)"
mkdir -p "$OUT/out" "$OUT/clips"
job() { n=$1; shift; dotnet "$OUT/wr/WordRender.dll" "$OUT/out/$n" "$n" 140 "$HERE/phones/ami.json" --source "$*" > "$OUT/out/$n.log" 2>&1 && echo "$n ok" || echo "$n FAILED (see $OUT/out/$n.log)"; }
export -f job; export OUT HERE
{
echo "ref noise=.05"; echo "ros pulse=rosenberg"; echo "w20 noise=.33"
echo "h20 noise_hp=2000 noise=.33"; echo "h25 noise_hp=2000 noise=.165"; echo "h15 noise_hp=2000 noise=.6"
} | xargs -P "$JOBS" -L1 bash -c 'job "$@"' _
$PY -I "$HERE/clips.py" "$OUT"

View file

@ -100,43 +100,4 @@ function verdictMarkdown(v) {
return L.join("\n") + "\n";
}
// Autosave. The key names the kit by its id and its clip-id set, not by the content hash: a rebuild that fixes a note or
// re-renders a clip is the same kit and keeps the listener's answers; a different clip-id set is a different kit and starts
// fresh (the old entry is left untouched in the browser). Saved state is answers by clip id and pairs by "idA|idB", plus the
// seed; the A/B/same value of a pair is positional (A is the first of the pair in the seed's order), so it stays meaningful
// only while the manifest's clip order is unchanged.
const SAVE_PREFIX = "aqua-listen.v2:";
function saveKey(manifest) { return `${SAVE_PREFIX}${manifest.kit.id}:${manifest.clips.map((c) => c.id).sort().join(",")}`; }
// Earlier pages keyed the save by `aqua-listen:<kitid>:<8-hex content hash>`. Given every localStorage entry as
// [{key, state}] (state already parsed, null if unparseable), returns the key of the legacy entry to adopt, or null:
// same kit id, a seed, and answers/pairs that mention only clip ids of this kit. Fullest entry wins (most answered fields);
// ties go to the later key so the choice is deterministic.
function pickLegacySave(manifest, entries) {
const ids = new Set(manifest.clips.map((c) => c.id)), prefix = `aqua-listen:${manifest.kit.id}:`;
let best = null, bestScore = -1;
for (const { key, state } of entries) {
if (typeof key !== "string" || !key.startsWith(prefix) || !/^[0-9a-f]{8}$/.test(key.slice(prefix.length))) continue;
if (!state || typeof state !== "object" || !state.seed || typeof state.answers !== "object" || !state.answers) continue;
const pairs = state.pairs && typeof state.pairs === "object" ? state.pairs : {};
if (!Object.keys(state.answers).every((id) => ids.has(id))) continue;
if (!Object.keys(pairs).every((k) => k.split("|").every((id) => ids.has(id)))) continue;
const score = Object.values(state.answers).reduce((n, a) => n + (a ? ["verdict", "landed", "reason"].filter((f) => a[f]).length : 0), 0) + Object.keys(pairs).length;
if (score > bestScore || (score === bestScore && key > best)) { best = key; bestScore = score; }
}
return best;
}
// A save as stored -> the state the page runs on, or null. Normalises answers/pairs to plain objects (a hand-edited or old save
// must not crash the page). pairSig records the manifest's clip order the pair picks were made under; a pick's A/B/same is
// relative to that order, so a save with a missing or different pairSig keeps seed and answers and loses its pairs. A legacy
// (hash-keyed) save has no pairSig and cannot be checked: its pairs are kept and stamped with the current signature.
const pairSig = (manifest) => manifest.clips.map((c) => c.id).join(",");
const plain = (o) => (o && typeof o === "object" && !Array.isArray(o) ? o : {});
function restoreSave(manifest, saved, legacy) {
if (!saved || typeof saved !== "object" || !saved.seed) return null;
const sig = pairSig(manifest), keep = legacy || saved.pairSig === sig;
return Object.assign({}, saved, { answers: plain(saved.answers), pairs: keep ? plain(saved.pairs) : {}, pairSig: sig });
}
module.exports = { SCHEMA, VERDICTS, DEVICES, AUDIO_EXT, validateManifest, planOrder, buildVerdict, verdictMarkdown, rng, saveKey, pickLegacySave, pairSig, restoreSave };
module.exports = { SCHEMA, VERDICTS, DEVICES, AUDIO_EXT, validateManifest, planOrder, buildVerdict, verdictMarkdown, rng };

View file

@ -1,20 +1,12 @@
// Browser smoke for a built page: node smoke.mjs listen.html (needs playwright-core and a Chromium; set PLAYWRIGHT_CORE=/path/to/playwright-core
// and optionally CHROME=/path/to/chrome). Not part of `node test.mjs`: the repo has no browser dependency.
import { createRequire } from "node:module";
import { readFileSync, writeFileSync, mkdtempSync } from "node:fs";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { buildKit } from "./build.mjs";
import { resolve, join } from "node:path";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_CORE ?? "playwright-core");
const file = resolve(process.argv[2]);
const browser = await chromium.launch({ executablePath: process.env.CHROME || undefined });
// MOBILE=1 drives an Android-Chrome-shaped context (touch, small viewport, mobile UA) with no downloads accepted.
const mobile = !!process.env.MOBILE;
const ctx = await browser.newContext(mobile
? { acceptDownloads: false, viewport: { width: 412, height: 915 }, hasTouch: true, isMobile: true, deviceScaleFactor: 2.6, permissions: ["clipboard-read", "clipboard-write"],
userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36" }
: { acceptDownloads: true, permissions: ["clipboard-read", "clipboard-write"] }), page = await ctx.newPage();
const ctx = await browser.newContext({ acceptDownloads: true }), page = await ctx.newPage();
const requests = [], errors = [];
page.on("request", (r) => { if (!r.url().startsWith("file:") && !r.url().startsWith("blob:") && !r.url().startsWith("data:")) requests.push(r.url()); });
page.on("pageerror", (e) => errors.push(e.message));
@ -32,70 +24,15 @@ await first.locator("input[value=fix]").check(); await first.locator("input[type
await page.reload();
check(await page.locator("section.card").first().locator("input[value=fix]").isChecked(), "answers survive a reload (localStorage autosave)");
check((await page.locator("section.card").first().locator("input[type=text]").inputValue()) === "a bit thin", "reason survives a reload");
await page.click("#export");
const text = await page.inputValue("#export-text");
check(await page.locator("#export-text").evaluate((e) => e.readOnly), "export textarea is read-only");
const v = JSON.parse(text);
check(v.listener === "Tester" && v.device === "headphones" && v.clips[0].verdict === "fix" && v.clips[0].landed === 4 && v.clips[0].device === "headphones", "textarea carries the verdict JSON");
const got = [];
page.on("download", (d) => got.push(d));
await page.click("button:has-text('Export')");
for (let i = 0; i < 50 && got.length < 2; i++) await page.waitForTimeout(100);
const names = got.map((d) => d.suggestedFilename()).sort();
check(names.join() === "verdict.json,verdict.md", "export downloads verdict.json and verdict.md");
const v = JSON.parse(readFileSync(await got.find((d) => d.suggestedFilename() === "verdict.json").path(), "utf8"));
check(v.listener === "Tester" && v.device === "headphones" && v.clips[0].verdict === "fix" && v.clips[0].landed === 4 && v.clips[0].device === "headphones", "verdict.json carries the answers");
check(v.consent === true && v.clips.length === total, "consent recorded, every clip present");
await page.click("#copy-json");
check((await page.evaluate(() => navigator.clipboard.readText())) === text, "Copy button puts the full JSON on the clipboard");
// http-Android shape: no async clipboard API at all, so only the execCommand path can copy
await page.evaluate(() => { Object.defineProperty(navigator, "clipboard", { value: undefined, configurable: true }); window.__copied = null; document.execCommand = (c) => { window.__copied = document.activeElement.value; return c === "copy"; }; });
await page.click("#copy-json");
check((await page.textContent("#export-msg")).startsWith("Copied") && (await page.evaluate(() => window.__copied)) === text, "without the clipboard API, the execCommand fallback copies the full JSON");
await page.reload();
await page.click("#export");
check((await page.inputValue("#export-text")).includes('"verdict": "fix"'), "reload loses nothing: export after reload still has the answers");
check(requests.length === 0, `no network requests (${requests.join(", ")})`);
check(errors.length === 0, `no page errors (${errors.join("; ")})`);
// ---- Autosave persistence across a rebuild. Served over http at one fixed path so the origin (and localStorage) is the same for
// the page as given (A) and a rebuild of the same kit with a different content hash (B: a note edit and one byte appended to a clip).
const html = readFileSync(file, "utf8"), kit = JSON.parse(html.match(/<script id="kit-data"[^>]*>([\s\S]*?)<\/script>/)[1].replace(/\\u003c/g, "<"));
const tmp = mkdtempSync(join(tmpdir(), "aqua-listen-smoke-"));
for (const c of kit.manifest.clips) { const buf = Buffer.from(kit.audio[c.id].b64, "base64"); writeFileSync(join(tmp, c.file), c.id === kit.manifest.clips[0].id ? Buffer.concat([buf, Buffer.from([0])]) : buf); }
const B = buildKit({ ...kit.manifest, kit: { ...kit.manifest.kit, note: (kit.manifest.kit.note || "") + " (rebuilt)" } }, tmp);
check(B.hash !== kit.hash, `the rebuilt page has a different content hash (${kit.hash} -> ${B.hash})`);
let serving = html;
const srv = createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(q.url.startsWith("/p/listen.html") ? serving : "x"); });
await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
const url = `http://127.0.0.1:${srv.address().port}/p/listen.html`;
const ids = kit.manifest.clips.map((c) => c.id), mfst = kit.manifest.kit.id;
const ctx2 = await browser.newContext(), pg = await ctx2.newPage(), errs2 = [];
pg.on("pageerror", (e) => errs2.push(e.message));
const begin = async () => { await pg.goto(url); if (await pg.locator("#consent").count()) { await pg.check("#consent"); await pg.click("button:has-text('Start listening')"); } };
const firstId = async () => (await pg.locator("section.card").first().getAttribute("id")).slice(5);
await begin();
const id1 = await firstId(), card = () => pg.locator("#clip-" + id1);
await card().locator("input[value=drop]").check(); await card().locator("input[type=text]").fill("rebuild survivor");
await pg.reload();
check(await card().locator("input[value=drop]").isChecked(), "persistence: answer survives a reload of the same page");
serving = B.html; await pg.reload();
check((await pg.locator("body").innerText()).includes("(rebuilt)"), "persistence: the rebuilt page is what loaded");
check(await card().locator("input[value=drop]").isChecked() && (await card().locator("input[type=text]").inputValue()) === "rebuild survivor", "persistence: answers survive a rebuild with a different content hash");
const keys = await pg.evaluate(() => Object.keys(localStorage));
check(keys.length === 1 && keys[0].startsWith("aqua-listen.v2:"), `persistence: one save, under the hash-free key (${keys})`);
// an earlier build's hash-keyed save is adopted when the new key is empty, and never overwrites a new-key save
await pg.evaluate(() => localStorage.clear());
const old = (seed, verdict) => JSON.stringify({ seed, answers: { [ids[ids.length - 1]]: { verdict, landed: 2, reason: "typed before the rebuild" } }, pairs: {}, device: "speakers", notes: "", listener: "Meta", consent: true });
const oldKey = `aqua-listen:${mfst}:${kit.hash}`;
await pg.evaluate(([k, v, k2, v2]) => { localStorage.setItem(k, v); localStorage.setItem(k2, v2); }, [oldKey, old(11, "keep"), `aqua-listen:other-kit:${kit.hash}`, old(12, "drop")]);
await pg.reload();
await pg.click("button:has-text('Start listening')").catch(() => {});
const lastCard = pg.locator("#clip-" + ids[ids.length - 1]);
check(await lastCard.locator("input[value=keep]").isChecked() && (await lastCard.locator("input[type=text]").inputValue()) === "typed before the rebuild", "migration: the hash-keyed save from the earlier build is adopted");
check((await pg.evaluate(() => Object.keys(localStorage))).some((k) => k.startsWith("aqua-listen.v2:")) && (await pg.evaluate(([k]) => JSON.parse(localStorage.getItem(Object.keys(localStorage).find((x) => x.startsWith("aqua-listen.v2:")))).seed, [0])) === 11, "migration: saved under the new key, with the old seed");
check(await pg.evaluate((k) => localStorage.getItem(k) !== null, `aqua-listen:other-kit:${kit.hash}`), "migration: another kit's entry is left untouched");
await pg.evaluate(([k, v]) => { localStorage.setItem(k, v); localStorage.setItem(Object.keys(localStorage).find((x) => x.startsWith("aqua-listen.v2:")), v); }, [oldKey, old(13, "fix")]);
await pg.reload();
check(await pg.locator("#clip-" + ids[ids.length - 1]).locator("input[value=fix]").isChecked(), "migration: an existing new-key save is used, not overwritten by the hash-keyed one");
// a save with no pairs and array answers must not crash the page; a reordered kit keeps answers and drops pair picks
await pg.evaluate(([k]) => { localStorage.clear(); localStorage.setItem(k, JSON.stringify({ seed: 5, answers: [], consent: true })); }, [(await pg.evaluate(() => 0), `aqua-listen.v2:${mfst}:${[...ids].sort().join(",")}`)]);
await pg.reload();
check(await pg.locator("audio").count() === ids.length && errs2.length === 0, "a save without pairs and with array answers loads without errors");
await pg.evaluate(([k, v]) => localStorage.setItem(k, v), [oldKey, old(14, "drop")]);
pg.once("dialog", (d) => d.accept()); await pg.click("text=Erase this kit's saved answers"); await pg.waitForLoadState();
check(await pg.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("aqua-listen:") && !k.includes("other-kit") || k.startsWith("aqua-listen.v2:")).length) === 0 && await pg.locator("#consent").count() === 1, "erase removes the new-key save and the adoptable hash-keyed one (nothing resurrects)");
check(errs2.length === 0, `persistence: no page errors (${errs2.join("; ")})`);
srv.close();
await browser.close();

View file

@ -101,73 +101,9 @@ test("build refuses a missing file and a manifest escape, naming them", () => {
assert.throws(() => buildKit(mf([clip("a", { file: "../x.wav" })]), dir), /relative path/);
assert.throws(() => buildKit(mf([clip("a", { title: "" })]), dir), /title is required/);
});
test("pictures ride in a collapsed block only for clips that have both, and only then does the policy admit data: images", () => {
const pics = mkdtempSync(join(tmpdir(), "aqua-listen-img-")), png = Buffer.from("89504e470d0a1a0a", "hex");
writeFileSync(join(pics, "a.spec.png"), png); writeFileSync(join(pics, "a.wave.png"), png); writeFileSync(join(pics, "b.spec.png"), png);
const withPics = buildKit(manifest, dir, pics), data = JSON.parse(/<script id="kit-data" type="application\/json">(.*?)<\/script>/s.exec(withPics.html)[1]);
assert.deepEqual(Object.keys(data.images), ["a"]);
assert.deepEqual(data.images.a.map((p) => p.label), ["spectrogram", "waveform"]);
assert.match(withPics.html, /media-src blob:; img-src data:/);
const bare = buildKit(manifest, dir);
assert.doesNotMatch(bare.html, /img-src/); assert.deepEqual(JSON.parse(/<script id="kit-data" type="application\/json">(.*?)<\/script>/s.exec(bare.html)[1]).images, {});
assert.notEqual(withPics.hash, bare.hash);
});
test("markup in a title cannot break the page", () => {
const m = mf([clip("a", { title: "</script><b>" , feel: "</script>"})]);
const h = buildKit(m, dir).html;
assert.equal((h.match(/<\/script>/g) || []).length, 3);
});
const st = (answers, pairs = {}) => ({ seed: 7, answers, pairs, consent: true });
test("autosave key is stable across a content-hash change and moves with the clip-id set", () => {
const m = mf([clip("b"), clip("a")]);
assert.equal(L.saveKey(m), L.saveKey(mf([clip("a"), clip("b", { title: "reworded", feel: "other" })])), "title/feel edits and clip order do not move the key");
assert.notEqual(L.saveKey(m), L.saveKey(mf([clip("a"), clip("b"), clip("c")])));
assert.notEqual(L.saveKey(m), L.saveKey(mf([clip("a"), clip("z")])));
assert.notEqual(L.saveKey(m), L.saveKey({ kit: { id: "k2", title: "Kit" }, clips: m.clips }));
assert.ok(!/^aqua-listen:/.test(L.saveKey(m)), "new keys are never mistaken for hash-keyed legacy entries");
const dir2 = mkdtempSync(join(tmpdir(), "aqlk-")); writeFileSync(join(dir2, "a.wav"), Buffer.alloc(50)); writeFileSync(join(dir2, "b.wav"), Buffer.alloc(50));
const b1 = buildKit(m, dir2); writeFileSync(join(dir2, "b.wav"), Buffer.alloc(51)); const b2 = buildKit(m, dir2);
assert.notEqual(b1.hash, b2.hash);
assert.ok(b1.html.includes("saveKey") && !b1.html.includes("${kit.hash}"), "the built page keys on saveKey, not the hash");
});
test("legacy migration adopts the hash-keyed entry of the same kit", () => {
const m = mf([clip("a"), clip("b")]);
const old = { key: "aqua-listen:k1:93312816", state: st({ a: { verdict: "keep", landed: 3 } }) };
assert.equal(L.pickLegacySave(m, [{ key: "unrelated", state: null }, old]), old.key);
const fuller = { key: "aqua-listen:k1:00000001", state: st({ a: { verdict: "keep", landed: 3, reason: "x" }, b: { verdict: "fix" } }) };
assert.equal(L.pickLegacySave(m, [old, fuller]), fuller.key, "the fuller entry wins");
});
test("legacy migration ignores other kits, foreign clip ids, malformed keys and empty state", () => {
const m = mf([clip("a"), clip("b")]), ans = { a: { verdict: "keep" } };
for (const e of [
{ key: "aqua-listen:k2:93312816", state: st(ans) }, // another kit
{ key: "aqua-listen:k1:93312816", state: st({ zz: { verdict: "keep" } }) }, // foreign clip id in answers
{ key: "aqua-listen:k1:93312816", state: st(ans, { "a|zz": "A" }) }, // foreign clip id in pairs
{ key: "aqua-listen:k1:nothex", state: st(ans) }, { key: "aqua-listen:k1:93312816:x", state: st(ans) },
{ key: "aqua-listen:k1:93312816", state: null }, { key: "aqua-listen:k1:93312816", state: { answers: ans } }])
assert.equal(L.pickLegacySave(m, [e]), null, JSON.stringify(e.key) + JSON.stringify(e.state));
});
test("restoreSave: reordered clips keep answers and seed but drop pair picks; same order keeps them", () => {
const m = mf([clip("a", { pair: "b" }), clip("b", { pair: "a" }), clip("c")]), rev = mf([...m.clips].reverse());
const saved = { ...st({ a: { verdict: "keep" }, c: { verdict: "fix" } }, { "a|b": "A" }), pairSig: L.pairSig(m) };
assert.deepEqual(L.restoreSave(m, saved, false).pairs, { "a|b": "A" });
const r = L.restoreSave(rev, saved, false);
assert.deepEqual(r.pairs, {}); assert.equal(r.seed, 7); assert.equal(r.answers.a.verdict, "keep"); assert.equal(r.pairSig, L.pairSig(rev));
assert.deepEqual(L.restoreSave(m, st({}, { "a|b": "A" }), false).pairs, {}, "no signature: pairs dropped");
assert.deepEqual(L.restoreSave(m, st({}, { "a|b": "A" }), true).pairs, { "a|b": "A" }, "legacy adoption keeps pairs");
assert.equal(L.restoreSave(m, st({}, { "a|b": "A" }), true).pairSig, L.pairSig(m), "and stamps the current signature");
assert.equal(L.restoreSave(m, { answers: {} }, false), null);
});
test("restoreSave: a save without pairs or with array answers is normalised, not left to crash the page", () => {
const m = mf([clip("a")]);
for (const bad of [{ seed: 3 }, { seed: 3, answers: [], pairs: null }, { seed: 3, answers: "x", pairs: [] }]) {
const r = L.restoreSave(m, bad, true); assert.deepEqual(r.answers, {}); assert.deepEqual(r.pairs, {});
L.buildVerdict(m, L.planOrder(m.clips, r.seed), r, "now");
}
});
test("the built page keys its save through saveKey and never builds a hash key", () => {
const h = buildKit(mf([clip("a")]), dir).html;
assert.ok(h.includes("KEY = L.saveKey(kit.manifest)"));
assert.ok(!/kit\.hash/.test(h) && !/KEY = [`"']/.test(h) && !/localStorage\.(set|get)Item\(`/.test(h), "no hash-form or string-built key in the page source");
});
console.log(`${n} tests passed`);

View file

@ -1,67 +0,0 @@
"""python3 -I test_clip_images.py (numpy + matplotlib; synthetic clips, no render needed)"""
import hashlib, json, sys, tempfile, unittest, wave
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import clip_images as ci
SR, BURST_AT = 48000, 0.30
def write(path, x):
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((np.clip(x, -1, 1) * 32767).astype("<i2").tobytes())
def word(with_burst):
t = np.arange(int(0.6 * SR)) / SR
x = 0.2 * np.sin(2 * np.pi * 300 * t) * (np.abs(t - 0.3) > 0.05) # a vowel with a gap round the release
if with_burst:
i = int(BURST_AT * SR); n = int(0.012 * SR)
x[i:i + n] += np.random.default_rng(1).normal(0, 0.1, n) * np.hanning(n)
return x
class Fixture(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp()); self.clips = self.tmp / "clips"; self.clips.mkdir()
write(self.clips / "ba.wav", word(True)); write(self.clips / "ba_noburst.wav", word(False))
self.root = self.tmp / "r"
for sub, wb in (("out", True), ("outnb", False)):
(self.root / sub / "ba").mkdir(parents=True); write(self.root / sub / "ba" / "ba.wav", word(wb))
(self.root / "out" / "ba" / "script.aqua").write_text("phoneme_gesture name=ba_0_ɑ ipa=ɑ start=0 dur=0.2 intensity=1\nphoneme_gesture name=ba_1_b ipa=b start=0.2 dur=0.095 intensity=1\n")
self.kit = self.tmp / "kit.json"
self.kit.write_text(json.dumps({"clips": [{"id": "x-ba", "file": "ba.wav"}, {"id": "x-ba-nb", "file": "ba_noburst.wav"}]}))
def run_tool(self, out, *extra):
sys.argv = ["clip_images", str(self.clips), str(out), *extra]; ci.main()
def test_images_are_deterministic_and_complete(self):
a, b = self.tmp / "a" / "images", self.tmp / "b" / "images"
self.run_tool(a); self.run_tool(b)
names = sorted(p.name for p in a.iterdir())
self.assertEqual(names, ["ba.spec.png", "ba.wave.png", "ba_noburst.spec.png", "ba_noburst.wave.png"])
for n in names:
self.assertEqual(hashlib.sha256((a / n).read_bytes()).hexdigest(), hashlib.sha256((b / n).read_bytes()).hexdigest(), n)
def test_notes_find_the_release_and_the_twin_says_none(self):
self.run_tool(self.tmp / "o" / "images", "--kit", str(self.kit), "--renders", str(self.root))
rows = json.loads((self.tmp / "o" / "burst-notes.json").read_text())
p = rows[0]["burst"][0]
self.assertAlmostEqual(p["release_s"], BURST_AT, delta=0.003)
self.assertGreater(p["burst_end_s"], BURST_AT + 0.004); self.assertLess(p["burst_end_s"], BURST_AT + 0.02)
self.assertEqual(rows[1]["burst"], "no burst expected")
self.assertIn("no burst expected", (self.tmp / "o" / "burst-notes.md").read_text())
def test_burst_shows_in_the_spectrogram_at_the_noted_time_only(self):
def hi_db(x, at):
db, f, t = ci.stft_db(x, SR); col = int(np.argmin(np.abs(t - at)))
lin = 10 ** (db[f > 2000, col] / 20); return 20 * np.log10(np.sqrt((lin ** 2).sum()) + 1e-12)
w, nb = word(True), word(False)
self.assertGreaterEqual(hi_db(w, BURST_AT + 0.006) - hi_db(nb, BURST_AT + 0.006), 10)
self.assertLess(hi_db(w, BURST_AT + 0.106) - hi_db(nb, BURST_AT + 0.106), 10) # a note 100 ms late would find nothing
if __name__ == "__main__":
unittest.main()

View file

@ -1,17 +1,11 @@
// Page glue. The kit (manifest, content hash, base64 audio, optional base64 PNGs per clip id) is in #kit-data; logic is AquaListen (logic.cjs, inlined).
// Page glue. The kit (manifest, content hash, base64 audio) is in #kit-data; logic is AquaListen (logic.cjs, inlined).
(() => {
const L = globalThis.AquaListen, kit = JSON.parse(document.getElementById("kit-data").textContent);
const app = document.getElementById("app"), KEY = L.saveKey(kit.manifest);
const app = document.getElementById("app"), KEY = `aqua-listen:${kit.manifest.kit.id}:${kit.hash}`;
let state = null, order = null;
const save = () => { try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) { /* private mode: the export still works */ } };
const read = (k) => { try { return JSON.parse(localStorage.getItem(k)); } catch (e) { return null; } };
const legacyEntries = () => { const e = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); e.push({ key: k, state: read(k) }); } return e; };
// Own key first; if empty, adopt a hash-keyed save from an earlier build of this kit (L.pickLegacySave) and keep using the new key.
const load = () => {
const own = L.restoreSave(kit.manifest, read(KEY), false); if (own) return own;
try { const from = L.pickLegacySave(kit.manifest, legacyEntries()); return from ? L.restoreSave(kit.manifest, read(from), true) : null; } catch (e) { return null; }
};
const load = () => { try { const s = JSON.parse(localStorage.getItem(KEY)); return s && s.seed ? s : null; } catch (e) { return null; } };
const h = (tag, attrs, ...kids) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) { if (k === "class") e.className = v; else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v); }
@ -35,7 +29,7 @@
h("ul", {},
h("li", {}, "This page works on its own. It talks to no server, has no account and no tracking, and sends nothing anywhere."),
h("li", {}, "Your answers are saved in this browser only, so you can close the tab and come back. Clearing your browser data erases them."),
h("li", {}, "Nothing leaves your computer until you press Export, which shows your answers as text to copy, share or save. Sending those files to the person who gave you this page is your choice."),
h("li", {}, "Nothing leaves your computer until you press Export, which saves two files. Sending those files to the person who gave you this page is your choice."),
h("li", {}, "You can stay anonymous. A name or nickname is optional.")),
h("p", {}, h("label", {}, box, " I understand, and I'm happy to take part.")),
h("p", {}, h("label", {}, "Name or nickname (optional) ", h("input", { type: "text", id: "alias", maxlength: "60" }))),
@ -68,7 +62,6 @@
h("h2", {}, o.slot ? `Sound ${o.slot}` : `Sound ${n}`),
h("p", { class: "feel" }, `It should feel: ${c.feel}`),
audio,
(kit.images[id] || []).length ? h("details", {}, h("summary", {}, "Pictures of this sound (optional)"), kit.images[id].map((p) => h("img", { src: "data:image/png;base64," + p.b64, alt: p.label, class: "pic" }))) : [],
h("div", { class: "row" }, h("span", {}, "Keep, fix or drop?"), radios("v-" + id, L.VERDICTS, a.verdict, (v) => touch(id, { verdict: v }))),
h("div", { class: "row" }, h("span", {}, "Did it land? 1 = not at all, 5 = completely"), radios("l-" + id, [1, 2, 3, 4, 5], a.landed, (v) => touch(id, { landed: Number(v) }))),
reason);
@ -95,40 +88,22 @@
h("div", { class: "bar" }, h("div", { class: "row" }, dev, prog)),
...cards,
h("div", { class: "card" }, h("h2", {}, "Finished?"), notes,
h("p", { class: "hint" }, "Export shows your answers as text you can copy, share or download. Unanswered sounds are exported as blank. Your answers stay saved in this browser until you erase them."),
h("div", { class: "row" }, h("button", { id: "export", onclick: exportAll }, "Export my answers"), h("button", { class: "quiet", onclick: reset }, "Erase this kit's saved answers")), h("div", { id: "export-panel" })));
h("p", { class: "hint" }, "Export saves verdict.json and verdict.md to your downloads. Unanswered sounds are exported as blank."),
h("div", { class: "row" }, h("button", { onclick: exportAll }, "Export verdict.json + verdict.md"), h("button", { class: "quiet", onclick: reset }, "Erase my answers"))));
progress();
}
function progress() { const e = document.getElementById("progress"); if (e) e.textContent = `${kit.manifest.clips.filter((c) => answered(c.id)).length} of ${kit.manifest.clips.length} answered`; }
// Export is a visible panel, not a silent download: Android Chrome blocks the second of two scripted downloads and
// gives no sign, so the verdict is also shown in a read-only textarea with copy, share and one-download-per-tap buttons.
function verdictNow() { return L.buildVerdict(kit.manifest, order, state, new Date().toISOString()); }
function download(name, text, type) {
const a = h("a", { href: URL.createObjectURL(new Blob([text], { type })), download: name });
document.body.append(a); a.click(); a.remove();
}
async function copyText(text, area) {
try { await navigator.clipboard.writeText(text); return true; } catch (e) { /* no clipboard API or not allowed: fall through */ }
try { area.focus(); area.select(); area.setSelectionRange(0, text.length); return document.execCommand("copy"); } catch (e) { return false; }
}
function exportAll() {
const v = verdictNow(), json = JSON.stringify(v, null, 2) + "\n", md = L.verdictMarkdown(v);
const area = h("textarea", { id: "export-text", rows: "10", readonly: true, "aria-label": "Your answers as verdict.json" }, json);
const msg = h("p", { class: "hint", id: "export-msg", role: "status" }, "Your answers are below. Copy them and paste them into a message to whoever sent you this page.");
const say = (t) => { msg.textContent = t; };
const buttons = [
h("button", { id: "copy-json", onclick: async () => say((await copyText(json, area)) ? "Copied verdict.json. Paste it into your message." : "Copy was blocked. The text box is selected: use your phone's Copy.") }, "Copy answers (JSON)"),
h("button", { class: "quiet", id: "copy-md", onclick: async () => { const t = h("textarea", {}, md); document.body.append(t); const ok = await copyText(md, t); t.remove(); say(ok ? "Copied the readable table." : "Copy was blocked."); } }, "Copy as table"),
h("button", { class: "quiet", onclick: () => { area.focus(); area.select(); area.setSelectionRange(0, json.length); say("Selected. Use your phone's Copy."); } }, "Select all"),
h("button", { class: "quiet", onclick: () => download("verdict.json", json, "application/json") }, "Download verdict.json"),
h("button", { class: "quiet", onclick: () => download("verdict.md", md, "text/markdown") }, "Download verdict.md")];
if (navigator.share) buttons.splice(2, 0, h("button", { class: "quiet", id: "share", onclick: () => navigator.share({ title: "Listening verdict", text: json }).catch(() => say("Sharing was cancelled or unavailable.")) }, "Share"));
const panel = document.getElementById("export-panel");
panel.replaceChildren(h("h3", {}, "Your answers"), msg, area, h("div", { class: "row" }, buttons));
area.focus(); area.select(); panel.scrollIntoView();
const v = L.buildVerdict(kit.manifest, order, state, new Date().toISOString());
download("verdict.json", JSON.stringify(v, null, 2) + "\n", "application/json");
download("verdict.md", L.verdictMarkdown(v), "text/markdown");
}
function reset() { if (confirm("Erase the answers this page has saved in this browser for this kit, including any older saved copy of them? Other pages are not touched.")) { try { localStorage.removeItem(KEY); for (let k; (k = L.pickLegacySave(kit.manifest, legacyEntries())); ) localStorage.removeItem(k); } catch (e) {} location.reload(); } }
function reset() { if (confirm("Erase every answer you've given in this browser?")) { try { localStorage.removeItem(KEY); } catch (e) {} location.reload(); } }
if (load() && load().consent) start(); else consent();
})();

View file

@ -16,5 +16,3 @@ button:disabled { opacity: 0.4; cursor: default; }
.bar { position: sticky; top: 0; background: var(--bg); padding: 0.5rem 0; border-bottom: 1px solid var(--line); z-index: 1; }
.pair { border: 2px dashed var(--line); border-radius: 10px; padding: 0 0.75rem; margin: 1rem 0; }
small, .hint { opacity: 0.75; }
img.pic { max-width: 100%; height: auto; display: block; margin: 0.5rem 0; }
textarea[readonly] { font: 0.8rem/1.3 ui-monospace, monospace; }

View file

@ -3,9 +3,10 @@
// and whether render peak / rms predicted the ratings. Usage: node analyze.mjs export1.json [export2.json ...]
// Pure functions are exported for test.mjs; the CLI runs only when this file is the entry point.
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { rng, shuffle, dspHash, SCHEMA } from "./logic.js";
import { rng, shuffle, SCHEMA } from "./logic.js";
export const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
export const sd = (xs) => (xs.length < 2 ? NaN : Math.sqrt(xs.reduce((a, x) => a + (x - mean(xs)) ** 2, 0) / (xs.length - 1)));
@ -101,6 +102,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
if (e.schema !== SCHEMA) throw new Error(`${p}: schema ${e.schema}, expected ${SCHEMA}`);
return e;
});
const expectedDsp = await dspHash(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "thruster-trial.dsp"), "utf8"));
const expectedDsp = createHash("sha256").update(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "thruster-trial.dsp"))).digest("hex");
console.log(format(analyze(exports, { expectedDsp })));
}

View file

@ -73,10 +73,6 @@ export async function sha256Hex(text) {
return [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
}
// The DSP identity an export records and analyze.mjs compares: sha-256 of the source text with CRLF folded to LF, so a CRLF
// checkout of the same DSP hashes the same. LF text hashes exactly as before, so exports made before this stay valid.
export const dspHash = (text) => sha256Hex(String(text).replace(/\r\n/g, "\n"));
// answers: [{ A: {rating, word, time, plays}, B: {...} }] aligned with design.
export function buildExport({ seed, design, renders, answers, dspSha256, sampleRate, userAgent, exportedAt }) {
if (!/^[0-9a-f]{64}$/.test(dspSha256 ?? "")) throw new Error("export needs the sha-256 of the DSP source that was rendered");

View file

@ -5,19 +5,14 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { makeDesign, variants, stats, cleanWord, validRating, buildExport, sha256Hex, dspHash, renderVariant, rng, shuffle, SCHEMA, PATCH } from "./logic.js";
import { makeDesign, variants, stats, cleanWord, validRating, buildExport, sha256Hex, renderVariant, rng, shuffle, SCHEMA, PATCH } from "./logic.js";
import { analyze, format, mean, sd, spearman, ranks, pearson } from "./analyze.mjs";
const here = dirname(fileURLToPath(import.meta.url));
const dist = resolve(process.argv[2] ?? join(here, "dist"));
const DSP_SHA = await dspHash(readFileSync(join(here, "thruster-trial.dsp"), "utf8"));
const DSP_SHA = await sha256Hex(readFileSync(join(here, "thruster-trial.dsp"), "utf8"));
let n = 0;
const failed = [];
// A failing test is reported and the run goes on, so a mutation of the patch shows every test it kills, not only the first.
const t = async (name, fn) => {
try { await fn(); n++; console.log(`ok ${name}`); }
catch (e) { failed.push(name); console.log(`FAIL ${name}\n ${String(e.message).split("\n")[0].slice(0, 200)}`); }
};
const t = async (name, fn) => { await fn(); n++; console.log(`ok ${name}`); };
await t("design: every unordered pair once, both positions used, replayable from the seed", () => {
const d = makeDesign(7);
@ -164,31 +159,6 @@ await t("analyze CLI: runs on export files and rejects a foreign schema", async
assert.equal(spawnSync("node", [join(here, "analyze.mjs")]).status, 2);
});
await t("dsp hash: CRLF and LF text hash equal, LF text hashes as plain sha-256 (old exports stay valid), other text differs", async () => {
const lf = readFileSync(join(here, "thruster-trial.dsp"), "utf8").replace(/\r\n/g, "\n");
assert.equal(await dspHash(lf.replace(/\n/g, "\r\n")), await dspHash(lf));
assert.equal(await dspHash(lf), await sha256Hex(lf));
assert.equal(await dspHash(lf), DSP_SHA);
assert.notEqual(await dspHash(lf + " "), await dspHash(lf));
assert.notEqual(await dspHash("a\nb"), await dspHash("a b"));
});
await t("analyze CLI: a CRLF checkout of the same DSP raises no foreign-DSP warning; a changed DSP still does", async () => {
const { execFileSync } = await import("node:child_process");
const { mkdtempSync, writeFileSync, copyFileSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const lf = readFileSync(join(here, "thruster-trial.dsp"), "utf8");
const run = (dsp) => {
const d = mkdtempSync(join(tmpdir(), "trial-crlf-"));
for (const f of ["analyze.mjs", "logic.js"]) copyFileSync(join(here, f), join(d, f));
writeFileSync(join(d, "thruster-trial.dsp"), dsp);
writeFileSync(join(d, "e.json"), JSON.stringify(fakeExport(5, 48000).doc));
return execFileSync("node", [join(d, "analyze.mjs"), join(d, "e.json")], { encoding: "utf8" });
};
assert.doesNotMatch(run(lf.replace(/\n/g, "\r\n")), /WARNING/);
assert.match(run(lf + "// edited\n"), /WARNING/);
});
// --- the patch, through the runtime the page loads ---
const { instantiateFaustModuleFromFile, LibFaust, FaustCompiler, FaustMonoDspGenerator } =
await import(pathToFileURL(join(dist, "vendor/faustwasm/index.js")).href);
@ -291,14 +261,4 @@ await t("patch: the noise knob scales rasp and rattle together at rpm 600 (what
assert.ok(Math.abs(half / full - 0.5) < 0.05, `half/full ${half / full}`);
});
await t("patch: the noise slider is live: noise 20 differs from noise 100 by the rasp-band ratio 0.2 at rpm 4800, while noise 100 stays identical to thruster.dsp", async () => {
const at = (noise) => renderVariant(trial.g, trial.controls, { params: { rpm: 4800, noise } }, SR, 1);
const [x20, x100, ref] = [await at(20), await at(100), await renderVariant(base.g, base.controls, { params: { rpm: 4800 } }, SR, 1)];
assert.ok(maxDiffOf(x100, ref) < 1e-6, `noise 100 vs thruster.dsp: ${maxDiffOf(x100, ref)}`);
assert.ok(maxDiffOf(x20, x100) > 1e-2, `noise 20 and noise 100 must render different signals: ${maxDiffOf(x20, x100)}`);
const r = Math.sqrt(highBandEnergy(x20.samples) / highBandEnergy(x100.samples));
assert.ok(Math.abs(r - 0.2) < 0.03, `rasp band amplitude ratio ${r}, expected 0.2`);
});
if (failed.length) { console.log(`${n} passed, ${failed.length} FAILED`); process.exit(1); }
console.log(`${n} passed`);

View file

@ -3,7 +3,7 @@
// Nothing here makes a network request after the page assets load, and nothing is written to storage.
import { instantiateFaustModuleFromFile, LibFaust, FaustCompiler, FaustMonoDspGenerator } from "./vendor/faustwasm/index.js";
import { controlsOf } from "./ui.js";
import { variants, makeDesign, renderVariant, cleanWord, validRating, buildExport, dspHash, PATCH } from "./logic.js";
import { variants, makeDesign, renderVariant, cleanWord, validRating, buildExport, sha256Hex, PATCH } from "./logic.js";
const $ = (s, root = document) => root.querySelector(s);
const status = (t) => { $("#status").textContent = t; };
@ -39,7 +39,7 @@ async function start() {
const compiler = new FaustCompiler(new LibFaust(await instantiateFaustModuleFromFile("./vendor/libfaust-wasm/libfaust-wasm.js")));
const g = new FaustMonoDspGenerator();
const dspText = await (await fetch(`./${PATCH}.dsp`)).text();
dspSha256 = await dspHash(dspText); // the exact source compiled, so an export names the DSP that produced it
dspSha256 = await sha256Hex(dspText); // the exact source compiled, so an export names the DSP that produced it
if (!await g.compile(compiler, "thruster_trial", dspText, "-ftz 2")) throw new Error(compiler.getErrorMessage());
const controls = controlsOf(JSON.parse(g.factory.json));
for (const v of variants()) {

View file

@ -6,14 +6,14 @@ Generates eight sender voices (aqua, eureka, heimdall, kiko, libby, nibu, void,
- `src/voices.mjs` - the voices and the shared rhythm family (event = rhythm, sender = timbre). Pure JS, deterministic; uses only the sample rate from `../earcon-workshop/web/earcon.js`.
- `src/build.mjs <rawDir>` - renders the 32 clips at unit scale. `src/finish.py <rawDir> <outDir>` - equal A-weighted exposure, Ogg encode, decode-back measurement, manifest, `metrics.json` (needs numpy and soundfile with Vorbis). `src/metriclib.py`, `src/measure.py` - measurements (true peak, A-weighted exposure, onset, end-of-clip checks).
- `src/gen_page.py <publishDir>` - writes `index.html` (no autoplay) from `metrics.json`, `voices.json` and the `inspect_clips.py` output under `findings/`. `src/verify.py [dir]` - checks the files against the limits and manifest schema. `src/inspect_clips.py <rawDir> <outDir> <tag>` - spectrogram + 1 ms envelope PNGs and onset lists for every Void clip, multi-note checks for Nibu. `src/neutral_instrument.test.mjs` - the neutral fallback's instrument id (`NEUTRAL_INSTRUMENT_ID` in `voices.mjs`) is a `DingCatalog` id present in `tools/aqua-feel/lowered-dings/*.dsp`. `src/polyphony.test.mjs` - a clip is the sum of per-note renders and notes do not depend on each other.
- `src/gen_page.py <publishDir>` - writes `index.html` (no autoplay) from `metrics.json`, `voices.json` and the `inspect_clips.py` output under `findings/`. `src/verify.py [dir]` - checks the files against the limits and manifest schema. `src/inspect_clips.py <rawDir> <outDir> <tag>` - spectrogram + 1 ms envelope PNGs and onset lists for every Void clip, multi-note checks for Nibu. `src/polyphony.test.mjs` - a clip is the sum of per-note renders and notes do not depend on each other.
- v3: `renderNote` renders each note in its own buffer with its own noise stream; Libby/Kiko notes that something follows end by the next onset and the last rings; Nibu has three no-glide proposals (`NIBU_PROPOSALS`, encoded under `out/proposals/`); Kiko is struck glass; Void's tick is a soft knock.
- v4: Void has no tick (it was a second hit 95 ms into every note) and a note something follows ends by the next onset; `polyphony.test.mjs` fails if a Void clip has more onsets than notes. Nibu's voice is proposal 3 (the 8 kHz 5-bit sine) for all four events; proposals 1 and 2 stay as alternates under `out/proposals/`, not in the manifest.
- Not here: the rendered clips and the listening page. A staged copy, with the README of its measurements, is at `/opt/commons/handoff/aqua-dings-voices-20261110` on Yggdrasil.
Sound regression guard over every clip this generator and the Earcon Workshop ship (onsets per note, clicks, clipping, true peak, tails, loudness): `python3 tools/sound-guard/guard.py` (see `../sound-guard/README.md`).
Run: `node src/polyphony.test.mjs && node src/neutral_instrument.test.mjs && node src/build.mjs raw && python src/finish.py raw out && python src/verify.py .` (`build.mjs` also renders the four neutral fallbacks, Earcon Workshop `warm-bell` at default sliders with mention=warning, dm=waiting, message=message, invite=done, and `finish.py` equalises them to the same A-weighted exposure as the senders; `out/manifest.json` lists them under `neutral`).
Run: `node src/polyphony.test.mjs && node src/build.mjs raw && python src/finish.py raw out && python src/verify.py .` (`build.mjs` also renders the four neutral fallbacks, Earcon Workshop `warm-bell` at default sliders with mention=warning, dm=waiting, message=message, invite=done, and `finish.py` equalises them to the same A-weighted exposure as the senders; `out/manifest.json` lists them under `neutral`).
## Publishing (one place)

View file

@ -1,16 +1,16 @@
// node build.mjs <rawDir>: render every sender x motif at unit scale to float32 mono WAV (finish.py does loudness, ogg and metrics).
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { SENDERS, MOTIFS, renderClip, VOICES, RHYTHM, NIBU_PROPOSALS, NEUTRAL_INSTRUMENT_ID } from "./voices.mjs";
import { SENDERS, MOTIFS, renderClip, VOICES, RHYTHM, NIBU_PROPOSALS } from "./voices.mjs";
import { SR, renderFamily } from "../../earcon-workshop/web/earcon.js";
const out = process.argv[2]; mkdirSync(out, { recursive: true });
const wav32 = (x) => { const b = Buffer.alloc(44 + x.length * 4); b.write("RIFF", 0); b.writeUInt32LE(36 + x.length * 4, 4); b.write("WAVEfmt ", 8); b.writeUInt32LE(16, 16); b.writeUInt16LE(3, 20); b.writeUInt16LE(1, 22); b.writeUInt32LE(SR, 24); b.writeUInt32LE(SR * 4, 28); b.writeUInt16LE(4, 32); b.writeUInt16LE(32, 34); b.write("data", 36); b.writeUInt32LE(x.length * 4, 40); x.forEach((v, i) => b.writeFloatLE(v, 44 + i * 4)); return b; };
const NAMES = [...SENDERS, ...Object.keys(NIBU_PROPOSALS)];
for (const s of NAMES) for (const m of MOTIFS) writeFileSync(join(out, `${s}-${m}.wav`), wav32(renderClip(s, m)));
// Neutral fallback: the Earcon Workshop identity named by NEUTRAL_INSTRUMENT_ID at default sliders (renderFamily peak-normalises the whole family), one event per motif.
// Neutral fallback: the Earcon Workshop warm-bell identity at default sliders (renderFamily peak-normalises the whole family), one event per motif.
// The mapping is provisional and was chosen for distinctness only (it matches the Ratatoskr handoff b3eb9d01); finish.py equalises these to the sender median.
export const NEUTRAL_EVENT = { mention: "warning", dm: "waiting", message: "message", invite: "done" };
const fam = renderFamily(NEUTRAL_INSTRUMENT_ID);
const fam = renderFamily("warm-bell");
for (const m of MOTIFS) writeFileSync(join(out, `neutral-${m}.wav`), wav32(fam.items.find((it) => it.event === NEUTRAL_EVENT[m]).samples));
writeFileSync(join(out, "voices.json"), JSON.stringify({ voices: Object.fromEntries([...SENDERS.map((s) => [s, VOICES[s]]), ...Object.entries(NIBU_PROPOSALS)].map(([s, v]) => [s, { object: v.object, family: v.family, caption: v.caption }])), rhythm: RHYTHM }, null, 1));
console.log(`wrote ${NAMES.length * MOTIFS.length} raw clips and ${MOTIFS.length} neutral clips to ${out}`);

View file

@ -1,11 +0,0 @@
// node neutral_instrument.test.mjs: the instrument id build.mjs renders for the neutral fallback is a DingCatalog id.
// The catalog's checked-in mirror is tools/aqua-feel/lowered-dings/*.dsp (AquaLower generates it; a dotnet test guards it).
import assert from "node:assert/strict";
import { readdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { NEUTRAL_INSTRUMENT_ID } from "./voices.mjs";
const dir = fileURLToPath(new URL("../../aqua-feel/lowered-dings/", import.meta.url));
const ids = readdirSync(dir).filter((f) => f.endsWith(".dsp")).map((f) => f.slice(0, -4));
assert.ok(ids.length > 0, `no .dsp files in ${dir}`);
assert.ok(ids.includes(NEUTRAL_INSTRUMENT_ID), `neutral instrument "${NEUTRAL_INSTRUMENT_ID}" is not a catalog id (${ids.join(", ")})`);
console.log(`ok: ${NEUTRAL_INSTRUMENT_ID} in catalog mirror {${ids.join(", ")}}`);

View file

@ -7,8 +7,6 @@ import { SR } from "../../earcon-workshop/web/earcon.js";
const TAU = Math.PI * 2;
export const SENDERS = ["aqua", "eureka", "heimdall", "kiko", "libby", "nibu", "void", "weksa"];
export const MOTIFS = ["mention", "dm", "message", "invite"];
// The DingCatalog instrument id whose Earcon Workshop voice build.mjs renders as the neutral fallback; neutral_instrument.test.mjs ties it to the catalog mirror.
export const NEUTRAL_INSTRUMENT_ID = "warm-bell";
// Shared rhythm family: onset times in ms and a rising scale degree (semitones) per onset. Rhythm tells the event:
// mention = one note, message = quick pair, dm = slow pair, invite = long gap then short (an opening, then in).

View file

@ -17,8 +17,6 @@ export const EVENTS = {
waiting: { label: "Waiting", meaning: "Needs you: quiet, sparse, slow low sway, three soft notes", notes: [[0, 0, 0.55], [5, 450, 0.55], [0, 900, 0.55]] },
};
// DEPRECATED as an identity owner (ruled 2026-11-12: DingCatalog owns Dings patch identity; see
// docs/dings-patch-identity-authority-map.md, 'Migration plan'). Kept working; do not add ids or copy catalog values here.
// Timbre identities. rootHz in the calm mid register; fmRatio/fmIndex/fmDecay shape the bell; harmonics > 0 selects the
// additive triangle; attack is seconds. Values start from the Dings catalog instruments and were not tuned by ear.
export const IDENTITIES = {

View file

@ -1,104 +0,0 @@
#!/usr/bin/env python3
"""What the formant numbers do not say. Measures a render for the faults Meta heard in tract-weak-spots-1 (2026-11-13) while every
formant matched its target; it does not listen, and a pass here is not a verdict (the listening page is).
ear_metrics.py FILE.wav [--f0 140] [--steady A B] [--json]
click_ratio largest pitch-period-window peak over the median window peak. A voiced word with no transient is near 1; the pre-fix
nibu (a phone boundary stepping an area) was 3.54 with its window at the /b/ closure (0.271 s); after, 1.76 (a vowel's own pulses).
step_db largest single-sample step, in dB over the median sample step of the voiced part. A cell area that jumps is one sample wide.
bandwidths LPC pole bandwidths (Hz) of the steady part, F1..F3 as (Hz, bandwidth). Natural vowels run about 40-100 Hz at F1, 50-120 at
F2, 80-200 at F3 (Hawks & Miller 1995, Fant 1972); a lossless tube rings narrower, which reads as reedy.
hnr_db harmonics-to-noise ratio of the steady part by autocorrelation at the pitch lag.
hf_db energy above 4 kHz re the total, dB.
"""
import sys, wave, json, argparse
import numpy as np
def wav(path):
with wave.open(path) as w:
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(float) / 32768.0, w.getframerate()
def click_ratio(x, sr, f0):
p = max(8, int(sr / f0))
peaks = np.array([np.abs(x[i:i + p]).max() for i in range(0, len(x) - p, p // 2)])
voiced = peaks[peaks > peaks.max() * 0.02]
if len(voiced) < 4:
return 0.0, 0.0
at = int(np.argmax(peaks)) * (p // 2) / sr
return float(peaks.max() / np.median(voiced)), at
def step_db(x):
d = np.abs(np.diff(x))
live = d[d > d.max() * 1e-3]
return float(20 * np.log10(d.max() / max(np.median(live), 1e-12))) if len(live) else 0.0
def autocorr(s, n=None):
"""Autocorrelation at lags 0..n-1 by FFT (np.correlate is quadratic)."""
n = n or len(s)
f = np.fft.rfft(s, 2 * len(s))
return np.fft.irfft(f * np.conj(f))[:n]
def lpc(s, o):
s = s * np.hamming(len(s))
r = autocorr(s, o + 1)
R = np.array([[r[abs(i - j)] for j in range(o)] for i in range(o)])
a = np.linalg.solve(R + 1e-9 * r[0] * np.eye(o), r[1:o + 1])
return np.concatenate([[1], -a])
def bandwidths(y, sr, order=14):
dec = max(1, int(round(sr / 10000)))
k = np.hanning(4 * dec + 1)
k /= k.sum()
z = np.convolve(y - y.mean(), k, "same")[::dec]
fs = sr / dec
z = np.append(z[0], z[1:] - 0.97 * z[:-1])
rt = np.roots(lpc(z, order))
rt = rt[np.imag(rt) > 0.001]
fq = np.angle(rt) * fs / (2 * np.pi)
bw = -np.log(np.abs(rt)) * fs / np.pi
# a formant is a narrow pole; broad poles (> 400 Hz) are the spectral tilt the all-pole fit spends order on
return [(int(f), int(b)) for f, b in sorted(zip(fq, bw)) if 150 < f < 4500 and b < 400][:3]
def hnr_db(y, sr, f0):
y = y - y.mean()
ac = autocorr(y)
ac /= ac[0]
lo, hi = int(sr / (f0 * 1.3)), int(sr / (f0 * 0.75))
m = float(ac[lo:hi].max())
return 10 * np.log10(max(m, 1e-6) / max(1 - m, 1e-6))
def measure(path, f0=140.0, steady=None):
x, sr = wav(path)
a, b = steady if steady else (len(x) / sr * 0.35, len(x) / sr * 0.85)
y = x[int(a * sr):int(b * sr)]
sp = np.abs(np.fft.rfft((y - y.mean()) * np.hanning(len(y))))
fr = np.fft.rfftfreq(len(y), 1 / sr)
cr, at = click_ratio(x, sr, f0)
return {
"file": path.split("/")[-1], "click_ratio": round(cr, 2), "click_at_s": round(at, 4), "step_db": round(step_db(x), 1),
"bandwidths": bandwidths(y, sr), "hnr_db": round(hnr_db(y, sr, f0), 1),
"hf_db": round(float(10 * np.log10(max((sp[fr > 4000] ** 2).sum(), 1e-20) / (sp ** 2).sum())), 1),
}
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("files", nargs="+")
ap.add_argument("--f0", type=float, default=140.0)
ap.add_argument("--steady", nargs=2, type=float)
ap.add_argument("--json", action="store_true")
a = ap.parse_args()
rows = [measure(f, a.f0, a.steady) for f in a.files]
if a.json:
print(json.dumps(rows, indent=1))
else:
for r in rows:
print(f"{r['file']:20s} click {r['click_ratio']:5.2f} at {r['click_at_s']:.3f}s step {r['step_db']:5.1f} dB hnr {r['hnr_db']:5.1f} hf {r['hf_db']:6.1f} F(Hz,bw) {r['bandwidths']}")

View file

@ -1,39 +0,0 @@
#!/usr/bin/env python3
"""A machine ear for the tract renders: what phone string a speech recogniser reads out of a clip. A PROXY for 'what was heard', never a
verdict: it is trained on natural speech and reads the vowels of this tract poorly (every isolated vowel came back as /i/), so use it
for the events it separates well (a burst read as /v/ against /b/, a nasal present or missing, a consonant that is only a click).
It reproduced three of Meta's four first listening reports on tract-weak-spots-1 before any fix: ba with burst -> 'v ɑ' (she heard
'fah then bah'), ana -> 'v ɑ m ɑ' (a basketball buzzer, no articulation), nibu -> 'i b u' (both consonants clicks, the /n/ missing).
phone_probe.py CLIP.wav...
Needs torch, transformers, scipy and the HuggingFace model facebook/wav2vec2-lv-60-espeak-cv-ft (about 1.2 GB, downloaded once into
HF_HOME). The CTC decode reads vocab.json directly, so the phonemizer library is not needed.
"""
import sys, wave, json
import numpy as np
import torch
from scipy.signal import resample_poly
from transformers import Wav2Vec2ForCTC
from huggingface_hub import hf_hub_download
MODEL = "facebook/wav2vec2-lv-60-espeak-cv-ft"
def phones(model, vocab, path):
with wave.open(path) as w:
sr = w.getframerate()
x = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float32) / 32768
x = resample_poly(x, 16000, sr).astype(np.float32)
x = np.concatenate([np.zeros(4000, np.float32), x, np.zeros(4000, np.float32)]) # silence either side, as speech has
x = (x - x.mean()) / (x.std() + 1e-7)
with torch.no_grad():
logits = model(torch.tensor(x)[None]).logits[0]
ids = logits.argmax(-1).tolist()
out = [vocab[i] for k, i in enumerate(ids) if (k == 0 or i != ids[k - 1]) and vocab[i] != "<pad>"]
return " ".join(out)
if __name__ == "__main__":
model = Wav2Vec2ForCTC.from_pretrained(MODEL).eval()
vocab = {v: k for k, v in json.load(open(hf_hub_download(MODEL, "vocab.json"))).items()}
for p in sys.argv[1:]:
print(f"{p.split('/')[-1]:24s} | {phones(model, vocab, p)}")

View file

@ -1,37 +0,0 @@
#!/usr/bin/env python3
"""burst_spectrum isolates the burst: the difference of a render and its --no-burst twin is zero outside the release, and the peak and
centroid it reports are those of the noise that was added there. python3 tools/formant-check/test_burst_spectrum.py"""
import os, tempfile, unittest, wave
import numpy as np
import weak_spots as w
SR = 48000
def write(root, sub, name, x):
d = os.path.join(root, sub, name); os.makedirs(d, exist_ok=True)
with wave.open(os.path.join(d, name + ".wav"), "wb") as f:
f.setnchannels(1); f.setsampwidth(2); f.setframerate(SR); f.writeframes((np.clip(x, -1, 1) * 32767).astype("<i2").tobytes())
class BurstSpectrum(unittest.TestCase):
def pair(self, tone_hz, release=.24, seconds=.5):
t = np.arange(int(seconds * SR)) / SR
shared = .2 * np.sin(2 * np.pi * 140 * t) # the voiced word both renders share
burst = np.zeros_like(t); a = int(release * SR); n = int(.015 * SR)
burst[a:a + n] = .1 * np.sin(2 * np.pi * tone_hz * t[:n]) * np.hanning(n)
root = tempfile.mkdtemp(); write(root, "out", "w", shared + burst); write(root, "outnb", "w", shared)
return root, release
def test_the_isolated_burst_is_zero_outside_the_release_and_peaks_where_it_was_put(self):
root, release = self.pair(5000)
r = w.burst_spectrum(root, "w", release, 20)
self.assertLess(r["outside_peak"], 1e-4) # 16-bit rounding only
self.assertAlmostEqual(r["peak_hz"], 5000, delta=400)
self.assertAlmostEqual(r["centroid_hz"], 5000, delta=600)
self.assertGreater(r["window_peak"], .05)
def test_a_lower_burst_has_the_lower_peak(self):
lo = w.burst_spectrum(*self.pair(2800)[:1], "w", .24, 20)
hi = w.burst_spectrum(*self.pair(5200)[:1], "w", .24, 20)
self.assertLess(lo["peak_hz"], hi["peak_hz"])
if __name__ == "__main__": unittest.main()

View file

@ -1,144 +0,0 @@
#!/usr/bin/env python3
"""Re-measures the tract voice's four listening weak spots from WordRender outputs. Measures; it does not listen.
weak_spots.py ROOT [--json OUT.json]
ROOT holds: out/<word>/<word>.wav (140 Hz renders: v_<vowel>, v_<vowel>_s with primary stress, ama, ana, bin, bun, ba, nibu, nibu_flat),
out148/v_<vowel> (the five stress vowels unstressed at 148.4 Hz: the f0 rise alone), outnb/<word> (the same word with --no-burst); --burst-sub names the directory of the with-burst bin/ba/bun renders.
A stress: level of the steady part (100-170 ms) of stressed against unstressed vowels, split into the f0 rise alone and the rest.
B /b/ release: burst alone (render minus --no-burst render), its peak and decay against the vowel peak, the closure, the tail.
C nasals: murmur level against the flanking vowels (the steady-part method of verify_renders.py), Burg N1, band levels of m against n.
D lax vowels: Burg F1/F2 of /ɪ/ /ʊ/ against the tube chain and Hillenbrand 1995 / Peterson & Barney 1952 male means.
"""
import sys, os, json, wave, argparse
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import burg_formants as bf
def wav(path):
with wave.open(path) as w:
return np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(float) / 32768.0, w.getframerate()
def rms(x, sr, a, b):
s = x[int(a * sr):int(b * sr)]
return float(np.sqrt((s ** 2).mean())) if len(s) else 0.0
def peak(x, sr, a, b):
s = x[int(a * sr):int(b * sr)]
return float(np.abs(s).max()) if len(s) else 0.0
def db(a, b): return round(20 * np.log10(max(a, 1e-12) / max(b, 1e-12)), 2)
def load(root, sub, name):
return wav(os.path.join(root, sub, name, name + ".wav"))
def burg(root, name, t0, t1):
x, sr = load(root, "out", name)
y = bf.resample(x, sr, 10000); y = np.append(y[0], y[1:] - 0.97 * y[:-1]); fs = 10000
n = int(0.03 * fs); hop = int(0.01 * fs); rows = []
for s in range(int(t0 * fs), int(t1 * fs) - n, hop):
fr = y[s:s + n]
if fr.std() < 1e-6: continue
rows.append(bf.formants(fr, fs, 12)[:4])
return [round(float(np.median([r[i] for r in rows if len(r) > i])), 1) if sum(len(r) > i for r in rows) >= max(3, len(rows) // 2) else None for i in range(3)]
FIVE = ["i", "ah", "u", "e", "o"] # the vowels the test PrimaryStressRendersAboutTwoDecibelsLouderOnAverageOverVowels holds the mean over
HILL = {"ih": (429, 2034), "oo_short": (469, 1123)}
PB = {"ih": (392, 1993), "oo_short": (437, 1023)}
TUBE = {"ih": (346, 1987), "oo_short": (478, 850)} # tube_formants.py at 17.52 cm
def stress(root):
out = {}
for v in FIVE:
x0, sr = load(root, "out", f"v_{v}"); xf, _ = load(root, "out148", f"v_{v}"); xs, _ = load(root, "out", f"v_{v}_s")
l0, lf, ls = (rms(q, sr, .10, .17) for q in (x0, xf, xs))
out[v] = {"total_db": db(ls, l0), "f0_rise_only_db": db(lf, l0), "rest_db": round(db(ls, l0) - db(lf, l0), 2)}
for tag, sel in (("mean_five", FIVE),):
out[tag] = {k: round(float(np.mean([out[v][k] for v in sel])), 2) for k in ("total_db", "f0_rise_only_db", "rest_db")}
out[tag]["total_sd"] = round(float(np.std([out[v]["total_db"] for v in sel])), 2)
xa, sr = load(root, "out", "nibu_flat"); xb, _ = load(root, "out", "nibu")
out["nibu_i_150_250ms_db"] = db(rms(xb, sr, .15, .25), rms(xa, sr, .15, .25))
return out
def release_at(c0, c1):
"""Where a stop's articulators begin to open: StopReleaseStartSeconds in PatchScript.cs (the end less min(12 ms, 0.3 of the gesture))."""
return c1 - min(0.012, 0.3 * (c1 - c0))
def burst(root, name, c0, c1, sub="out"):
"""c0..c1: the b gesture's start and end in seconds; v1: the vowel's steady part after it."""
x, sr = load(root, sub, name); nb, _ = load(root, "outnb", name)
n = min(len(x), len(nb)); d = x[:n] - nb[:n]
vp = peak(x, sr, c1 + .06, c1 + .17)
i = int(np.argmax(np.abs(d))); tpk = i / sr
env = np.array([np.abs(d[k:k + int(.002 * sr)]).max() for k in range(0, n - int(.002 * sr), int(.002 * sr))])
pk = float(np.abs(d).max())
below = [k for k in range(int(tpk * 500), len(env)) if env[k] < pk * .1]
decay_ms = round((below[0] / 500 - tpk) * 1000, 0) if below else None
last = x[int((c1 + .06) * sr):]
rel = release_at(c0, c1)
return {"closure_peak": round(peak(x, sr, c0, rel), 4), "release_peak_full": round(peak(x, sr, rel, c1 + .005), 4),
"burst_peak": round(pk, 4), "burst_peak_ms": round(tpk * 1000), "burst_to_tenth_ms": decay_ms, "vowel_peak": round(vp, 4),
"burst_re_vowel_db": db(pk, vp), "release_peak_re_vowel_db": db(peak(x, sr, rel, c1 + .005), vp),
"burst_rms_in_30ms_after_peak_re_vowel_rms_db": db(rms(d, sr, tpk, tpk + .03), rms(x, sr, c1 + .06, c1 + .17)),
"burst_peak_from_120ms_after_release_to_end": round(peak(d, sr, c1 + .12, n / sr), 4), "burst_diff_samples_nonzero_before_closure_end": int(np.count_nonzero(np.abs(d[:int(rel * sr)]) > 1e-9)),
"file_end_rms_last_100ms": round(rms(x, sr, len(x) / sr - .1, len(x) / sr), 5), "vowel_rms": round(rms(x, sr, c1 + .06, c1 + .17), 4)}
BURST_BANDS = ((0, 1000), (1000, 2000), (2000, 3500), (3500, 7000), (7000, 24000))
def burst_spectrum(root, word, release_s, window_ms=20, sub="out", smooth_hz=400, min_hz=1000):
"""The isolated burst's spectrum: the difference of out/<word> and outnb/<word> (renders with and without release_flow), window_ms from
release_s, Hann windowed. peak_hz is the maximum of the power spectrum smoothed over smooth_hz and searched from min_hz up (a noise
burst has no single line; below 1 kHz the release carries the tract's own low resonance, 430-480 Hz in /ata/ and /apa/, which is not
the place cue: DESIGN choice of the floor), peak_hz_all the same without the floor, centroid_hz the power-weighted mean frequency from
min_hz up, band_db the power in BURST_BANDS (dB, absolute), window_peak the largest sample in the window, outside_peak the largest
sample outside release_s - 5 ms .. release_s + 120 ms (the closure's residue: 0 for a burst that exists only in the window)."""
x, sr = load(root, sub, word); nb, _ = load(root, "outnb", word)
n = min(len(x), len(nb)); d = x[:n] - nb[:n]
a = int(release_s * sr); m = int(window_ms / 1000 * sr); s = d[a:a + m] * np.hanning(m)
nfft = 1 << 14
P = np.abs(np.fft.rfft(s, nfft)) ** 2; f = np.fft.rfftfreq(nfft, 1 / sr)
k = max(1, int(smooth_hz / (sr / nfft))); Ps = np.convolve(P, np.ones(k) / k, mode="same")
up = f >= min_hz
out_mask = np.ones(n, bool); out_mask[max(0, int((release_s - .005) * sr)):int((release_s + .12) * sr)] = False
return {"peak_hz": round(float(f[up][np.argmax(Ps[up])]), 0), "peak_hz_all": round(float(f[int(np.argmax(Ps))]), 0),
"centroid_hz": round(float((f[up] * P[up]).sum() / max(P[up].sum(), 1e-30)), 0),
"band_db": {f"{lo}_{hi}": round(float(10 * np.log10(P[(f >= lo) & (f < hi)].sum() + 1e-30)), 1) for lo, hi in BURST_BANDS},
"window_peak": round(float(np.abs(d[a:a + m]).max()), 5), "outside_peak": float(np.abs(d[out_mask]).max()) if out_mask.any() else 0.0}
def bands(x, sr, a, b, edges=((0, 400), (400, 800), (800, 1600), (1600, 3200))):
s = x[int(a * sr):int(b * sr)]; s = s * np.hanning(len(s))
P = np.abs(np.fft.rfft(s, 1 << 15)) ** 2; f = np.fft.rfftfreq(1 << 15, 1 / sr)
return [float(10 * np.log10(P[(f >= lo) & (f < hi)].sum() + 1e-30)) for lo, hi in edges]
def nasals(root):
out = {}
for w in ("ama", "ana"):
x, sr = load(root, "out", w); c0, c1 = .18, .275
v1, v2 = rms(x, sr, c0 - .08, c0 - .01), rms(x, sr, c1 + .03, c1 + .12)
m = rms(x, sr, c0 + .2 * (c1 - c0), c1 - .2 * (c1 - c0))
out[w] = {"murmur_db": db(m, np.sqrt((v1 ** 2 + v2 ** 2) / 2)), "N1_N2_N3": burg(root, w, .20, .26),
"band_db_0_400_400_800_800_1600_1600_3200": [round(q, 1) for q in bands(x, sr, c0 + .2 * (c1 - c0), c1 - .2 * (c1 - c0))],
"vowel_band_db": [round(q, 1) for q in bands(x, sr, c0 - .08, c0 - .01)]}
out["n_minus_m_band_db"] = [round(a - b, 1) for a, b in zip(out["ana"]["band_db_0_400_400_800_800_1600_1600_3200"], out["ama"]["band_db_0_400_400_800_800_1600_1600_3200"])]
out["n_minus_m_vowel_band_db"] = [round(a - b, 1) for a, b in zip(out["ana"]["vowel_band_db"], out["ama"]["vowel_band_db"])]
return out
def lax(root):
out = {}
for v in ("ih", "oo_short"):
f = burg(root, f"v_{v}", .07, .15)
pct = lambda a, r: round(100 * (a - r) / r, 1)
out[v] = {"burg_F1_F2": f[:2], "tube": TUBE[v], "hillenbrand": HILL[v], "pb": PB[v],
"vs_tube_pct": [pct(f[0], TUBE[v][0]), pct(f[1], TUBE[v][1])], "vs_hillenbrand_pct": [pct(f[0], HILL[v][0]), pct(f[1], HILL[v][1])],
"vs_pb_pct": [pct(f[0], PB[v][0]), pct(f[1], PB[v][1])]}
return out
def main():
ap = argparse.ArgumentParser(); ap.add_argument("root"); ap.add_argument("--json"); ap.add_argument("--burst-sub", default="out", help="subdirectory of ROOT holding the with-burst renders of bin, ba, bun (outpost after the release_flow fix)"); a = ap.parse_args()
res = {"A_stress": stress(a.root), "B_release": {"bin": burst(a.root, "bin", 0, .095, a.burst_sub), "ba": burst(a.root, "ba", 0, .095, a.burst_sub),
"bun": burst(a.root, "bun", 0, .095, a.burst_sub)},
"C_nasals": nasals(a.root), "D_lax": lax(a.root)}
s = json.dumps(res, indent=1, default=float, ensure_ascii=False)
print(s)
if a.json: open(a.json, "w").write(s + "\n")
if __name__ == "__main__": main()