Skip to content

SAPI 5 Compatibility

buntatoes edited this page Nov 29, 2026 · 1 revision

SAPI 5 Compatibility

Tonic compiles a freestanding multi-architecture Windows PE sapi.dll (x86_64-windows, i386-windows, and aarch64-windows) implementing the core Windows SAPI 5 COM interfaces for text-to-speech, finite-grammar command recognition, event notifications, and voice token enumeration.

Every COM vtable struct in src/com/abi.zig and src/sapi/*.zig is verified at compile time with assertVtableCount and assertVtableSlot to guarantee exact Windows ABI slot offsets on both 32-bit (stdcall/winapi) and 64-bit (win64/aarch64) targets.


Exported DLL Entry Points (src/sapi/dllmain.zig)

Export Behavior
DllMain Returns TRUE (1).
DllGetClassObject Dispatches documented SAPI 5 CLSIDs to static IClassFactory singletons (CLASS_E_CLASSNOTAVAILABLE for unknown CLSIDs).
DllCanUnloadNow Returns S_OK when atomic global live COM object count (g_object_count) and class factory lock count (g_lock_count) are both zero, else S_FALSE.
DllRegisterServer Returns S_OK.
DllUnregisterServer Returns S_OK.

Supported CLSIDs & ClassFactory (src/com/abi.zig, src/sapi/root.zig)

Class Name CLSID Instantiated Object
CLSID_SpVoice {96749377-3391-11D2-9EE3-00C04F797396} SpVoice (ISpVoice, ISpEventSource, ISpNotifySource, IUnknown)
CLSID_SpInprocRecognizer {41B89B6B-9399-11D2-9623-00C04F8EE628} SpRecognizer with is_shared = 0 (ISpRecognizer, ISpProperties, IUnknown)
CLSID_SpSharedRecognizer {3BEE4890-4FE9-4A37-8C1E-5E7E12791C1F} SpRecognizer with is_shared = 1 (ISpRecognizer, ISpProperties, IUnknown)
CLSID_SpObjectTokenCategory {A910187F-0C7A-45AC-92CC-59EDAFB77B53} SpObjectTokenCategory (ISpObjectTokenCategory, ISpDataKey, IUnknown)
CLSID_SpObjectToken {EF411752-3736-4CB4-9C8C-8EF4CCB58EFE} SpObjectToken initialized to the built-in Tonic English voice token

Note

CLSID_SpStream ({715D9C59-4442-11D2-9605-00C04F8EE628}) is defined in src/com/abi.zig, but DllGetClassObject does not yet instantiate a standalone SpStream COM object. Callers can still pass their own ISequentialStream, IStream, or ISpStream implementation to ISpVoice::SetOutput and ISpVoice::SpeakStream.


Implemented COM Interfaces & Vtable Layouts

Interface Inheritance Chain Vtable Slots Source File
IUnknown Base 3 (0..2) src/com/abi.zig
IClassFactory IUnknown 5 (0..4) src/com/abi.zig
ISpNotifySink IUnknown 4 (0..3) src/sapi/notify.zig
ISpNotifyCallback Standalone callback vtable 1 (0) src/sapi/notify.zig
ISpVoice ISpEventSource -> ISpNotifySource -> IUnknown 37 (0..36) src/sapi/voice.zig
ISpRecognizer ISpProperties -> IUnknown 23 (0..22) src/sapi/recognizer.zig
ISpRecoContext ISpEventSource -> ISpNotifySource -> IUnknown 31 (0..30) src/sapi/recognizer.zig
ISpRecoGrammar ISpGrammarBuilder -> IUnknown 29 (0..28) src/sapi/recognizer.zig
ISpPhrase IUnknown 7 (0..6) src/sapi/result.zig
ISpRecoResult ISpPhrase -> IUnknown 14 (0..13) src/sapi/result.zig
ISpObjectTokenCategory ISpDataKey -> IUnknown 21 (0..20) src/sapi/token.zig
ISpObjectToken ISpDataKey -> IUnknown 25 (0..24) src/sapi/token.zig
IEnumSpObjectTokens IUnknown 9 (0..8) src/sapi/token.zig

Subsystem Behavior Details

ISpVoice (src/sapi/voice.zig)

  • Speech Synthesis & Routing:
    • Speak(pwcs, dwFlags, pulStreamNumber) decodes UTF-16LE text and handles SPF_ASYNC (spawns a Win32 worker thread on Windows PE), SPF_PURGEBEFORESPEAK (increments purge generation, resets active waveOut, waits up to 500 ms for in-flight async work, and clears pending events), SPF_IS_XML / SPF_PARSE_SSML / SPF_PARSE_SAPI (dispatches to the SSML/SAPI XML segment synthesizer), and SPF_IS_NOT_XML (forces plain-text synthesis).
    • If an output stream was bound via SetOutput (querying ISequentialStream, IStream, or ISpStream), synthesized 22050 Hz 16-bit mono PCM bytes are written directly to that stream.
    • Otherwise, on Windows PE, audio plays via dynamic winmm.dll (WaveOutPlayer) unless TONIC_NO_AUDIO_PLAYBACK is set. On native Linux tests/hosts, plain text probes HostBridge (libspeechd.so.2) with built-in formant fallback.
  • Playback Control & Status:
    • SetRate/GetRate clamps to [-10, +10]; SetVolume/GetVolume clamps to [0, 100].
    • Pause and Resume maintain a pause count and forward to waveOutPause/waveOutRestart.
    • WaitUntilDone(msTimeout) waits on the voice's manual-reset completion event (SPRS_IS_SPEAKING -> SPRS_DONE).
    • GetStatus populates SPVOICESTATUS (ulCurrentStream, ulLastStreamQueued, hrLastResult, dwRunningState, ulInputWordPos, ulInputWordLen).
    • SpeakStream reads up to 16 MiB from an input ISequentialStream and forwards to any bound output stream.
  • Event Queue (MAX_QUEUED_EVENTS = 64):
    • Queues SPEI_START_INPUT_STREAM and SPEI_END_INPUT_STREAM by default, and emits SPEI_WORD_BOUNDARY (with estimated audio byte offset, word position, and word length) whenever requested via SetInterest.

ISpRecognizer, ISpRecoContext & ISpRecoGrammar (src/sapi/recognizer.zig)

  • Grammar Authoring & Loading:
    • Programmatic builder (ISpGrammarBuilder): ResetGrammar, GetRule, CreateNewState, AddWordTransition (registers phrases directly into GrammarRecognizer), and Commit.
    • File & Memory Loading: LoadCmdFromFile (up to 2 MiB via CreateFileW/ReadFile) and LoadCmdFromMemory (auto-detects UTF-16LE with/without BOM, UTF-8 with/without BOM, W3C SRGS XML, SAPI 5 XML, and plain phrase lists up to 256 KiB). Compiled binary SAPI CFG buffers are detected safely and return S_OK without crashing.
    • Rule & Grammar States: SetRuleState (matches by rule name or applies to all rules when pszName == null), SetRuleIdState, SetGrammarState/GetGrammarState (SPGS_ENABLED, SPGS_DISABLED, SPGS_EXCLUSIVE), and SetContextState/GetContextState.
  • Live Capture & Recognition Dispatch:
    • Transitioning SetRecoState to SPRST_ACTIVE or SPRST_ACTIVE_ALWAYS on Windows PE starts WaveInCapture (16 kHz mono, 4x100 ms buffers) unless TONIC_NO_MIC_CAPTURE is set. Setting SPRST_INACTIVE or SPRST_INACTIVE_WITH_PURGE stops capture.
    • Completed utterances are scored across up to MAX_RECO_CONTEXTS = 16 contexts and MAX_CTX_GRAMMARS = 16 enabled grammars per context. Matches with confidence >= 0.35 allocate a SpRecoResult, push an SPEI_RECOGNITION event (SPET_LPARAM_IS_OBJECT, queue capacity MAX_CTX_EVENTS = 32), and trigger ISpNotifySource.
    • EmulateRecognition extracts text from the supplied ISpPhrase, matches active grammar metadata when available, and dispatches an SPEI_RECOGNITION event with confidence = 1.0.

ISpRecoResult & ISpPhrase (src/sapi/result.zig)

  • GetPhrase: Packs SPPHRASE, an array of per-word SPPHRASEELEMENT entries (up to 128 words, with pszDisplayText, pszLexicalForm, per-word audio offsets, and confidence tier), and all UTF-16LE strings into a single CoTaskMemAlloc block so callers can release the entire structure with one CoTaskMemFree call per Windows SAPI 5 ownership rules.
  • GetText: Supports both whole-phrase (SP_GETWHOLEPHRASE) and word sub-range extraction into CoTaskMemAlloc-allocated UTF-16LE strings.
  • GetResultTimes: Computes SPRECORESULTTIMES.ullLength in 100-nanosecond units from captured byte count and sample rate.
  • GetRecoContext: Returns an AddRef'd pointer to the originating ISpRecoContext (attached cleanly when dequeued via GetEvents to avoid internal reference cycles).
  • Confidence Tiers: >= 0.72 -> SP_HIGH_CONFIDENCE (+1), >= 0.42 -> SP_NORMAL_CONFIDENCE (0), < 0.42 -> SP_LOW_CONFIDENCE (-1).

ISpNotifySource (src/sapi/notify.zig)

Shared by both ISpVoice and ISpRecoContext, supporting all 5 SAPI 5 notification modes:

  1. Win32 Event: SetNotifyWin32Event, WaitForNotifyEvent, GetNotifyEventHandle (real CreateEventW handle on Windows PE; automatically reset when the event queue drains).
  2. Window Message: SetNotifyWindowMessage dispatches via dynamic user32.dll!PostMessageW.
  3. C Callback Function: SetNotifyCallbackFunction invokes fn(wParam, lParam) callconv(.winapi).
  4. Callback Interface: SetNotifyCallbackInterface invokes ISpNotifyCallback::NotifyCallback(wParam, lParam).
  5. Notify Sink COM Object: SetNotifySink queries IID_ISpNotifySink (with direct-pointer fallback) and invokes ISpNotifySink::Notify() outside internal locks to prevent re-entrancy deadlocks.

Built-In Object Tokens (src/sapi/token.zig)

SpObjectTokenCategory::EnumTokens returns an IEnumSpObjectTokens enumerator exposing 1 built-in voice token:

Property Value
Token ID HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TonicEnglish
Name (and default value) Tonic English
Vendor Tonic
Language 409 (0x0409, English)
Gender Neutral

Current Limitations & Unimplemented SAPI 5 Features

Feature / Method Current Behavior Notes
Binary SAPI CFG Grammars (SPBINARYGRAMMAR) LoadCmdFromMemory / LoadCmdFromFile detect binary blobs and return S_OK with 0 parsed rules Compiled binary CFG rule-graph deserialization is not yet implemented; SRGS XML, SAPI 5 XML, phrase lists, and AddWordTransition are supported.
Open Dictation (LoadDictation) LoadDictation, UnloadDictation, SetDictationState return S_OK as no-ops Tonic focuses on closed-vocabulary finite command grammars rather than unconstrained dictation.
ISpRecoResult Audio & Serialization GetAudio, SpeakAudio, Serialize, ScaleAudio, ISpPhrase::GetSerializedPhrase, and ISpRecoContext::DeserializeResult return E_NOTIMPL Recognition results currently retain phrase text, rule metadata, confidence, and timing without raw PCM retention.
Recognition Alternates ISpRecoResult::GetAlternates returns 0 alternates (S_OK) Top-1 matching rule is returned.
ISpRecoGrammar::SaveCmd Returns E_NOTIMPL Binary grammar serialization is not yet implemented.
Voice Skip, Bookmarks, Phoneme & Viseme Events ISpVoice::Skip returns 0 skipped (S_OK); SPEI_TTS_BOOKMARK, SPEI_PHONEME, and SPEI_VISEME are not emitted SPEI_START_INPUT_STREAM, SPEI_WORD_BOUNDARY, and SPEI_END_INPUT_STREAM are emitted.
CLSID_SpStream Factory Not registered in DllGetClassObject (CLASS_E_CLASSNOTAVAILABLE) External ISequentialStream/IStream pointers passed to SetOutput/SpeakStream work directly.
Configuration UI (DisplayUI) IsUISupported sets FALSE (S_OK); DisplayUI returns E_NOTIMPL Headless / non-GUI compatibility layer.