# 07 — Voice and audio (VOX): microphone, speech recognition, TTS, voice effects, subtitles, music detection, call audio Source of truth: CapriCore 1.0.4 tree at `~/Capri` (read-only). All paths below are relative to that root unless stated otherwise. Capri uses a single *install root* that holds `config/`, `integrations/`, `data/`, `logs/` and `.runtime/`; the Rust port should keep that layout (the Python TTS sidecar depends on it, see §10). Conventions: `file:line` references point at the 1.0.4 sources. "Host" = the Electron main process, "renderer" = the companion web page; in the Rust app both collapse into one process (plus sidecars). Feature IDs are stable: `VOX-xx`. --- ## 1. Purpose and scope This spec covers everything that captures, recognizes, synthesizes, plays, transforms or classifies audio in Capri: | Area | Capri files | Rust module (proposed, §10) | |---|---|---| | Microphone session, wake gate, transcript routing, echo guard | `apps/desktop/microphone-service.mjs`, `apps/desktop/wake-phrase.mjs`, `apps/desktop/voice-follow-up.mjs` (consumed), `apps/desktop/renderer/microphone.mjs`, `renderer/microphone-worklet.mjs`, `renderer/microphone-button.mjs`, `renderer/wake-feedback.mjs` (consumed), `main/companion-ipc.mjs:31-157` (wake audio, consumed) | `capri-mic`, `capri-wake` | | Microphone device selection | `apps/desktop/audio-input-settings.mjs` | `capri-audio-io` | | ASR worker protocol and runtime | `apps/desktop/asr-worker.mjs`, `integrations/asr_runtime/{worker,protocol,model,recognition,vocabulary,alignment,shared_encoder}.py`, `integrations/multilingual.py`, `config/{companion-asr,asr-vocabulary,asr-model-upstream,asr-vad-upstream,multilingual-candidates,multilingual-runtime}.json`, `config/asr-requirements.lock.txt` | `capri-asr` | | Speech-pause setting | `renderer/speech-settings.mjs`, `renderer/speech-panel.mjs` | `capri-mic` | | TTS client (sentence queue) | `apps/desktop/voice-service.mjs`, `renderer/speech-text.mjs` | `capri-tts` | | TTS sidecar (Python, kept) | `integrations/voice_runtime/*` (+ `host.mjs`, `readiness.mjs`, `environment.mjs`, `startup-error.mjs`), `integrations/voice_training/*` (summary), `config/{companion-voice,tts-catalog,voice-runtime,voice-upstream,voice-model-download,qwen-tts-upstream,voice-training,voice-evaluation.en}.json`, `config/requirements-*.lock`, `config/voice-*-overrides.txt`, `config/voice-pytorch-*.constraints.txt` | `capri-tts::sidecar` | | Voice catalog, residency, training, install | `apps/desktop/voice-catalog-service.mjs`, `voice-residency.mjs`, `voice-training-service.mjs`, `speech-install-service.mjs`, `packages/runtime/src/voice-settings.mjs`, `packages/runtime/src/hardware/voice-gpu.mjs`, `packages/installer/src/{speech-components,voice-catalog-prepare,voice-pack}.mjs` (followed imports), `tools/setup/*.ps1|*.py` (followed) | `capri-tts::catalog`, `capri-speech-install` | | Playback, effects, level meter | `renderer/voice-player.mjs`, `renderer/voice-effects.mjs`, `renderer/voice-effects-settings.mjs`, `renderer/voice-effects-panel.mjs`, `renderer/voice-model-panel.mjs` | `capri-player`, `capri-fx` | | Subtitles | `renderer/subtitles.mjs`, `renderer/subtitle-controller.mjs` | `capri-subtitles` | | Music listening | `apps/desktop/{music-listening-service,music-listening-settings,music-audio-capture,music-detector-provision,music-artwork}.mjs`, `renderer/{system-music-capture,music-worklet,music-listening-panel}.mjs`, `integrations/music_runtime/{worker,features,tempo}.py`, `config/music-detector.json` | `capri-music` | | System audio into ASR | `apps/desktop/system-audio-capture.mjs`, `renderer/microphone.mjs:115-210` | `capri-mic` | | Call audio | `apps/desktop/{call-audio-setup,call-response,virtual-cable-installer}.mjs`, `main/{call-audio,call-audio-diagnostics}.mjs`, `renderer/{call-audio-route,call-audio-settings,call-microphone}.mjs`, `integrations/call-audio/CableDefaults.cs` | `capri-call` | | Wiring | `apps/desktop/main.mjs` (lines cited per feature), `apps/desktop/preload.cjs:18-205` (IPC surface) | app crate | Out of scope (other specs, only interfaces listed in §9): chat/turn production, avatar rendering (mouth plates `renderer/avatar-mouth.mjs`, music poses/notes `renderer/music-animation.mjs`), language-settings model, reminders, the settings-window framework, response-timing telemetry, window raising. **Current Linux state (observed, not designed):** none of the owned files carry `FWS-LINUX-BRIDGE` patches. On the owner's machine ASR and TTS run only because of hand-made shims (`.runtime/asr-venv/Scripts/python.exe -> ../bin/python`, `.runtime/voice-training-venv/Scripts/python.exe -> ../bin/python`, `.runtime/asr-venv/Lib/site-packages -> ../lib/python3.11/site-packages`) and a manual uv setup (`.runtime/asr-setup.log`, `.runtime/voice-setup.log`, `.runtime/voice-server-test.log` show Parakeet/Silero/Whisper verified and "Capri voice ready on loopback port 8101" with torch 2.7.1+cu128 on an RTX 5070 Laptop GPU). Music listening, system audio and call audio are hard-disabled by `process.platform === 'win32'` gates (`music-listening-service.mjs:98`, `music-audio-capture.mjs:11`, `system-audio-capture.mjs:11`, `main.mjs:1337-1359`). The in-app speech installer fails (see VOX-34). --- ## 2. Feature catalog Priority legend: **P0** core (companion broken without it), **P1** expected by a Capri user, **P2** optional/niche. ### 2.1 Microphone and speech recognition #### VOX-01 — Microphone session lifecycle · P0 Source: `microphone-service.mjs:60-314,527-533`; `main.mjs:5942-5969,6160-6178`; `renderer/microphone.mjs:39-114,268-299`. - Host state machine `status`: `off → starting → arming → listening → off`. Every start creates a *capture* `{id: uuidv4, generation, sequence:0, interrupted:Set, finalized:Set, waiting:0, latestUtterance:-1, discardedThrough:-1, recognitionPhase:'idle', inputGeneration:0, followUps:0, wake: WakePhraseGate}`; `generation` is a monotonically increasing integer bumped by every start/stop/close so late results/packets from a previous capture are ignored. - `start()` is idempotent (returns the current snapshot if a capture exists). It publishes `starting`, sends worker `start {sessionId, attention: !wakeWord.enabled, trailingSilenceSeconds}` (this lazily spawns/loads the recognizer), and on ack moves to `arming` unless the generation changed (`'Microphone start cancelled'`). Failure → `recognizerFailed(error, startup=true)` then rethrow. - `confirm(id)` (renderer calls it after its audio graph is wired, IPC `capri:microphone-ready`) requires `status==='arming'` and the same id, else throws `'Inactive microphone'`; sets `listening`. - Host preconditions for `capri:microphone-start` (`main.mjs:5942`): speech installer not busy (`'Wait for speech installation to finish, or cancel it in Languages.'`); recognition allowed and installed for the current recognition language, not shutting down, backend phase `ready` or `asleep`, else `'The selected speech recognition model is unavailable. Run setup-multilingual.cmd.'`. Returns `{...snapshot, sessionId, deviceId, deviceLabel}`. Side effect: if companion `wakeSound==='voice'`, awake, no chat turn, voice not generating and no playback → prepare the cached wake voice in background (VOX-15). - Renderer start order: AudioContext at 16 kHz (fallback: default rate), `resume()`, `startMicrophone`, `getUserMedia` (VOX-02 constraints), track `ended` → stop + `'The microphone disconnected. Choose an available device in Menu → Microphone input.'`, load worklet, graph `source → micGain → worklet → silence(gain 0) → destination` (worklet output always zero: the mic is never monitored), `microphoneReady(id)`, then state `listening` with `actualDeviceLabel`. Any await that finds the run replaced releases what it acquired (tracks stopped, `stopMicrophone(run.id)`). - Renderer error mapping: `NotAllowedError` → `'Microphone access was denied. Check Windows microphone access for desktop apps.'`; `NotFoundError|NotReadableError|OverconstrainedError` → `'The selected microphone is unavailable. Choose a device in Menu → Microphone input.'`; anything else → `'Speech recognition could not start. Check the selected language and setup-multilingual.cmd.'`. - `stop(id?)`: no-op `false` if `id` given and not current. Closes wake timers, clears capture, bumps generation, `status='off'`, new EchoGuard, publishes `microphone.settings {…, stoppedSessionId}`, and (if a worker process exists) sends `stop {sessionId}` ignoring errors. - IPC `capri:microphone-stop` accepts `{id?, keepModelWarm?: boolean}` or a bare id (`main.mjs:6167`); if stopped and `!keepModelWarm` the recognizer process is closed (frees ~1-3 GB RAM). The composer mic button stops with `keepModelWarm=true`; the header button is the "master switch" that also unloads (`renderer/microphone.mjs:31-38`: toggle → stop if running; else if `modelLoaded` → unload; else start). - The microphone is **off at every launch** (nothing persisted). Recognition-language change (`main.mjs:6197-6234`) stops capture, closes the worker and requires re-enabling. Device change stops capture and emits `microphone.device-changed {deviceId, deviceLabel, restart}`; the renderer restarts if `restart`. - Sleep (`main.mjs:2343-2436`): unloading keeps an *already enabled* CPU microphone alive (so wake phrases still work); otherwise the worker is closed. On wake-up the recognizer is pre-started (startup step `recognition`) only if capture is active. #### VOX-02 — Capture format and framing · P0 Source: `renderer/microphone.mjs:6-17`, `renderer/microphone-worklet.mjs:2-58`. - Constraints: mono, `echoCancellation:true`, `noiseSuppression:false`, `autoGainControl:false` (recognition needs unprocessed quiet syllables), `deviceId:{exact:id}` when a specific device is saved, otherwise the system default. - `PCMFramer(inputRate, 16000, 1600)`: box-integration resampler (each output sample = mean of the input interval of length `inputRate/16000`), non-finite → 0, clamp to [-1, 1]; emits frames of **1600 samples = 100 ms of f32 LE mono @16 kHz** with `rms = sqrt(Σx²/1600)`. Must be continuous across render-quantum boundaries (tested at 16/44.1/48 kHz). - Level meter: `min(1, rms*10)` drives the transcript-preview and wake-feedback CSS level. - Rust/Linux: open a PulseAudio record stream `float32le/16000/1ch` on the selected source (PipeWire/PulseAudio resamples server-side), fragment 1600 frames. Keep `PCMFramer` for backends that cannot resample (cpal/ALSA). #### VOX-03 — Audio transport and backpressure · P0 Source: `renderer/microphone.mjs:3,211-254`; `microphone-service.mjs:336-377`. - Renderer FIFO: max **50 frames (5 s)**; overflow → stop + `'Microphone audio could not keep up. Enable the microphone to retry.'`. Pump sends at most 2 frames concatenated (≤12 800 bytes = 200 ms) per message, never waits to fill a batch, increments `sequence` per message. `{accepted:false}` → silent stop; exception → stop + `'The speech recognizer stopped. Enable the microphone to retry.'`. - Host validation: packets for no/other capture or not `listening` → `{accepted:false}` quietly (late packets after stop/language change must neither reach ASR nor fault a newer capture). Otherwise require `sequence === expected`, `pcm` byte array of 1..12 800 bytes, length % 4 == 0, and at most **2 packets in flight**; violation → `fail('Microphone audio could not be delivered reliably. Restart the microphone.')` and error. Transport errors record `lastFailure {at, code: error.code ?? 'ASR_TRANSPORT', message: ≤300 chars}` and fail with the worker's message (if it has a code) or `'Recognition could not keep up. Restart the microphone.'`. - Rust: capture thread → bounded channel (50 frames) → recognizer; same overflow behavior; keep `{sessionId, sequence}` tokens on every frame. #### VOX-04 — Microphone device selection · P1 Source: `audio-input-settings.mjs:1-114`; `main.mjs:874,3574-3605,3663-3709`. - Persisted file `data/desktop/microphone.json` (§3). `''` means system default. A corrupt file is ignored (defaults used) and **not overwritten** until the user explicitly selects a device. - `update(devices)`: ≤128 entries else error; keep `kind==='audioinput'`, id string ≤512 chars without control chars, non-empty. Entry `default` only provides the default label: `'System default — ' + label.replace(/^Default\s*[-–—]\s*/i,'')`. Skip `communications` and duplicates. Labels: control chars → space, trim, ≤180 chars, fallback `Microphone N`. - `describe(id)`: `'default'`→`''`; unknown id → `'That microphone is unavailable. Reopen the menu to refresh the list.'`. `select(id)` writes only when changed. - Menu (tray/context): radio items "System default…" + devices; a saved-but-absent device is shown checked and disabled as `Unavailable —