Repository navigation
Component Audio Chain
The audio chain is the browser-side Web Audio path for generated speech and TV static. It glitches each decoded clip on the main thread (pitch jumps, syllable replays, tape wobble), registers three AudioWorkletProcessors, routes the result through them, exposes volume control through a GainNode, and feeds mouth animation by sampling low-frequency analyser energy. It is created by Component-Frontend-App and updates Component-State-Stores through voiceStore.
-
packages/frontend/src/audio/audioChain.tsownsAudioContext, worklet registration, node graph, static playback, volume, mouth-open detection, and disposal. -
packages/frontend/src/audio/glitchEngine.ts(not onmainyet: it ships in PR #78,feat/voice-glitch-episodes, pinned atb8a8832) owns the episode clock and the offline pitch-jump, replay and wobble effects;GLITCH_CONFIGholds every tuned number. -
packages/frontend/src/audio/stutterProcessor.tsis meant to replay a short ring buffer while stuttering. It does not: its read pointer trails the write pointer by one sample, so "stuttering" outputs a one-sample delay. Nothing triggers it, so it is a passthrough. -
packages/frontend/src/audio/eqProcessor.tsadds a fixed bandpass-filtered signal back into the dry signal; its coefficients, not the comments, determine the response. -
packages/frontend/src/audio/staticProcessor.tsinjects short white-noise bursts. -
packages/frontend/src/audio/worklet.d.tsdeclares worklet globals for TypeScript. -
packages/frontend/src/hooks/useAudio.tssubscribes to conversation completion, synthesizes TTS, plays audio, and polls mouth state.
-
interface AudioChaininit(): Promise<void>-
play(audioBuffer: AudioBuffer): number— returns the played length in ms after glitching (0 beforeinit()) stop(): voidsetVolume(level: number): voidgetIsMouthOpen(): booleantriggerStutter(): voidtriggerStaticBurst(): voidplayStatic(durationMs?: number): voidstopStatic(): voiddispose(): void
-
createAudioChain(options?: { glitcher?: Glitcher }): AudioChain— tests inject a seeded glitcher -
createGlitcher(random?: Random): GlitcherandapplyGlitches(samples, sampleRate, mask, random)inglitchEngine.ts interface UseAudioHandle { dispose: () => void; }createUseAudio(audioChain: AudioChain, budget?: ReturnType<typeof createBudgetDegradation>): UseAudioHandle
The processor modules register names rather than exporting functions:
registerProcessor('stutter-processor', StutterProcessor)registerProcessor('eq-processor', EqProcessor)registerProcessor('static-processor', StaticProcessor)
audioChain.play() first runs channel 0 through the glitch engine and builds a
mono buffer from the result. audioChain.init() creates and connects:
AudioBufferSourceNode (glitched clip)
-> stutter-processor
-> eq-processor
-> static-processor
-> AnalyserNode
-> GainNode
-> AudioContext.destination
playStatic() is separate: it creates a looping mono white-noise AudioBufferSourceNode, scales each sample by STATIC_GAIN = 0.11, and connects it directly to the GainNode. The static-only trim is applied before the shared volume gain, so the volume knob still controls both static and speech. Static does not pass through stutter, EQ, static burst, or analyser. Replay ticks (below) also connect straight to the GainNode, so they follow the volume knob but do not open the mouth.
The 0.11 trim is an RMS-derived starting point from decoding the committed greetings in a browser. It is not a LUFS or post-worklet loudness match; speech EQ and glitch processing change the greeting output level, so the value may need subjective listening calibration.
There are no exported AudioParam maps from the worklets. Runtime controls are methods and MessagePort messages:
| Node | Control exposed today | Fixed parameters in code |
|---|---|---|
| Glitch engine | createAudioChain({ glitcher }) |
GLITCH_CONFIG; see § Voice glitch episodes |
stutter-processor |
Port messages { type: 'stutter-start' } and { type: 'stutter-stop' }
|
2,205-sample ring buffer, about 50 ms at 44.1 kHz (replay broken, see Files) |
eq-processor |
None | hard-coded biquad-like coefficients and boostGain = 2.0
|
static-processor |
Port message { type: 'burst' }
|
441-sample burst, burstGain = 0.15
|
playStatic() source |
playStatic() / stopStatic()
|
1-second mono white-noise buffer, sample multiplier STATIC_GAIN = 0.11
|
AnalyserNode |
getIsMouthOpen() reads it |
fftSize = 256, first 8 bins averaged, threshold 100
|
GainNode |
setVolume(level) |
level clamped to [0, 1], 20 ms linear ramp |
The builder heard no pitch shift in the greetings and asked for a more
noticeable, random one, plus replays and speed changes. Four rounds of offline
auditions rendered greeting-015 through the real worklets in headless Edge.
The builder chose Take K by ear, and glitchEngine.ts implements it:
| Setting | Value |
|---|---|
| Base pitch | 1.0 (the Polly voice; the 1.05 pitch-processor was removed) |
| Glitch spell / clean gap | 6–10 s / 10–20 s, alternating, first spell at page load |
| Effects per spell | random non-empty mix of pitch jumps, replays and wobble |
| Pitch jumps | 1.2/s; 40 % down to 0.8–0.9, otherwise up to 1.25–1.6; 120–350 ms; 5 ms crossfade |
| Replays | 0.7/s; last 60–120 ms plays 2–3 times in all; 2 ms fades; skips quiet slices (RMS < 0.02), the first 0.3 s, and 3 slices after each replay |
| Tape wobble | 0.4/s; speed ±12–25 % on a raised cosine over 150–300 ms |
| Replay tick | 441 samples of noise × 0.15 per repeat, scheduled on the GainNode
|
Design choices that matter when changing it:
-
The clock counts played audio, not wall time. One glitcher lives in each
createAudioChain(), so consecutive clips continue the same spell instead of each restarting glitched. Page load starts glitched so the first greeting shows the character. - Clean voice is dry. The granular shifter reads ahead, so a jump at ratio 1.0 returns the exact input sample. Jumps fade in and out without a seam, and the voice between them has no comb or latency. Take K ran the shifter continuously at 1.0, which is slightly different.
-
Effects run offline on the main thread, once per clip, before the
buffer source starts. A 12 s clip at 48 kHz took about 26 ms with all
effects and 5 ms when clean. Replays and wobble change the clip's length, so
play()returns the played duration anduseGreetingcompletes on it.
These numbers were chosen by listening. Change them only after another listening round, not by reasoning about what sounds right.
createUseGreeting() calls audioChain.play(greeting.audioBuffer), so greetings
already use pitch/EQ. The pitch factor is +5%, not an increase in playback
or speaking speed. triggerStutter() and triggerStaticBurst() have no
application call sites: replay and noise bursts stay inactive during normal
greetings. SSML supplies their current onset repetitions.
The EQ comments and research R4 describe a roughly 5 kHz/+6 dB or 4-6 kHz
treatment. Calculating the actual coefficients and dry + 2 * filtered mix
gives a response peak near 3340 Hz / +9.54 dB at 44.1 kHz. Frequency scales
with sample rate; this is not a measured speech loudness boost.
docs/audio-plan.md records raw and reconstructed DSP peak/RMS for the first
T158 auditions and shipped greeting-015. The schwa clip is 16560 ms; its
raw peak is -7.70 dBFS, reconstructed DSP peak at 50% volume -13.29 dBFS.
No tested clip exceeded full scale before volume or at 50%. The reconstruction
used local Edge decoding at 44.1 kHz and current worklet code in 128-frame
blocks, without looping TV noise or triggered bursts. It is not LUFS, true
peak, hardware-output capture or human listening.
A temporary local Vite/Edge check served the private schwa MP3 and started playback through the app's native worklet chain, then stopped both helpers. The builder defers adding greeting replay/static triggers until base pacing is accepted. No DSP settings or trigger wiring changed in this audition.
A headless Edge probe of the Vite dev app instrumented AudioNode.connect
and recorded AudioBufferSourceNode -> stutter-processor for the greeting:
a 9.58 s mono buffer through all four worklets in a 48 kHz context. The
tuning static went straight to GainNode, as designed.
Replies take a different path. synthesizeTurn() returned textOnly: true
because new PollyClient({}) in pollyTts.ts has no region and throws
Region is missing before any request. useAudio then falls back to
browserTts.speak(), which uses speechSynthesis with pitch = 1.2 and
a browser-chosen voice. That path is outside Web Audio, so no stutter,
pitch, EQ or analyser processing applies. Every current reply uses this
fallback, locally and when deployed.
The greeting's +5% pitch (since removed) measured about +0.9 semitone in a sine test of the worklet code at 44.1 and 48 kHz. It is a subtle timbre shift, not an audible "pitch-shifted" voice. Next to fallback replies, which use a different voice and native pitch, greetings can sound unprocessed even though they are processed.
Spec 003 retires this path: server-side Polly audio events (T029/T036),
played by useAudio (T033/T041); T081 deletes browser TTS. Spec 003 never
names the audio chain, so T033 should assert routing through
audioChain. play() stops the current source on every call, so
sequential segments need queuing rather than playback on arrival. Replies
routed this way get the glitch engine too, since it runs inside play().
Until 2da4328, init() loaded each processor with
new URL('./xProcessor.ts', import.meta.url). In vite build this becomes a
data:video/mp2t;base64,… URL holding the raw TypeScript source. The
.ts extension is read as an MPEG transport stream, and the file is not
compiled. Probed in headless Edge with the eq processor source:
- as built,
addModulefails withAbortError: Failed to load worklet module script; - with a JavaScript MIME type, it fails with
SyntaxErroron theprivatefields.
So init() rejects in production. App.tsx logs it, play() then returns
0, and greetings finish silently on the manifest timer. Only pnpm run dev
compiles the worklets, which is why local listening works. This predates the
glitch engine; the engine itself runs on the main thread but needs the chain
to be heard.
The fix (spec 003 T177, #76): audioChain.ts imports each processor as
./xProcessor.ts?worker&url. Vite then bundles it as a separate entry and
emits a compiled IIFE at /assets/xProcessor-<hash>.js. That URL is
same-origin, so CSP script-src 'self' allows it.
packages/frontend/tests/audio/workletAssets.test.ts runs a real
production build and fails if any output holds a data:video/mp2t URL or a
.ts file, or if any of the three processors is missing as its own compiled,
referenced script. It failed first for exactly those reasons. It has not yet
been heard in a deployed browser (T174).
Two traps for anyone touching this:
- A bare
new URL('./x.ts', import.meta.url)looks right and works in dev. Only the production build reveals the problem. - Do not put a test in a
tests/build/folder: the repo.gitignoreignores everybuilddirectory, sogit addsilently skips it.
createUseAudio() subscribes to useConversationStore. When it observes isStreaming transition from true to false with non-empty currentResponseText, it processes that turn once by currentTurnIndex.
Normal path:
- Set
useVoiceStore.getState().setSpeaking(true). - Call
synthesizeTurn(text). - Decode
audioDatain a temporaryAudioContext. - Call
audioChain.play(audioBuffer). - Poll
audioChain.getIsMouthOpen()every 50 ms and writesetMouthOpen(isOpen).
Deployment dependency: synthesizeTurn uses a browser-side Polly client,
but the CloudFront CSP in frontend-stack.ts does not allow Polly in
connect-src. Once this path has credentials and is deployed, the browser
would block the Polly request; no deployment has tested it yet. The exact
voice endpoint and CSP must be reconciled in spec 003's plan. See
Component-Infra-Stacks. A browser-TTS fallback is not an approved
workaround for the P1 cloud-only requirement.
Fallback path uses browser speech synthesis when budget degradation is in browser_tts mode, when Polly returns text-only, or when Polly throws and browser TTS is available.
Constitutional status: this describes existing fallback code, not an approved P1 exception. P1 requires all TTS on AWS; browser speech remains an unresolved conflict for the next spec. See Decision-Browser-TTS-Fallback and Concept-Cloud-Only-Inference.
Two properties worth knowing before any TTS provider is reconsidered, both visible in the graph above:
-
The chain's input is a decoded
AudioBuffer. Nothing in the glitch engine, stutter, EQ or static knows where the audio came from. Max's voice character is therefore portable to any source of PCM, not tied to Polly. -
Mouth animation reads the
AnalyserNode, not viseme marks. The MVP mouth is an energy threshold over the first 8 FFT bins. The viseme marks Contract-Polly-TTS fetches and stores are unused here, and are held for V1 3D lip-sync.
Together these split the migration question in two: swapping TTS keeps the character effects and the MVP mouth, and costs the V1 lip-sync path. See Source-Nova-Sonic.
-
createUseAudio()starts mouth polling afteraudioChain.play(), but no callback fromAudioBufferSourceNode.onendedstops polling or resetsisSpeakingwhen speech finishes.dispose()stops polling, and error/browser fallback paths reset speaking, but the successful audio-buffer path does not. -
audioChain.play()is a no-op beforeinit()has completed and returns 0; callers must initialize first. - Never time speech from a manifest or source duration. Glitches change the clip's length; use the ms that
play()returns. - Worklets must be imported with
?worker&url. A barenew URL('./x.ts', import.meta.url)ships raw-TypeScriptdata:URLs that browsers reject (above). -
triggerStutter()always schedulesstutter-stopafter 80 ms and also triggers a static burst. -
setVolume()before initialization is buffered inpendingVolumeand applied after nodes exist.
- Concept-Cloud-Only-Inference
- Concept-Budget-Ceiling
- Concept-Personality-Gate
- Concept-IP-And-Legal-Posture
- Concept-Supply-Chain-Discipline
- Concept-Graceful-Degradation
- Concept-Observability
- Concept-Testing-And-TDD
- Concept-Credential-Hygiene
Editing in the browser? Wiki edits are live and bypass wiki:lint. Read
Guide-Wiki-Contributing first.