Repository navigation
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.
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 | 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. |
Raw ASCII/UTF-8 English text passes through normalizeText before phoneme expansion:
-
Numbers: Integer tokens in
0..999are 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:
textToPhonemeschecks a 37-word high-frequency exception lexicon (function words, digits, and common command words likefire,reload,shield,ready) before falling back towordToPhonemesRuleBased, which handles suffixes/trigraphs (tion/sion,igh,tch, trailinging), consonant and vowel digraphs, doubled-consonant collapsing, silent trailinge, and context-sensitivec/g/y.
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/octavelip radiation. - Pitch contour (
base_pitch_hz = 125.0 Hz, scaled bypitch_scalein[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, tap0xB400_0001).
- Voiced segments use a smooth Rosenberg-style glottal pulse (
-
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 across45%..68%.
- Excitation feeds three Direct Form II Transposed second-order unity-DC biquad resonators (
-
Rate, Volume & Post-Processing:
- SAPI rate (
-10..+10) scales speaking speed via1.10^rate(~0.35x at-10,1.0xat0, ~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 softtanhlimiter before optional conversion to 16-bit signed PCM and 44-byte RIFF WAVE packaging (writeWav16).
- SAPI rate (
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 likex-slow/fast,soft/loud,low/high, percentages, semitonesst, andHzoffsets) 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 (&,<,>,",').
extractFeatures converts arbitrary-rate mono PCM (such as 16000 Hz microphone capture or 22050 Hz synthesized templates) into 26-dimensional acoustic feature frames (FeatureFrame):
-
Framing & Windowing: 10 ms frame hop (
sample_rate / 100), 25 ms analysis window (clamped toFFT_SIZE = 512),0.97pre-emphasis filter, and Hamming window. -
Spectrum & Mel Filterbank: In-place 512-point iterative Radix-2 Cooley-Tukey FFT (
HALF_FFT = 257power bins) projected through a 26-band triangular Mel filterbank spanning80 Hztomin(sample_rate / 2, 8000 Hz). -
Cepstrum & CMVN: Log energy (
1e-10floor) followed by DCT-II produces 13 static MFCCs (C0..C12). Per-utterance Cepstral Mean and Variance Normalization (CMVN) normalizesC1..C12to zero mean and unit variance for speaker, microphone EQ, and gain invariance. -
Temporal Deltas: First-order regression Delta MFCCs (
N = 2, denominator10.0) append 13 dynamic coefficients (ΔC0..ΔC12) to capture formant transitions.
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>(includingrepeat="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 viamax_depth/max_phrases, and detects compiled binary SAPI CFG blobs viaisLikelyBinaryGrammarso binary blobs return zero phrases safely instead of crashing.
GrammarRecognizer matches spoken utterances against active grammar rules:
-
Multi-Rate Acoustic Templates: Calling
addPhraseorloadGrammarsynthesizes 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 viaaddPhraseWithTemplateF32. -
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.004with 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 overC1..C12and weightedΔC1..ΔC12(delta_w = 1.8), omittingC0/ΔC0for 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 withconfidence >= 0.35emitSPEI_RECOGNITIONevents.
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:-
WaveOutPlayeropensWAVE_MAPPERat 22050 Hz 16-bit mono (CALLBACK_EVENT) and writes audio in ~100 ms chunks (2205samples) soPause,Resume, andSPF_PURGEBEFORESPEAKcancellation respond promptly. -
WaveInCaptureopensWAVE_MAPPERat 16000 Hz 16-bit mono (CALLBACK_EVENT) using 4 rotating 100 ms buffers (1600samples each) on a dedicated capture thread.SpRecognizer.processCaptureBlocktracks an adaptive noise floor, preserves a 100 ms pre-roll buffer, accumulates up to 4 seconds (64000samples), and flushes utterances after ~500 ms of trailing silence.
-
-
user32.dll: ResolvesPostMessageWforSetNotifyWindowMessagedelivery. -
ole32.dll: ResolvesCoTaskMemAllocandCoTaskMemFreefor SAPI 5GetPhrase/GetTextownership semantics. -
Host Test Fallbacks: On non-Windows builds (such as native Linux
zig build test),winmm_audio.zigprovides deterministic atomic events, size-prefixedCoTaskMememulation, and simulated capture/playback hooks so the full SAPI 5 pipeline is unit-tested natively.
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.
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 insrc/game_fixes.zigunder per-title sections gated strictly by case-insensitive executable basename (setActiveExecutable/resolveFixesForExecutable) so one title's quirk cannot regress other games.
Copyright (c) 2026 buntatoes. Tonic is a 100% standalone speech engine built from scratch and licensed under the Apache License 2.0. The Tonic, Pisco, Vodka, and Bitters names, wordmarks, and logos are All Rights Reserved.
Trademarks & Non-Affiliation: Windows and SAPI are trademarks or registered trademarks of Microsoft Corporation. Steam, Steam Play, and Proton are trademarks or registered trademarks of Valve Corporation. Linux, AMD, NVIDIA, Intel, and other third-party trademarks belong to their respective owners; Tonic is an independent open-source project and is not affiliated with, endorsed by, or sponsored by any of them.
Design & Engine
Build & Usage
Support
Links
-
Tonic Repository (
unstable/stable) - Pisco · Pisco Wiki
- Vodka · Vodka Wiki
- Bitters
- Apache-2.0 License