Skip to content

Architecture

buntatoes edited this page Nov 29, 2026 · 1 revision

Architecture

Tonic is organized as a modular, zero-dependency pure-Zig codebase (src/) that compiles both native Linux host artifacts (tonic, libtonic.so) and freestanding multi-architecture Windows PE sapi.dll binaries (x86_64-windows, i386-windows, aarch64-windows) from the same core DSP, grammar, and COM modules.


High-Level Pipeline

Windows Game / App (under Vodka / Pisco)            Native Linux Consumer
  │  CoCreateInstance / DllGetClassObject             │  CLI (`tonic`) or C ABI (`libtonic.so`)
  ▼                                                   ▼
sapi.dll  (src/sapi/dllmain.zig)                    src/cli/main.zig  /  src/root.zig
  ├── COM ABI & Vtable Guards  (src/com/abi.zig)
  ├── ISpVoice                 (src/sapi/voice.zig)
  │     ├── SSML / SAPI XML Parser   (src/tts/ssml.zig)
  │     ├── Text Normalizer & G2P    (src/tts/phonemes.zig)
  │     ├── Klatt Formant Synth      (src/tts/synth.zig)
  │     └── Playback: ISequentialStream │ dynamic winmm.dll waveOut │ optional libspeechd.so.2
  ├── ISpRecognizer / Context / Grammar / Result  (src/sapi/recognizer.zig, result.zig)
  │     ├── SRGS / SAPI XML / Phrase Parser       (src/asr/srgs.zig)
  │     ├── 512-pt FFT + 26-dim CMVN/Delta MFCC   (src/asr/mfcc.zig)
  │     ├── Adaptive VAD + Multi-Rate Banded DTW  (src/asr/grammar.zig)
  │     └── Capture: dynamic winmm.dll waveIn (16 kHz) │ EmulateRecognition │ direct PCM feed
  ├── ISpNotifySource Engine   (src/sapi/notify.zig)
  │     └── Win32 Event │ PostMessageW │ Callback Fn │ ISpNotifyCallback │ ISpNotifySink
  └── Object Tokens & Per-Game Registry  (src/sapi/token.zig, src/game_fixes.zig)

Module Map

Module Path Responsibility
Root & C ABI src/root.zig Aggregates all submodules, defines VERSION (0.1.0-dev), and exports libtonic.so C ABI symbols (tonic_version, tonic_sample_rate, tonic_synthesize_pcm16, tonic_free_pcm16).
COM ABI src/com/abi.zig 16-byte Guid, HResult (COM + SAPI SPERR_*), atomic ComRefCount, IUnknown/IClassFactory vtables, comptime vtable slot/count assertions, and documented SAPI 5 CLSIDs/IIDs.
Text & G2P src/tts/phonemes.zig English text normalizer, abbreviation expander, 42-phoneme ARPAbet-style inventory with acoustic formant tables, diphthong glide targets, exception lexicon, and rule-based G2P.
Formant TTS src/tts/synth.zig 22050 Hz Klatt-style 3-formant cascaded biquad synthesizer, Rosenberg glottal pulse, 32-bit Galois LFSR noise source, SAPI rate/volume/pitch controls, and 44-byte RIFF WAV serializer.
SSML / SAPI XML src/tts/ssml.zig Bounded segment parser for W3C SSML and SAPI 5 XML prosody/silence tags (<rate>, <volume>, <pitch>, <prosody>, <break>, <silence>).
MFCC Frontend src/asr/mfcc.zig Iterative 512-point Radix-2 FFT, pre-emphasis, Hamming window, 26-band triangular Mel filterbank, log energy, DCT-II, per-utterance CMVN (C1..C12), and first-order Delta MFCCs (26-dim feature vectors).
SRGS / SAPI Grammar src/asr/srgs.zig Bounded parser and phrase expander for W3C SRGS XML, Microsoft SAPI 5 XML, UTF-8/UTF-16LE encodings, and plain phrase lists, with safe binary CFG detection.
Grammar ASR src/asr/grammar.zig GrammarRecognizer with multi-rate synthetic or caller-supplied templates, adaptive 20th-percentile noise-floor VAD, Sakoe-Chiba banded DTW, and [0.0, 1.0] confidence scoring.
Linux Host Bridge src/host/bridge.zig Optional runtime dlopen("libspeechd.so.2") probe for Linux speech-dispatcher when TONIC_NO_HOST_SPEECH is unset, falling back cleanly to the built-in formant engine.
SAPI 5 Frontend src/sapi/ dllmain.zig, root.zig, types.zig, token.zig, notify.zig, voice.zig, recognizer.zig, result.zig, and winmm_audio.zig implementing the Windows PE sapi.dll COM layer and dynamic Win32 plumbing.
Native CLI src/cli/main.zig Standalone Linux tonic executable (info, speak, recognize, --version, --help) with built-in 16-bit RIFF WAV decoder/encoder.
Per-Game Fixes src/game_fixes.zig Isolated per-executable compatibility flag registry so game-specific workarounds never regress general SAPI 5 behavior.

Text-to-Speech Pipeline (src/tts/)

1. Text Normalization & Grapheme-to-Phoneme (phonemes.zig)

Raw ASCII/UTF-8 English text passes through normalizeText before phoneme expansion:

  • Numbers: Integer tokens in 0..999 are expanded to spoken English words (e.g., 42 -> "forty two", 305 -> "three hundred five"). Digit sequences of 4 or more digits are expanded digit-by-digit.
  • Abbreviations: Dotted titles/terms (Mr., Mrs., Ms., Dr., St., vs., etc.) and common gaming/technical abbreviations (fps, hp, xp, km, ok) expand to full spoken forms.
  • Prosodic Punctuation: Commas, semicolons, and colons map to .PAUSE_SHORT (95 ms nominal); periods, exclamation marks, and question marks map to .PAUSE_LONG (190 ms nominal); word boundaries map to .SIL (60 ms nominal).
  • 42-Phoneme Inventory (PHONEME_COUNT = 42): Covers silence/pauses (SIL, PAUSE_SHORT, PAUSE_LONG), 10 monophthong vowels, 5 diphthongs (AW, AY, EY, OW, OY), 3 nasals, 4 liquids/glides, 6 voiced/unvoiced stops, 9 voiced/unvoiced fricatives and aspirate (HH), and 2 affricates (CH, JH).
  • Exception Lexicon + Rule-Based G2P: textToPhonemes checks a 37-word high-frequency exception lexicon (function words, digits, and common command words like fire, reload, shield, ready) before falling back to wordToPhonemesRuleBased, which handles suffixes/trigraphs (tion/sion, igh, tch, trailing ing), consonant and vowel digraphs, doubled-consonant collapsing, silent trailing e, and context-sensitive c/g/y.

2. Klatt-Style Formant Synthesizer (synth.zig)

synthesizePhonemesF32 renders mono audio at 22050 Hz (SAMPLE_RATE = 22050):

  • Glottal & Noise Excitation:
    • Voiced segments use a smooth Rosenberg-style glottal pulse (t_open = 0.46, t_close = 0.62) differentiated sample-to-sample (* 1.4) to model +6 dB/octave lip radiation.
    • Pitch contour (base_pitch_hz = 125.0 Hz, scaled by pitch_scale in [0.45, 2.5] and clamped to [55, 420] Hz) applies natural statement declination (1.06 -> 0.88), a rising tail on the final 28% of questions (?), and subtle 5 Hz (+/- 0.8%) micro-prosody vibrato.
    • Unvoiced and fricative excitation uses a deterministic 32-bit Galois LFSR (0xACE1_BEEF, tap 0xB400_0001).
  • 3-Stage Cascaded Formant Resonators:
    • Excitation feeds three Direct Form II Transposed second-order unity-DC biquad resonators (F1 -> F2 -> F3).
    • Resonator center frequencies and bandwidths interpolate smoothly every 32-sample control hop (~1.45 ms, smooth_alpha = 0.22) across phoneme boundaries and diphthong glides (AW -> UW, AY -> IY, EY -> IY, OW -> UW, OY -> IY) to prevent clicks.
    • Stop consonants (B, D, G, P, T, K, CH, JH) apply a brief damped closure over the first 45% of the segment followed by a release burst across 45%..68%.
  • Rate, Volume & Post-Processing:
    • SAPI rate (-10..+10) scales speaking speed via 1.10^rate (~0.35x at -10, 1.0x at 0, ~2.6x at +10), with a 18 ms minimum phoneme floor.
    • Output passes through a ~60 Hz DC-blocking high-pass filter, boundary fade-in/fade-out (128 / 160 samples), linear SAPI volume gain (0..100), and a soft tanh limiter before optional conversion to 16-bit signed PCM and 44-byte RIFF WAVE packaging (writeWav16).

3. SSML & SAPI 5 XML Prosody (ssml.zig)

parseSsml splits XML markup into ordered .speech and .silence_ms segments with a nesting stack bounded to MAX_NESTING_DEPTH = 32 and silences capped at MAX_SILENCE_MS = 10_000 ms:

  • SAPI 5 XML Tags: <rate absspeed="..." speed="..."/>, <volume level="..."/>, <pitch absmiddle="..." middle="..."/>, <silence msec="..."/>.
  • W3C SSML Tags: <prosody rate="..." volume="..." pitch="..."> (supporting named levels like x-slow/fast, soft/loud, low/high, percentages, semitones st, and Hz offsets) and <break time="...ms|...s" strength="none|x-weak|weak|medium|strong|x-strong"/> (defaulting to 250 ms).
  • Text Handling: Skips XML comments (<!-- ... -->) and processing instructions (<? ... ?>), and decodes standard XML entities (&amp;, &lt;, &gt;, &quot;, &apos;).

Finite-Grammar Speech Recognition Pipeline (src/asr/)

1. Acoustic Feature Extraction (mfcc.zig)

extractFeatures converts arbitrary-rate mono PCM (such as 16000 Hz microphone capture or 22050 Hz synthesized templates) into 26-dimensional acoustic feature frames (FeatureFrame):

  1. Framing & Windowing: 10 ms frame hop (sample_rate / 100), 25 ms analysis window (clamped to FFT_SIZE = 512), 0.97 pre-emphasis filter, and Hamming window.
  2. Spectrum & Mel Filterbank: In-place 512-point iterative Radix-2 Cooley-Tukey FFT (HALF_FFT = 257 power bins) projected through a 26-band triangular Mel filterbank spanning 80 Hz to min(sample_rate / 2, 8000 Hz).
  3. Cepstrum & CMVN: Log energy (1e-10 floor) followed by DCT-II produces 13 static MFCCs (C0..C12). Per-utterance Cepstral Mean and Variance Normalization (CMVN) normalizes C1..C12 to zero mean and unit variance for speaker, microphone EQ, and gain invariance.
  4. Temporal Deltas: First-order regression Delta MFCCs (N = 2, denominator 10.0) append 13 dynamic coefficients (ΔC0..ΔC12) to capture formant transitions.

2. Grammar Parsing (srgs.zig)

parseGrammar accepts UTF-8 (with or without BOM) and UTF-16LE (with or without BOM) input and expands finite command sets under strict safety limits (max_phrases = 256, max_depth = 16):

  • W3C SRGS XML: <grammar root="...">, <rule id="...">, <one-of>, <item> (including repeat="0-..." optional branches), and <ruleref uri="#..."/>.
  • Microsoft SAPI 5 XML: <GRAMMAR>, <RULE NAME="..." TOPLEVEL="ACTIVE|INACTIVE">, <L> (alternatives), <P> (sequence), <O> (optional), and <RULEREF NAME="..." REFID="..."/>.
  • Plain Phrase Lists: Newline-separated phrases ignoring empty lines and # comment lines.
  • Safety Guards: Ignores non-phrase semantic/metadata subtrees (<tag>, <meta>, <lexicon>, <dictation>, <wildcard>), deduplicates expanded phrases case-insensitively, terminates cyclic <ruleref> graphs cleanly via max_depth/max_phrases, and detects compiled binary SAPI CFG blobs via isLikelyBinaryGrammar so binary blobs return zero phrases safely instead of crashing.

3. Adaptive VAD & Multi-Rate Banded DTW (grammar.zig)

GrammarRecognizer matches spoken utterances against active grammar rules:

  • Multi-Rate Acoustic Templates: Calling addPhrase or loadGrammar synthesizes three acoustic templates per phrase at SAPI rates -2, 0, and +2 (~0.83x, 1.0x, and ~1.21x duration), trims silence, and extracts 26-dim CMVN + Delta features. Callers can also supply recorded PCM templates directly via addPhraseWithTemplateF32.
  • Adaptive Noise-Floor VAD (trimSilenceVad): Computes RMS energy over 10 ms blocks, samples up to 512 blocks to estimate the 20th-percentile background noise floor, rejects pure silence (peak_rms < 0.005) and steady stationary noise (noise_floor > 0.004 with peak-to-floor ratio < 1.75), and trims leading/trailing silence with 20 ms pre-pad and 30 ms post-pad.
  • Sakoe-Chiba Banded DTW (bandedDtwFeatureDistance): Aligns query and template feature sequences within a diagonal band (max(|n - m| + 4, max(n, m) / 3)). Frame distance computes Euclidean distance over C1..C12 and weighted ΔC1..ΔC12 (delta_w = 1.8), omitting C0/ΔC0 for volume invariance, normalized by (n + m).
  • Confidence Scoring: Maps best DTW distance (exp(-best_dist / 3.4)) plus runner-up margin separation (up to +0.25) into [0.0, 1.0]. In SAPI 5 (SpRecognizer.feedPcm16), matches with confidence >= 0.35 emit SPEI_RECOGNITION events.

Dynamic Win32 Audio Plumbing & Linux Host Bridge

Windows PE Dynamic Plumbing (src/sapi/winmm_audio.zig)

To keep sapi.dll freestanding (link_libc = false) and avoid hard import failures in minimal environments, winmm_audio.zig imports only core kernel32.dll primitives and lazily resolves optional Win32 DLLs via LoadLibraryA + GetProcAddress:

  • winmm.dll:
    • WaveOutPlayer opens WAVE_MAPPER at 22050 Hz 16-bit mono (CALLBACK_EVENT) and writes audio in ~100 ms chunks (2205 samples) so Pause, Resume, and SPF_PURGEBEFORESPEAK cancellation respond promptly.
    • WaveInCapture opens WAVE_MAPPER at 16000 Hz 16-bit mono (CALLBACK_EVENT) using 4 rotating 100 ms buffers (1600 samples each) on a dedicated capture thread. SpRecognizer.processCaptureBlock tracks an adaptive noise floor, preserves a 100 ms pre-roll buffer, accumulates up to 4 seconds (64000 samples), and flushes utterances after ~500 ms of trailing silence.
  • user32.dll: Resolves PostMessageW for SetNotifyWindowMessage delivery.
  • ole32.dll: Resolves CoTaskMemAlloc and CoTaskMemFree for SAPI 5 GetPhrase/GetText ownership semantics.
  • Host Test Fallbacks: On non-Windows builds (such as native Linux zig build test), winmm_audio.zig provides deterministic atomic events, size-prefixed CoTaskMem emulation, and simulated capture/playback hooks so the full SAPI 5 pipeline is unit-tested natively.

Linux Optional Host Speech Bridge (src/host/bridge.zig)

On Linux builds linked with libc (tonic CLI and libtonic.so), HostBridge.init() checks TONIC_NO_HOST_SPEECH. If unset (or "0"), it calls dlopen("libspeechd.so.2", RTLD_LAZY) and connects via spd_open("tonic", "sapi", null, SPD_MODE_SINGLE). Plain-text speech maps SAPI rate [-10, +10] to [-100, +100] and SAPI volume [0, 100] to [-100, +100]. If libspeechd.so.2 or the daemon is unavailable, Tonic transparently falls back to its built-in Klatt formant synthesizer.


Per-Game Compatibility Fix Registry (src/game_fixes.zig)

Tonic enforces a clear architectural boundary between universal SAPI 5 fixes and title-specific workarounds:

  • Universal COM ABI, TTS, ASR, and WinMM improvements belong directly in their core subsystems so all titles benefit.
  • Any game-specific workaround flags (GameFixFlags: force_sync_speak, relaxed_asr_threshold) are isolated in src/game_fixes.zig under per-title sections gated strictly by case-insensitive executable basename (setActiveExecutable / resolveFixesForExecutable) so one title's quirk cannot regress other games.

Clone this wiki locally