diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3463ca4..f05dab4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,13 +16,31 @@ jobs: - name: Checkout uses: actions/checkout@v4 - - name: Resolve version + - name: Resolve version and channel id: version run: | TAG="${GITHUB_REF_NAME}" VERSION="${TAG#v}" + + # A -beta suffix (e.g. v1.2.0-beta.1) selects the beta channel: a GitHub + # prerelease and a separate wyoming-apple-stt-beta formula that coexists with, + # and conflicts with, the stable one. + if [[ "${TAG}" == *-beta* ]]; then + CHANNEL="beta" + FORMULA_NAME="wyoming-apple-stt-beta" + FORMULA_CLASS="WyomingAppleSttBeta" + else + CHANNEL="stable" + FORMULA_NAME="wyoming-apple-stt" + FORMULA_CLASS="WyomingAppleStt" + fi + echo "tag=${TAG}" >> "$GITHUB_OUTPUT" echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT" + echo "formula_name=${FORMULA_NAME}" >> "$GITHUB_OUTPUT" + echo "formula_class=${FORMULA_CLASS}" >> "$GITHUB_OUTPUT" + echo "formula_file=Formula/${FORMULA_NAME}.rb" >> "$GITHUB_OUTPUT" - name: Run Swift tests run: make swift-test @@ -40,42 +58,62 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | + PRERELEASE_FLAG=() + if [[ "${{ steps.version.outputs.channel }}" == "beta" ]]; then + PRERELEASE_FLAG=(--prerelease) + fi gh release create "${{ steps.version.outputs.tag }}" \ "${{ steps.tarball.outputs.path }}" \ --title "${{ steps.version.outputs.tag }}" \ - --generate-notes + --generate-notes \ + "${PRERELEASE_FLAG[@]}" - name: Render formula and push to tap env: TAP_PUSH_TOKEN: ${{ secrets.TAP_PUSH_TOKEN }} + TAG: ${{ steps.version.outputs.tag }} VERSION: ${{ steps.version.outputs.version }} SHA256: ${{ steps.tarball.outputs.sha256 }} + CHANNEL: ${{ steps.version.outputs.channel }} + FORMULA_NAME: ${{ steps.version.outputs.formula_name }} + FORMULA_CLASS: ${{ steps.version.outputs.formula_class }} + FORMULA_FILE: ${{ steps.version.outputs.formula_file }} run: | set -euo pipefail - URL="https://github.com/FI-153/wyoming-apple-stt/releases/download/v${VERSION}/wyoming-apple-stt-${VERSION}.tar.gz" + URL="https://github.com/FI-153/wyoming-apple-stt/releases/download/${TAG}/wyoming-apple-stt-${VERSION}.tar.gz" URL="${URL}" python3 - <<'PY' import os from pathlib import Path + + # Stable and beta are mutually exclusive: both install the same apple-stt/apple-tts + # binaries and launchd service. conflicts_with is only enforced from the declaring + # side, so each formula names the other. + because = "both install the same binaries and launchd service" + other = "wyoming-apple-stt" if os.environ["CHANNEL"] == "beta" else "wyoming-apple-stt-beta" + conflicts = f'conflicts_with "{other}", because: "{because}"' + tpl = Path("packaging/formula.rb.template").read_text() resources = Path("packaging/python-resources.rb").read_text().rstrip() rendered = ( tpl + .replace("{{CLASS}}", os.environ["FORMULA_CLASS"]) .replace("{{URL}}", os.environ["URL"]) .replace("{{VERSION}}", os.environ["VERSION"]) .replace("{{SHA256}}", os.environ["SHA256"]) + .replace("{{CONFLICTS}}", conflicts) .replace("{{PYTHON_RESOURCES}}", resources) ) - Path("wyoming-apple-stt.rb").write_text(rendered) + Path("rendered-formula.rb").write_text(rendered) PY git clone "https://x-access-token:${TAP_PUSH_TOKEN}@github.com/FI-153/homebrew-tap.git" tap mkdir -p tap/Formula - mv wyoming-apple-stt.rb tap/Formula/wyoming-apple-stt.rb + mv rendered-formula.rb "tap/${FORMULA_FILE}" cd tap git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add Formula/wyoming-apple-stt.rb - git commit -m "wyoming-apple-stt ${VERSION}" + git add "${FORMULA_FILE}" + git commit -m "${FORMULA_NAME} ${VERSION}" git push origin HEAD:main diff --git a/CLAUDE.md b/CLAUDE.md index 47cbea4..0b04377 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,11 +1,12 @@ # Wyoming Apple STT -A Wyoming protocol STT server that bridges macOS on-device speech recognition (Apple's Speech -framework) to Home Assistant's Voice pipeline. +A Wyoming protocol STT + TTS server that bridges macOS on-device speech recognition (Apple's +Speech framework) and Siri text-to-speech to Home Assistant's Voice pipeline. ## Project Components -- **swift/** — Swift CLI tool that reads PCM audio from stdin and outputs transcribed text as JSON. +- **swift/Sources/AppleSTT/** — Swift CLI tool (`apple-stt`) that reads PCM audio from stdin and + outputs transcribed text as JSON. Uses SpeechAnalyzer on macOS 26+ and SFSpeechRecognizer on older systems. With `--worker` it runs as a persistent streaming worker instead: framed JSON commands on stdin (`transcribe` → `audio`+PCM payload → `stop`), `ready`/`partial`/`final`/`error` @@ -20,12 +21,22 @@ framework) to Home Assistant's Voice pipeline. - `SupportedLanguages.swift` — pure function `languageCodes(from:)` for extracting deduplicated, sorted short language codes from a list of locales. Used by `--list-languages` CLI flag. - `swift/Tests/AppleSTTTests/` — Swift unit tests (Swift Testing framework). +- **swift/Sources/AppleTTS/** — Swift CLI tool (`apple-tts`) exposing the private Siri synthesis + engine (`SiriTTSService.framework`). Runs as a long-lived worker: JSON commands on stdin, + JSON-header + binary PCM frames on stdout. `--list-voices` prints the system-managed Siri + voices (the only ones that reliably load; see `context/planning/add-siri-tts-streaming.md` + for the engine's lifecycle constraints — engines are never deallocated, init failures are + process-fatal by design). + - `swift/Tests/AppleTTSTests/` — voice-specifier parsing and asset-discovery tests. - **wyoming_apple_stt/** — Python Wyoming protocol server. Handles TCP connections from Home - Assistant. `stt.py` keeps a pool of pre-warmed `apple-stt --worker` processes; the handler - streams audio chunks into a worker session as they arrive, forwards partial transcripts as - `transcript-chunk` events, and emits the final transcript right after `audio-stop`. Any - streaming failure falls back to the buffered one-shot transcription path (audio is always - buffered in parallel). + Assistant. For STT, `stt.py` keeps a pool of pre-warmed `apple-stt --worker` processes + (mirroring the TTS pool design); the handler streams audio chunks into a worker session as + they arrive, forwards partial transcripts as `transcript-chunk` events, and emits the final + transcript right after `audio-stop`. Any streaming failure falls back to the buffered + one-shot transcription path (audio is always buffered in parallel). For TTS, `tts.py` + keeps a pool of pre-warmed `apple-tts` workers (acquire triggers a background replacement + spawn) and the handler serves both legacy `synthesize` and streaming + `synthesize-start/chunk/stop` with sentence-level incremental synthesis. - **scripts/** — Install and uninstall scripts for the launchd service. - **packaging/** — Release tooling: `build-release-tarball.sh` produces the GitHub release artifact; `formula.rb.template` + `python-resources.rb` are @@ -95,22 +106,42 @@ the user explicitly asks. Stage and commit decisions are always the user's to ma ## Releasing -Releases are tag-driven. To cut a new release: +Releases are tag-driven and split into two channels by the tag's shape. To cut a +**stable** release: ```bash git tag v.. git push origin v.. ``` +To cut a **beta** release, add a `-beta.` suffix: + +```bash +git tag v..-beta. # e.g. v1.2.0-beta.1 +git push origin v..-beta. +``` + +Both match the same `v*` trigger; the workflow branches on the `-beta` suffix. + The `.github/workflows/release.yml` workflow then: 1. Runs `make swift-test` and aborts on failure. 2. Builds the universal Swift binary via `packaging/build-release-tarball.sh` and assembles `wyoming-apple-stt-.tar.gz`. 3. Creates a GitHub release named after the tag and uploads the tarball as the - sole asset. -4. Renders `packaging/formula.rb.template` with the new version, URL, and sha256, - then pushes the resulting `Formula/wyoming-apple-stt.rb` to `FI-153/homebrew-tap`. + sole asset — marked as a **prerelease** for beta tags. +4. Renders `packaging/formula.rb.template` with the new version, URL, sha256, class + name, and a `conflicts_with` directive, then pushes the result to + `FI-153/homebrew-tap`. Stable tags write `Formula/wyoming-apple-stt.rb` (class + `WyomingAppleStt`); beta tags write a separate `Formula/wyoming-apple-stt-beta.rb` + (class `WyomingAppleSttBeta`), so the two channels coexist in the tap and never + overwrite each other. + +The beta uses a `-beta` suffix rather than `@beta` because Homebrew derives a formula's +Ruby class name from its filename and only maps `@` to `AT` before a digit +(`python@3.12`), so `wyoming-apple-stt@beta` would be an invalid class. Users install the +beta with `brew install FI-153/tap/wyoming-apple-stt-beta`; the two formulae +`conflicts_with` each other, so only one channel is active at a time. Requirements: diff --git a/Makefile b/Makefile index 5589927..bbc5e92 100644 --- a/Makefile +++ b/Makefile @@ -4,6 +4,7 @@ VENV_DIR := .venv VENV_PYTHON := $(VENV_DIR)/bin/python VENV_PIP := $(VENV_DIR)/bin/pip SWIFT_BIN := swift/.build/release/apple-stt +TTS_BIN := swift/.build/release/apple-tts PORT ?= 10300 LANGUAGE ?= en @@ -27,9 +28,9 @@ $(VENV_DIR)/bin/activate: requirements-dev.txt requirements.txt $(VENV_PIP) install --quiet -r requirements-dev.txt touch $(VENV_DIR)/bin/activate -build: $(SWIFT_BIN) ## Build the Swift CLI binary +build: $(SWIFT_BIN) ## Build the Swift CLI binaries -$(SWIFT_BIN): swift/Package.swift swift/Sources/AppleSTT/*.swift +$(SWIFT_BIN): swift/Package.swift swift/Sources/AppleSTT/*.swift swift/Sources/AppleTTS/*.swift cd swift && swift build -c release codesign -f -s - $(SWIFT_BIN) @@ -43,13 +44,14 @@ quality: venv ## Run ruff linter and mypy type checker $(VENV_DIR)/bin/ruff check wyoming_apple_stt/ tests/ $(VENV_DIR)/bin/mypy wyoming_apple_stt/ -run-clean: venv ## Rebuild Swift binary and start server - rm -f $(SWIFT_BIN) +run-clean: venv ## Rebuild Swift binaries and start server + rm -f $(SWIFT_BIN) $(TTS_BIN) cd swift && swift build -c release codesign -f -s - $(SWIFT_BIN) $(VENV_PYTHON) -m wyoming_apple_stt \ --uri tcp://0.0.0.0:$(PORT) \ --apple-stt-bin $(SWIFT_BIN) \ + --apple-tts-bin $(TTS_BIN) \ --language $(LANGUAGE) \ --debug @@ -57,6 +59,7 @@ run: venv build ## Run the server locally (Ctrl+C to stop) $(VENV_PYTHON) -m wyoming_apple_stt \ --uri tcp://0.0.0.0:$(PORT) \ --apple-stt-bin $(SWIFT_BIN) \ + --apple-tts-bin $(TTS_BIN) \ --language $(LANGUAGE) \ --debug diff --git a/README.md b/README.md index ee23765..7a29c7e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Wyoming Apple STT -On-device speech-to-text for Home Assistant, powered by Apple's Speech framework. +On-device speech-to-text **and Siri text-to-speech** for Home Assistant, powered by +Apple's Speech framework and the Siri speech synthesizer. Every word stays on your Mac: no cloud, no API key, no usage limits, full privacy. @@ -35,6 +36,55 @@ so concurrent utterances never wait for model initialization. If the streaming p for any reason, the server transparently falls back to buffered one-shot transcription of the same utterance — no audio is lost. +## Text-to-speech (Siri voices) 🗣️ + +The server also exposes the Mac's Siri voices as a Wyoming TTS service with **streaming +synthesis**: audio starts flowing to Home Assistant as soon as the first samples are +generated, sentence by sentence, instead of waiting for the whole reply. To keep latency +near zero, a synthesis engine is pre-warmed in an idle worker process at all times — when a +request arrives it starts speaking immediately while a replacement engine spins up in the +background for concurrent requests. + +Only voices that macOS manages itself are offered, because they always match the system's +Siri engine. macOS only keeps a *full* voice bundle on disk for a voice you've actually +selected — the language's other voice slots stay as tiny preview-only resource bundles +until you switch to them, so each voice you want available has to be selected at least +once: + +1. Open **System Settings → Siri → Siri Voice** (or **Accessibility → Spoken Content → + System Voice**), pick the language, then select **each voice slot you want** (e.g. + *Voice 1*/German "Martin" and *Voice 2*/German "Helena" are separate downloads) and let + it finish downloading. You can select a different voice afterwards as your live Siri + voice — once downloaded, the bundle stays and stays usable by this server regardless of + which one is currently active. +2. Restart the server. The voices appear automatically in Home Assistant's voice picker + (run `swift/.build/release/apple-tts --list-voices` to check what the server currently + sees without restarting anything). + +If no Siri voice is installed, the server logs a warning and runs STT-only. TTS can also be +turned off explicitly with `--no-tts` (via `EXTRA_ARGS`). + +Useful `EXTRA_ARGS` flags: `--tts-voice ` (default voice), `--tts-rate 1.2` +(speaking speed), `--tts-idle-workers 2` (more pre-warmed engines), `--no-tts`. + +### Concurrency model + +Each in-flight synthesis runs in its own `apple-tts` worker process, so requests never +queue behind each other. Beyond the pre-warmed pool (`--tts-idle-workers`, default 1), a +worker is spawned on demand for every concurrent request with no upper limit — the pool +only bounds how many engines are kept *pre-warmed*, not how many can run at once. A worker +that finishes while the pool already has enough idle workers is torn down immediately; +there's no idle timeout — surplus workers aren't kept around "just in case," and the +`idle_target` workers that are kept live until the server stops. + +In practice this scales with the Mac's CPU: tested on an 8-core Mac mini, 1–80 concurrent +requests all completed successfully (no errors, no dropped connections) at roughly 55 MB +resident memory per active worker. Latency stays near-instant (first audio in under +100 ms) up to about as many concurrent requests as physical cores; beyond that, requests +queue for CPU time and first-audio latency grows roughly linearly (e.g. ~3–11s at 80 +concurrent requests on 8 cores). This comfortably covers realistic Home Assistant usage +(one or a handful of simultaneous voice satellites); it isn't tuned for large numbers of +simultaneous conversations on constrained hardware. ## Install (Homebrew) 🍺 diff --git a/com.wyoming-apple-stt.plist.template b/com.wyoming-apple-stt.plist.template index 901f1c2..65a78da 100644 --- a/com.wyoming-apple-stt.plist.template +++ b/com.wyoming-apple-stt.plist.template @@ -15,6 +15,8 @@ tcp://0.0.0.0:__PORT__ --apple-stt-bin __APPLE_STT_BIN__ + --apple-tts-bin + __APPLE_TTS_BIN__ --language __LANGUAGE__ diff --git a/packaging/build-release-tarball.sh b/packaging/build-release-tarball.sh index 8ca0238..45ef7b8 100755 --- a/packaging/build-release-tarball.sh +++ b/packaging/build-release-tarball.sh @@ -19,26 +19,30 @@ DIST_DIR="${REPO_DIR}/dist" STAGE_DIR="${DIST_DIR}/wyoming-apple-stt-${VERSION}" TARBALL="${DIST_DIR}/wyoming-apple-stt-${VERSION}.tar.gz" -echo "==> Building universal Swift binary" +echo "==> Building universal Swift binaries" cd "${REPO_DIR}/swift" swift build -c release --arch arm64 --arch x86_64 -BIN_PATH="$(swift build -c release --arch arm64 --arch x86_64 --show-bin-path)/apple-stt" - -echo "==> Verifying binary is universal" -ARCHS="$(lipo -archs "${BIN_PATH}")" -if [[ "${ARCHS}" != *"arm64"* ]] || [[ "${ARCHS}" != *"x86_64"* ]]; then - echo "ERROR: expected universal binary, got: ${ARCHS}" >&2 - exit 1 -fi -echo " archs: ${ARCHS}" +BUILD_DIR="$(swift build -c release --arch arm64 --arch x86_64 --show-bin-path)" + +echo "==> Verifying binaries are universal" +for binary in apple-stt apple-tts; do + ARCHS="$(lipo -archs "${BUILD_DIR}/${binary}")" + if [[ "${ARCHS}" != *"arm64"* ]] || [[ "${ARCHS}" != *"x86_64"* ]]; then + echo "ERROR: expected universal ${binary}, got: ${ARCHS}" >&2 + exit 1 + fi + echo " ${binary} archs: ${ARCHS}" +done echo "==> Staging tarball contents at ${STAGE_DIR}" rm -rf "${STAGE_DIR}" "${TARBALL}" mkdir -p "${STAGE_DIR}" -cp "${BIN_PATH}" "${STAGE_DIR}/apple-stt" -# Re-sign so the embedded Info.plist (speech-recognition usage description) is -# bound into the signature; the linker's ad-hoc signature leaves it unbound and -# TCC then aborts the process on first SFSpeechRecognizer authorization request. +cp "${BUILD_DIR}/apple-stt" "${STAGE_DIR}/apple-stt" +cp "${BUILD_DIR}/apple-tts" "${STAGE_DIR}/apple-tts" +# Re-sign apple-stt so the embedded Info.plist (speech-recognition usage +# description) is bound into the signature; the linker's ad-hoc signature leaves +# it unbound and TCC then aborts the process on first SFSpeechRecognizer +# authorization request. apple-tts uses no speech-recognition entitlement. codesign -f -s - "${STAGE_DIR}/apple-stt" cp -R "${REPO_DIR}/wyoming_apple_stt" "${STAGE_DIR}/wyoming_apple_stt" cp "${REPO_DIR}/pyproject.toml" "${STAGE_DIR}/pyproject.toml" diff --git a/packaging/formula.rb.template b/packaging/formula.rb.template index 7b9570d..3520faf 100644 --- a/packaging/formula.rb.template +++ b/packaging/formula.rb.template @@ -1,4 +1,4 @@ -class WyomingAppleStt < Formula +class {{CLASS}} < Formula include Language::Python::Virtualenv desc "Wyoming protocol STT server backed by Apple's Speech framework" @@ -8,13 +8,16 @@ class WyomingAppleStt < Formula sha256 "{{SHA256}}" license "MIT" - depends_on "python@3.13" depends_on macos: :sequoia + depends_on "python@3.13" + + {{CONFLICTS}} {{PYTHON_RESOURCES}} def install bin.install "apple-stt" + bin.install "apple-tts" virtualenv_install_with_resources conf = etc/"wyoming-apple-stt.conf" @@ -43,6 +46,7 @@ class WyomingAppleStt < Formula --uri "tcp://0.0.0.0:${PORT}" \\ --language "${LANGUAGE}" \\ --apple-stt-bin "#{bin}/apple-stt" \\ + --apple-tts-bin "#{bin}/apple-tts" \\ ${EXTRA_ARGS} EOS chmod 0755, libexec/"wyoming-apple-stt-run" @@ -58,6 +62,8 @@ class WyomingAppleStt < Formula test do output = shell_output("#{bin}/apple-stt --list-languages") assert_match(/"en"/, output) + tts_output = shell_output("#{bin}/apple-tts --list-voices") + assert_match(/\A\[/, tts_output) system libexec/"bin/python", "-c", "import wyoming_apple_stt" end end diff --git a/scripts/install.sh b/scripts/install.sh index c619d2a..3ebc000 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -38,10 +38,12 @@ echo "Building Swift CLI..." cd "${PROJECT_DIR}/swift" swift build -c release SWIFT_BIN="${PROJECT_DIR}/swift/.build/release/apple-stt" -# Re-sign so the embedded Info.plist (speech-recognition usage description) is -# bound into the signature; TCC SIGABRTs worker mode otherwise. +TTS_BIN="${PROJECT_DIR}/swift/.build/release/apple-tts" +# Re-sign apple-stt so the embedded Info.plist (speech-recognition usage +# description) is bound into the signature; TCC SIGABRTs worker mode otherwise. codesign -f -s - "${SWIFT_BIN}" echo "Built: ${SWIFT_BIN}" +echo "Built: ${TTS_BIN}" # 2. Stop any running service before overwriting its files. Copying over the # live binary truncates its inode, breaking the running process's code @@ -54,6 +56,7 @@ launchctl unload "${PLIST_DIR}/${PLIST_NAME}" 2>/dev/null || true echo "Setting up install directory..." mkdir -p "${INSTALL_DIR}" cp "${SWIFT_BIN}" "${INSTALL_DIR}/apple-stt" +cp "${TTS_BIN}" "${INSTALL_DIR}/apple-tts" # 4. Create Python venv echo "Creating Python virtual environment..." @@ -71,6 +74,7 @@ sed \ -e "s|__VENV_PYTHON__|${INSTALL_DIR}/venv/bin/python|g" \ -e "s|__PORT__|${PORT}|g" \ -e "s|__APPLE_STT_BIN__|${INSTALL_DIR}/apple-stt|g" \ + -e "s|__APPLE_TTS_BIN__|${INSTALL_DIR}/apple-tts|g" \ -e "s|__LANGUAGE__|${LANGUAGE}|g" \ -e "s|__LOG_DIR__|${LOG_DIR}|g" \ -e "s|__INSTALL_DIR__|${INSTALL_DIR}|g" \ diff --git a/swift/Package.swift b/swift/Package.swift index 98698a1..287b5e2 100644 --- a/swift/Package.swift +++ b/swift/Package.swift @@ -22,10 +22,19 @@ let package = Package( ]), ] ), + .executableTarget( + name: "apple-tts", + path: "Sources/AppleTTS" + ), .testTarget( name: "AppleSTTTests", dependencies: ["apple-stt"], path: "Tests/AppleSTTTests" ), + .testTarget( + name: "AppleTTSTests", + dependencies: ["apple-tts"], + path: "Tests/AppleTTSTests" + ), ] ) diff --git a/swift/Sources/AppleTTS/SiriEngine.swift b/swift/Sources/AppleTTS/SiriEngine.swift new file mode 100644 index 0000000..0e207a3 --- /dev/null +++ b/swift/Sources/AppleTTS/SiriEngine.swift @@ -0,0 +1,196 @@ +import Foundation + +/// Receives raw PCM chunks (48 kHz, 16-bit, mono) as the engine produces them. +typealias SiriAudioHandler = @convention(block) (NSData) -> Void +/// Receives word-timing objects; unused here but the engine expects a handler to be set. +typealias SiriWordTimingsHandler = @convention(block) ([NSObject]) -> Void + +/// Errors raised while driving the private Siri synthesis engine. +enum SiriEngineError: Error, LocalizedError { + case frameworkUnavailable + case incompatibleVoice(String) + case engineInitFailed(String) + case synthesisFailed(String) + + var errorDescription: String? { + switch self { + case .frameworkUnavailable: + return "SiriTTSService.framework could not be loaded" + case .incompatibleVoice(let path): + return "Voice bundle uses the 2021-era tacotron-only format and cannot be loaded: \(path)" + case .engineInitFailed(let message): + return "The Siri engine couldn't load this voice: \(message)" + case .synthesisFailed(let message): + return "Synthesis failed: \(message)" + } + } +} + +/// Alloc an instance of an Objective-C class by name. +/// +/// alloc's +1 is deliberately left unclaimed: a consuming ObjC init takes it over, including +/// releasing it when init fails and returns nil (claiming it retained causes a use-after-free +/// exactly there). The resulting +1 over-retain on success is intentional — Siri engine +/// objects must never deallocate, see `SiriEngine.engineCache`. +private func allocInstance(_ cls: String) throws -> NSObject { + guard let cObject = NSClassFromString(cls) as? NSObject.Type else { + throw SiriEngineError.frameworkUnavailable + } + return cObject.perform("alloc").takeUnretainedValue() as! NSObject +} + +/// Owns the private Siri speech engine and hides the Objective-C bridging details. +/// +/// The native library is hostile to teardown: deallocating an engine tears down +/// process-global state that later inits and deallocs then trip over, and a failed init +/// poisons the autorelease pool (the next drain crashes in objc_release). Engines are +/// therefore cached per voice for the process lifetime and never deallocated, and callers +/// must treat `engineInitFailed` as fatal for the process. +final class SiriEngine { + private var engineCache: [String: NSObject] = [:] + + /// Load the private framework that hosts the engine classes. + /// + /// Must be called once before any other use. + /// + /// - Throws: `SiriEngineError.frameworkUnavailable` when dlopen fails. + static func loadFramework() throws { + let frameworkPath = "/System/Library/PrivateFrameworks/SiriTTSService.framework/SiriTTSService" + guard dlopen(frameworkPath, RTLD_LAZY) != nil else { + throw SiriEngineError.frameworkUnavailable + } + } + + /// Return a ready (initialized and preheated) engine for a voice bundle, caching it. + /// + /// - Parameter voicePath: Absolute path of the voice's `.asset` directory. + /// - Returns: The cached or newly initialized engine. + /// - Throws: `SiriEngineError` when the bundle is incompatible or the engine refuses it. + /// An `engineInitFailed` error leaves the process in a poisoned state; the caller must + /// report it and exit. + func engine(forVoicePath voicePath: String) throws -> NSObject { + if let cachedEngine = engineCache[voicePath] { + return cachedEngine + } + + let voiceURL = URL(fileURLWithPath: voicePath, isDirectory: true) + guard voiceIsCompatibleWithSystemEngine(voiceURL) else { + throw SiriEngineError.incompatibleVoice(voicePath) + } + + let newEngine = try initEngine(voicePath: voiceURL) + try preheat(newEngine) + engineCache[voicePath] = newEngine + return newEngine + } + + private func initEngine(voicePath: URL) throws -> NSObject { + let allocIns = try allocInstance("SiriTTSSynthesisEngine") + + let selector = NSSelectorFromString("initWithVoicePath:resourcePath:error:") + let method = class_getInstanceMethod(type(of: allocIns), selector) + let implementation = method_getImplementation(method!) + + // `Any` is an existential container (inline buffer + witness tables), not a single + // pointer, so it does not match the `NSString*` (`id`) slot the real IMP expects. + // Declaring these as `AnyObject` keeps the call ABI-compatible with a plain object + // pointer. + typealias Function = @convention(c) ( + AnyObject, Selector, AnyObject, AnyObject, UnsafeMutablePointer? + ) -> NSObject + let function = unsafeBitCast(implementation, to: Function.self) + + var error: NSObject? + let instance = function( + allocIns, + selector, + voicePath.path as NSString, + voicePath.appendingPathComponent("AssetData").path as NSString, + &error + ) + + if let error = error as? NSError { + throw SiriEngineError.engineInitFailed(error.localizedDescription) + } + + return instance + } + + private func preheat(_ engine: NSObject) throws { + let selector = NSSelectorFromString("preheatWithError:") + let method = class_getInstanceMethod(type(of: engine), selector) + let implementation = method_getImplementation(method!) + + typealias Function = @convention(c) ( + AnyObject, Selector, UnsafeMutablePointer + ) -> Bool + let function = unsafeBitCast(implementation, to: Function.self) + + var outError: AnyObject? + _ = function(engine, selector, &outError) + + if let error = outError as? NSError { + throw SiriEngineError.engineInitFailed(error.localizedDescription) + } + } + + /// Synthesize text with a voice, delivering PCM chunks through the audio handler. + /// + /// Blocks until synthesis completes; `audioHandler` fires on engine-owned threads while + /// this call is in progress. + /// + /// - Parameters: + /// - text: The text to speak. + /// - voicePath: Absolute path of the voice's `.asset` directory. + /// - rate: Speaking rate multiplier (1.0 = normal). + /// - pitch: Pitch multiplier (1.0 = normal). + /// - volume: Volume multiplier (1.0 = normal). + /// - audioHandler: Receives raw PCM chunks as they are produced. + /// - Throws: `SiriEngineError` when the engine cannot load the voice or synthesis fails. + func synthesize( + text: String, + voicePath: String, + rate: Double, + pitch: Double, + volume: Double, + audioHandler: @escaping SiriAudioHandler + ) throws { + let engine = try engine(forVoicePath: voicePath) + + let allocIns = try allocInstance("SiriTTSSynthesisEngineRequest") + let request = allocIns.perform("init").takeUnretainedValue() as! NSObject + + request.setValuesForKeys([ + "text": text, + "privacySensitive": false, + "requestId": UUID().uuidString, + "profile": 1, + "rate": rate, + "pitch": pitch, + "volume": volume, + ]) + + let wordTimingsHandler: SiriWordTimingsHandler = { _ in } + request.perform("setAudioHandler:", with: audioHandler) + request.perform("setWordTimingsHandler:", with: wordTimingsHandler) + + let selector = NSSelectorFromString("synthesize:error:") + let method = class_getInstanceMethod(type(of: engine), selector) + let implementation = method_getImplementation(method!) + + typealias Function = @convention(c) ( + AnyObject, Selector, AnyObject, UnsafeMutablePointer? + ) -> Bool + let function = unsafeBitCast(implementation, to: Function.self) + + var outError: NSObject? + let success = function(engine, selector, request, &outError) + + if let error = outError as? NSError { + throw SiriEngineError.synthesisFailed(error.localizedDescription) + } + if !success { + throw SiriEngineError.synthesisFailed("engine returned failure without an error") + } + } +} diff --git a/swift/Sources/AppleTTS/SystemVoices.swift b/swift/Sources/AppleTTS/SystemVoices.swift new file mode 100644 index 0000000..2418ad9 --- /dev/null +++ b/swift/Sources/AppleTTS/SystemVoices.swift @@ -0,0 +1,173 @@ +import Foundation + +/// A Siri voice bundle that macOS manages itself under the MobileAsset stores. +/// +/// These bundles are populated when a Siri voice is selected in System Settings and always +/// match the system's private TTS engine — unlike the frozen 2021 download catalog, whose +/// voices no longer load on current macOS. +struct SystemVoice: Codable { + /// Lowercase voice name from the asset specifier (e.g. "helena"). + let name: String + /// BCP-47 language tag (e.g. "de-DE"). + let language: String + /// Voice model type from the asset specifier (e.g. "neural"). + let type: String + /// Quality footprint from the asset specifier (e.g. "premium"). + let footprint: String + /// Speaker gender as reported by the asset properties, or "unknown". + let gender: String + /// The asset's ttsContentVersion, or 0 when absent. + let version: Int + /// Absolute path of the `.asset` directory (usable as the engine's voice path). + let path: String +} + +/// MobileAsset stores where macOS keeps the Siri voices selected in System Settings. +let defaultVoiceAssetStores = [ + "/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto", + "/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto", +] + +/// Parse a Siri TTS voice asset specifier into its voice fields. +/// +/// Specifiers look like `com.apple.siri.tts.voice.de_DE.helena.neural.premium`. The same +/// stores also hold `com.apple.siri.tts.resource.*` assets, which are not voices and are +/// rejected here. Locale underscores are normalized to hyphens ("de_DE" → "de-DE"). +/// +/// - Parameter specifier: The `Factor` or `AssetSpecifier` value from an asset's Info.plist. +/// - Returns: The parsed fields, or nil when the specifier is not a voice. +func parseVoiceSpecifier( + _ specifier: String +) -> (language: String, name: String, type: String, footprint: String)? { + let voicePrefix = "com.apple.siri.tts.voice." + guard specifier.hasPrefix(voicePrefix) else { return nil } + + let components = specifier.dropFirst(voicePrefix.count).components(separatedBy: ".") + guard components.count >= 4 else { return nil } + + return ( + language: components[0].replacingOccurrences(of: "_", with: "-"), + name: components[1], + type: components[2], + footprint: components[3] + ) +} + +/// Whether a voice bundle can be loaded *and* synthesized by the system engine on current macOS. +/// +/// Two bundle types are refused up front because both leave the native library in a broken +/// state rather than failing cleanly: +/// +/// - Tacotron-only bundles (the 2021 catalog era): the engine loads neural voices via their +/// fastspeech2 model data, but tacotron-only init demands emotion resources that no longer +/// exist, fails, and poisons the process. +/// - Bundles that force the "hydra" text frontend (the en-US / en-GB / en-IN "nashville" +/// family): init and preheat succeed, but `synthesize` throws `map::at: key not found` +/// because that frontend needs the shared `com.apple.siri.tts.resource.` bundle, which +/// the in-process engine cannot load on macOS 26 — and the failed synthesis poisons the +/// autorelease pool. See `voiceForcesHydraFrontend(atAssetData:)`. +/// +/// - Parameter voicePath: The voice bundle directory. +/// - Returns: True when the bundle is safe to hand to the engine. +func voiceIsCompatibleWithSystemEngine(_ voicePath: URL) -> Bool { + let assetData = voicePath.appendingPathComponent("AssetData") + let fileManager = FileManager.default + let usesTacotron = fileManager.fileExists(atPath: assetData.appendingPathComponent("tacotron").path) + let hasFastspeech2 = fileManager.fileExists(atPath: assetData.appendingPathComponent("fastspeech2").path) + if usesTacotron && !hasFastspeech2 { + return false + } + if voiceForcesHydraFrontend(atAssetData: assetData) { + return false + } + return true +} + +/// Whether a voice's frontend config forces the "hydra" text frontend. +/// +/// These voices carry a `frontend.cfg` with `"force_hydra_fe": true` and depend on the shared +/// `com.apple.siri.tts.resource.` bundle for their text-normalization rules. The +/// in-process engine can't load that bundle on macOS 26, so synthesis throws +/// `map::at: key not found`. Voices without a `frontend.cfg`, or with the flag absent or false, +/// use a self-contained frontend and synthesize normally. +/// +/// - Parameter assetData: The voice bundle's `AssetData` directory. +/// - Returns: True when the voice forces the hydra frontend. +func voiceForcesHydraFrontend(atAssetData assetData: URL) -> Bool { + let configURL = assetData.appendingPathComponent("frontend.cfg") + guard + let data = try? Data(contentsOf: configURL), + let config = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let forcesHydra = config["force_hydra_fe"] as? Bool + else { + return false + } + return forcesHydra +} + +/// Read one system voice from a `.asset` directory, if it holds a compatible voice. +/// +/// - Parameter assetDirectory: A `.asset` directory inside a MobileAsset store. +/// - Returns: The voice, or nil when the directory is not a usable, compatible voice bundle. +func systemVoice(atAssetDirectory assetDirectory: URL) -> SystemVoice? { + let assetData = assetDirectory.appendingPathComponent("AssetData") + guard FileManager.default.fileExists(atPath: assetData.path) else { return nil } + guard voiceIsCompatibleWithSystemEngine(assetDirectory) else { return nil } + + let infoPlistURL = assetDirectory.appendingPathComponent("Info.plist") + guard + let data = try? Data(contentsOf: infoPlistURL), + let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) + as? [String: Any], + let properties = plist["MobileAssetProperties"] as? [String: Any], + let specifier = (properties["Factor"] ?? properties["AssetSpecifier"]) as? String, + let fields = parseVoiceSpecifier(specifier) + else { return nil } + + return SystemVoice( + name: fields.name, + language: fields.language, + type: fields.type, + footprint: fields.footprint, + gender: properties["gender"] as? String ?? "unknown", + version: Int(properties["ttsContentVersion"] as? String ?? "") ?? 0, + path: assetDirectory.path + ) +} + +/// Discover all compatible system-managed Siri voices. +/// +/// Home Assistant keys a voice by `name-language-footprint`, ignoring its model type and +/// content version. The same speaker therefore ships as several assets that collapse to one +/// HA voice (e.g. `damon` en-US premium exists as both `neural` and `natural`). Those variants +/// are reported once here, keeping the one with the highest content version so HA sees no +/// duplicates. +/// +/// - Parameter stores: MobileAsset store directories to scan. +/// - Returns: The discovered voices, sorted by language, then name, then footprint. +func discoverSystemVoices(in stores: [String] = defaultVoiceAssetStores) -> [SystemVoice] { + var bestVoiceByKey: [String: SystemVoice] = [:] + + for store in stores { + let storeURL = URL(fileURLWithPath: store, isDirectory: true) + let assetURLs = (try? FileManager.default.contentsOfDirectory( + at: storeURL, + includingPropertiesForKeys: [.isDirectoryKey], + options: [.skipsHiddenFiles] + )) ?? [] + + for assetURL in assetURLs where assetURL.pathExtension == "asset" { + guard let voice = systemVoice(atAssetDirectory: assetURL) else { continue } + + let voiceKey = "\(voice.language)|\(voice.name)|\(voice.footprint)" + if let existing = bestVoiceByKey[voiceKey], existing.version >= voice.version { + continue + } + bestVoiceByKey[voiceKey] = voice + } + } + + return bestVoiceByKey.values.sorted { + ($0.language, $0.name, $0.footprint) < ($1.language, $1.name, $1.footprint) + } +} diff --git a/swift/Sources/AppleTTS/main.swift b/swift/Sources/AppleTTS/main.swift new file mode 100644 index 0000000..b3dbacc --- /dev/null +++ b/swift/Sources/AppleTTS/main.swift @@ -0,0 +1,179 @@ +import Foundation + +/// Sample rate of the PCM audio the Siri engine produces for current neural voices. +let engineSampleRate = 48_000 +/// Bytes per sample (16-bit). +let engineSampleWidth = 2 +/// Channel count (mono). +let engineChannels = 1 + +/// Serializes stdout writes: audio callbacks fire on engine threads while the main thread +/// owns the command loop, and each audio frame (header line + binary payload) must reach +/// the pipe as one contiguous write. +let stdoutLock = NSLock() + +/// Write one protocol frame to stdout: a JSON header line, then an optional binary payload. +func writeFrame(_ header: [String: Any], payload: Data? = nil) { + var data = try! JSONSerialization.data(withJSONObject: header) + data.append(0x0A) + if let payload { + data.append(payload) + } + + stdoutLock.lock() + defer { stdoutLock.unlock() } + FileHandle.standardOutput.write(data) +} + +/// Log a message to stderr (stdout is reserved for protocol frames). +func logError(_ message: String) { + fputs("[apple-tts] \(message)\n", stderr) +} + +/// A synthesize command received on stdin. +struct SynthesizeCommand: Decodable { + let command: String + let text: String + let voicePath: String + let rate: Double? + let pitch: Double? + let volume: Double? + + enum CodingKeys: String, CodingKey { + case command + case text + case voicePath = "voice_path" + case rate + case pitch + case volume + } +} + +/// Parsed command-line arguments. +struct CLIArgs { + /// When true, print discovered system voices as JSON and exit. + var listVoices: Bool = false + /// Voice bundle to initialize and preheat before signaling readiness. + var preloadVoicePath: String? +} + +/// Parse command-line arguments. +func parseArgs() -> CLIArgs { + var result = CLIArgs() + let args = CommandLine.arguments + + var i = 1 + while i < args.count { + if args[i] == "--list-voices" { + result.listVoices = true + i += 1 + } else if args[i] == "--preload-voice", i + 1 < args.count { + result.preloadVoicePath = args[i + 1] + i += 2 + } else { + i += 1 + } + } + + return result +} + +/// Run one synthesize command, streaming audio frames to stdout. +/// +/// Emits `audio` frames as the engine produces PCM, then a final `done` frame. On failure an +/// `error` frame is emitted instead; engine-init failures additionally terminate the process, +/// because a failed init leaves the native library in a state that crashes later (the pool +/// manager replaces the worker). +func handleSynthesize(_ command: SynthesizeCommand, engine: SiriEngine) { + let audioHandler: SiriAudioHandler = { data in + guard data.length > 0 else { return } + writeFrame( + [ + "type": "audio", + "length": data.length, + "rate": engineSampleRate, + "width": engineSampleWidth, + "channels": engineChannels, + ], + payload: data as Data + ) + } + + do { + try engine.synthesize( + text: command.text, + voicePath: command.voicePath, + rate: command.rate ?? 1.0, + pitch: command.pitch ?? 1.0, + volume: command.volume ?? 1.0, + audioHandler: audioHandler + ) + writeFrame(["type": "done"]) + } catch SiriEngineError.engineInitFailed(let message) { + writeFrame(["type": "error", "message": message]) + logError("Engine init failed, exiting (poisoned state): \(message)") + exit(1) + } catch { + writeFrame(["type": "error", "message": error.localizedDescription]) + } +} + +// MARK: - Main + +let cliArgs = parseArgs() + +if cliArgs.listVoices { + let voices = discoverSystemVoices() + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let jsonData = try! encoder.encode(voices) + FileHandle.standardOutput.write(jsonData) + FileHandle.standardOutput.write(Data([0x0A])) + exit(0) +} + +do { + try SiriEngine.loadFramework() +} catch { + logError("Error: \(error.localizedDescription)") + exit(1) +} + +let engine = SiriEngine() + +if let preloadVoicePath = cliArgs.preloadVoicePath { + do { + _ = try engine.engine(forVoicePath: preloadVoicePath) + // Preheating alone leaves lazy engine setup for the first synthesis, which then + // pays a multi-second penalty. A tiny discarded warmup synthesis moves that cost + // to worker startup, before the pool marks this worker ready. + try engine.synthesize( + text: ".", + voicePath: preloadVoicePath, + rate: 1.0, + pitch: 1.0, + volume: 1.0, + audioHandler: { _ in } + ) + logError("Preheated voice at \(preloadVoicePath)") + } catch { + logError("Error: preload failed: \(error.localizedDescription)") + exit(1) + } +} + +writeFrame(["type": "ready"]) + +while let line = readLine(strippingNewline: true) { + guard !line.isEmpty else { continue } + guard + let lineData = line.data(using: .utf8), + let command = try? JSONDecoder().decode(SynthesizeCommand.self, from: lineData), + command.command == "synthesize" + else { + writeFrame(["type": "error", "message": "unrecognized command: \(line.prefix(200))"]) + continue + } + + handleSynthesize(command, engine: engine) +} diff --git a/swift/Tests/AppleTTSTests/SystemVoicesTests.swift b/swift/Tests/AppleTTSTests/SystemVoicesTests.swift new file mode 100644 index 0000000..138b1b1 --- /dev/null +++ b/swift/Tests/AppleTTSTests/SystemVoicesTests.swift @@ -0,0 +1,272 @@ +import Foundation +import Testing + +@testable import apple_tts + +@Suite("parseVoiceSpecifier") +struct ParseVoiceSpecifierTests { + + @Test("parses a neural voice specifier") + func neuralVoice() { + let fields = parseVoiceSpecifier("com.apple.siri.tts.voice.de_DE.helena.neural.premium") + #expect(fields != nil) + #expect(fields?.language == "de-DE") + #expect(fields?.name == "helena") + #expect(fields?.type == "neural") + #expect(fields?.footprint == "premium") + } + + @Test("normalizes locale underscores to hyphens") + func localeNormalization() { + let fields = parseVoiceSpecifier("com.apple.siri.tts.voice.en_US.aria.neural.premiumhigh") + #expect(fields?.language == "en-US") + } + + @Test("keeps already-hyphenated locales") + func hyphenatedLocale() { + let fields = parseVoiceSpecifier("com.apple.siri.tts.voice.de-DE.martin.gryphon.compact") + #expect(fields?.language == "de-DE") + } + + @Test("rejects resource assets") + func resourceAsset() { + let fields = parseVoiceSpecifier("com.apple.siri.tts.resource.de_DE.nashville") + #expect(fields == nil) + } + + @Test("rejects specifiers with too few components") + func tooFewComponents() { + let fields = parseVoiceSpecifier("com.apple.siri.tts.voice.de_DE.helena") + #expect(fields == nil) + } + + @Test("rejects unrelated specifiers") + func unrelated() { + let fields = parseVoiceSpecifier("com.apple.MobileAsset.SomethingElse") + #expect(fields == nil) + } +} + +@Suite("systemVoice discovery") +struct SystemVoiceDiscoveryTests { + + /// Build a fake `.asset` bundle directory and return its URL. + private func makeAssetBundle( + specifier: String?, + gender: String? = "female", + contentVersion: String? = "1328", + modelDirectories: [String] = ["fastspeech2"], + frontendConfig: String? = nil, + includeAssetData: Bool = true + ) throws -> URL { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("apple-tts-tests-\(UUID().uuidString)", isDirectory: true) + let asset = root.appendingPathComponent("voice.asset", isDirectory: true) + try FileManager.default.createDirectory(at: asset, withIntermediateDirectories: true) + + if includeAssetData { + let assetData = asset.appendingPathComponent("AssetData", isDirectory: true) + try FileManager.default.createDirectory(at: assetData, withIntermediateDirectories: true) + for model in modelDirectories { + try FileManager.default.createDirectory( + at: assetData.appendingPathComponent(model, isDirectory: true), + withIntermediateDirectories: true + ) + } + if let frontendConfig { + try frontendConfig.write( + to: assetData.appendingPathComponent("frontend.cfg"), + atomically: true, + encoding: .utf8 + ) + } + } + + var properties: [String: Any] = [:] + if let specifier { + properties["Factor"] = specifier + } + if let gender { + properties["gender"] = gender + } + if let contentVersion { + properties["ttsContentVersion"] = contentVersion + } + + let plist: [String: Any] = ["MobileAssetProperties": properties] + let plistData = try PropertyListSerialization.data( + fromPropertyList: plist, format: .xml, options: 0 + ) + try plistData.write(to: asset.appendingPathComponent("Info.plist")) + + return asset + } + + @Test("reads a voice from a well-formed asset bundle") + func wellFormedBundle() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium" + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + let voice = systemVoice(atAssetDirectory: asset) + #expect(voice != nil) + #expect(voice?.name == "helena") + #expect(voice?.language == "de-DE") + #expect(voice?.type == "neural") + #expect(voice?.footprint == "premium") + #expect(voice?.gender == "female") + #expect(voice?.version == 1328) + #expect(voice?.path == asset.path) + } + + @Test("rejects tacotron-only bundles") + func tacotronOnlyBundle() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium", + modelDirectories: ["tacotron"] + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) == nil) + } + + @Test("accepts bundles with both tacotron and fastspeech2") + func mixedModelBundle() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium", + modelDirectories: ["tacotron", "fastspeech2"] + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) != nil) + } + + @Test("rejects voices that force the hydra frontend") + func hydraFrontendBundle() throws { + // Voices whose frontend.cfg sets force_hydra_fe need the shared + // com.apple.siri.tts.resource. bundle, which the in-process engine can't load on + // macOS 26 — synthesis fails with `map::at: key not found`. They must be refused up front. + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.damon.natural.premium", + frontendConfig: #"{"locale": "en-US", "force_hydra_fe": true}"# + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) == nil) + } + + @Test("accepts voices whose frontend config does not force hydra") + func nonHydraFrontendBundle() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_IE.aidan.natural.premium", + frontendConfig: #"{"locale": "en-IE", "force_hydra_fe": false}"# + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) != nil) + } + + @Test("rejects bundles without AssetData") + func missingAssetData() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium", + includeAssetData: false + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) == nil) + } + + @Test("rejects resource assets in the same store") + func resourceAsset() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.resource.de_DE.nashville" + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + #expect(systemVoice(atAssetDirectory: asset) == nil) + } + + @Test("defaults gender and version when absent") + func missingOptionalProperties() throws { + let asset = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.aria.neural.premium", + gender: nil, + contentVersion: nil + ) + defer { try? FileManager.default.removeItem(at: asset.deletingLastPathComponent()) } + + let voice = systemVoice(atAssetDirectory: asset) + #expect(voice?.gender == "unknown") + #expect(voice?.version == 0) + } + + @Test("discovery deduplicates identical voices across stores") + func deduplication() throws { + let assetA = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium" + ) + let assetB = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.de_DE.helena.neural.premium" + ) + defer { + try? FileManager.default.removeItem(at: assetA.deletingLastPathComponent()) + try? FileManager.default.removeItem(at: assetB.deletingLastPathComponent()) + } + + let voices = discoverSystemVoices(in: [ + assetA.deletingLastPathComponent().path, + assetB.deletingLastPathComponent().path, + ]) + #expect(voices.count == 1) + } + + @Test("collapses type variants that share language, name, and footprint") + func collapsesTypeVariants() throws { + // Same name/language/footprint but different type and version: these map to a single + // Home Assistant voice_id (name-language-footprint), so discovery must report one entry. + let neural = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.damon.neural.premium", + contentVersion: "1301" + ) + let natural = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.damon.natural.premium", + contentVersion: "5030" + ) + defer { + try? FileManager.default.removeItem(at: neural.deletingLastPathComponent()) + try? FileManager.default.removeItem(at: natural.deletingLastPathComponent()) + } + + let voices = discoverSystemVoices(in: [ + neural.deletingLastPathComponent().path, + natural.deletingLastPathComponent().path, + ]) + + #expect(voices.count == 1) + // The higher-version variant wins. + #expect(voices.first?.version == 5030) + #expect(voices.first?.type == "natural") + } + + @Test("keeps voices that differ only by footprint") + func keepsDistinctFootprints() throws { + let premium = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.aria.neural.premium" + ) + let compact = try makeAssetBundle( + specifier: "com.apple.siri.tts.voice.en_US.aria.neural.compact" + ) + defer { + try? FileManager.default.removeItem(at: premium.deletingLastPathComponent()) + try? FileManager.default.removeItem(at: compact.deletingLastPathComponent()) + } + + let voices = discoverSystemVoices(in: [ + premium.deletingLastPathComponent().path, + compact.deletingLastPathComponent().path, + ]) + #expect(voices.count == 2) + } +} diff --git a/tests/test_tts.py b/tests/test_tts.py new file mode 100644 index 0000000..ffbe313 --- /dev/null +++ b/tests/test_tts.py @@ -0,0 +1,278 @@ +"""Tests for the Siri TTS module: splitter, voice discovery, worker, and pool.""" + +import asyncio +import json +import stat + +import pytest + +from wyoming_apple_stt.tts import ( + SentenceSplitter, + SiriVoice, + TtsWorker, + TtsWorkerError, + TtsWorkerPool, + discover_tts_voices, + resolve_voice, +) + +# A stand-in for the apple-tts binary: prints ready, then answers every +# synthesize command with two audio frames and a done frame. +FAKE_WORKER = """#!/usr/bin/env python3 +import json, sys, os + +def frame(header, payload=b""): + sys.stdout.buffer.write(json.dumps(header).encode() + b"\\n" + payload) + sys.stdout.buffer.flush() + +if "--fail-start" in sys.argv: + sys.exit(1) + +frame({"type": "ready"}) +for line in sys.stdin: + cmd = json.loads(line) + text = cmd["text"] + if "explode" in text: + frame({"type": "error", "message": "engine refused"}) + continue + if "die" in text: + os._exit(1) + payload = text.encode() + for _ in range(2): + frame( + {"type": "audio", "length": len(payload), "rate": 48000, "width": 2, "channels": 1}, + payload, + ) + frame({"type": "done"}) +""" + + +@pytest.fixture +def fake_worker_bin(tmp_path): + """Write the fake apple-tts worker script and return its path.""" + path = tmp_path / "fake-apple-tts" + path.write_text(FAKE_WORKER) + path.chmod(path.stat().st_mode | stat.S_IEXEC) + return str(path) + + +@pytest.fixture +def voices() -> list[SiriVoice]: + """A small set of discovered voices.""" + return [ + SiriVoice( + name="helena", language="de-DE", type="neural", footprint="premium", + gender="female", version=1328, path="/assets/helena.asset", + ), + SiriVoice( + name="aria", language="en-US", type="neural", footprint="premiumhigh", + gender="female", version=1400, path="/assets/aria.asset", + ), + ] + + +# --- SentenceSplitter --- + + +def test_splitter_splits_complete_sentences(): + splitter = SentenceSplitter() + sentences = splitter.add("Hello world. How are you? ") + assert sentences == ["Hello world.", "How are you?"] + + +def test_splitter_holds_partial_sentence(): + splitter = SentenceSplitter() + assert splitter.add("This is not finished") == [] + assert splitter.add(" yet. But this") == ["This is not finished yet."] + assert splitter.finish() == "But this" + + +def test_splitter_finish_empty(): + splitter = SentenceSplitter() + assert splitter.add("Complete. ") == ["Complete."] + assert splitter.finish() is None + + +def test_splitter_handles_quotes_and_ellipsis(): + splitter = SentenceSplitter() + sentences = splitter.add('Er sagte "Hallo!" Dann ging er… Und dann kam er wieder') + assert sentences == ['Er sagte "Hallo!"', "Dann ging er…"] + assert splitter.finish() == "Und dann kam er wieder" + + +def test_splitter_does_not_split_decimal_numbers(): + splitter = SentenceSplitter() + assert splitter.add("Pi ist 3.14159 und mehr") == [] + + +# --- Voice discovery / resolution --- + + +def test_voice_id_and_description(voices): + assert voices[0].voice_id == "helena-de-DE-premium" + assert "Helena" in voices[0].description + assert "de-DE" in voices[0].description + + +async def test_discover_tts_voices(tmp_path): + entries = [ + { + "name": "helena", "language": "de-DE", "type": "neural", + "footprint": "premium", "gender": "female", "version": 1328, + "path": "/assets/helena.asset", + } + ] + script = tmp_path / "list-voices" + script.write_text(f"#!/bin/sh\necho '{json.dumps(entries)}'\n") + script.chmod(script.stat().st_mode | stat.S_IEXEC) + + discovered = await discover_tts_voices(str(script)) + assert len(discovered) == 1 + assert discovered[0].voice_id == "helena-de-DE-premium" + + +async def test_discover_tts_voices_missing_binary(): + assert await discover_tts_voices("/nonexistent/apple-tts") == [] + + +def test_resolve_voice_by_id(voices): + assert resolve_voice(voices, name="aria-en-US-premiumhigh") is voices[1] + + +def test_resolve_voice_by_bare_name(voices): + assert resolve_voice(voices, name="aria") is voices[1] + + +def test_resolve_voice_by_language(voices): + assert resolve_voice(voices, language="en-US") is voices[1] + + +def test_resolve_voice_by_short_language(voices): + assert resolve_voice(voices, language="de") is voices[0] + + +def test_resolve_voice_returns_none_on_no_match(voices): + assert resolve_voice(voices, name="nope", language="xx") is None + + +def test_resolve_voice_empty(): + assert resolve_voice([], name="any") is None + + +# --- TtsWorker --- + + +async def test_worker_synthesize_streams_frames(fake_worker_bin): + worker = TtsWorker(fake_worker_bin) + await worker.start(timeout=10) + try: + frames = [ + frame + async for frame in worker.synthesize( + text="hello", voice_path="/assets/x.asset", timeout=10 + ) + ] + assert len(frames) == 2 + assert frames[0].audio == b"hello" + assert frames[0].rate == 48000 + finally: + await worker.stop() + + +async def test_worker_error_frame_raises(fake_worker_bin): + worker = TtsWorker(fake_worker_bin) + await worker.start(timeout=10) + try: + with pytest.raises(TtsWorkerError, match="engine refused"): + async for _ in worker.synthesize( + text="explode", voice_path="/assets/x.asset", timeout=10 + ): + pass + finally: + await worker.stop() + + +async def test_worker_death_raises(fake_worker_bin): + worker = TtsWorker(fake_worker_bin) + await worker.start(timeout=10) + try: + with pytest.raises(TtsWorkerError): + async for _ in worker.synthesize( + text="die", voice_path="/assets/x.asset", timeout=10 + ): + pass + finally: + await worker.stop() + + +async def test_worker_start_failure_raises(): + failing = TtsWorker("/nonexistent/apple-tts") + with pytest.raises(TtsWorkerError): + await failing.start(timeout=5) + + +# --- TtsWorkerPool --- + + +async def test_pool_prewarms_idle_worker(fake_worker_bin): + pool = TtsWorkerPool(fake_worker_bin, idle_target=1) + await pool.start() + try: + assert len(pool._idle) == 1 + assert pool._idle[0].is_alive + finally: + await pool.stop() + + +async def test_pool_acquire_returns_warm_worker_and_replenishes(fake_worker_bin): + pool = TtsWorkerPool(fake_worker_bin, idle_target=1) + await pool.start() + try: + warm_worker = pool._idle[0] + worker = await pool.acquire() + assert worker is warm_worker # no spawn wait on the request path + + # A replacement spawn was scheduled in the background. + await asyncio.gather(*pool._spawn_tasks) + assert len(pool._idle) == 1 + assert pool._idle[0] is not worker + + await pool.release(worker) + # Pool is full again, so the released worker is disposed. + assert len(pool._idle) == 1 + assert not worker.is_alive + finally: + await pool.stop() + + +async def test_pool_release_returns_worker_when_idle_low(fake_worker_bin): + pool = TtsWorkerPool(fake_worker_bin, idle_target=2) + await pool.start() + try: + worker = await pool.acquire() + second = await pool.acquire() + idle_before = list(pool._idle) + await pool.release(worker) + assert worker in pool._idle or worker in idle_before + await pool.release(second) + finally: + await pool.stop() + + +async def test_pool_acquire_spawns_when_empty(fake_worker_bin): + pool = TtsWorkerPool(fake_worker_bin, idle_target=1) + # No start(): pool is empty, acquire must spawn synchronously. + worker = await pool.acquire() + try: + assert worker.is_alive + finally: + await pool.release(worker) + await pool.stop() + + +async def test_pool_stop_kills_idle_workers(fake_worker_bin): + pool = TtsWorkerPool(fake_worker_bin, idle_target=1) + await pool.start() + worker = pool._idle[0] + await pool.stop() + assert not worker.is_alive diff --git a/tests/test_tts_handler.py b/tests/test_tts_handler.py new file mode 100644 index 0000000..ed16ba3 --- /dev/null +++ b/tests/test_tts_handler.py @@ -0,0 +1,242 @@ +"""Tests for the TTS side of the Wyoming event handler.""" + +import asyncio +from unittest.mock import AsyncMock + +import pytest +from wyoming.audio import AudioChunk, AudioStart, AudioStop +from wyoming.tts import ( + Synthesize, + SynthesizeChunk, + SynthesizeStart, + SynthesizeStop, + SynthesizeStopped, + SynthesizeVoice, +) + +from wyoming_apple_stt.handler import AppleSTTEventHandler +from wyoming_apple_stt.tts import AudioFrame, SiriVoice, TtsService, TtsWorkerError + + +class FakeWorker: + """In-memory stand-in for a TtsWorker.""" + + def __init__(self) -> None: + self.is_alive = True + self.requests: list[dict] = [] + self.fail_next: str | None = None + self.stopped = False + + async def synthesize(self, text, voice_path, rate, pitch, volume, timeout): + self.requests.append({"text": text, "voice_path": voice_path}) + if self.fail_next: + message, self.fail_next = self.fail_next, None + raise TtsWorkerError(message) + yield AudioFrame(audio=text.encode(), rate=48000, width=2, channels=1) + + async def stop(self): + self.stopped = True + self.is_alive = False + + +class FakePool: + """In-memory stand-in for a TtsWorkerPool.""" + + def __init__(self) -> None: + self.workers: list[FakeWorker] = [] + self.released: list[FakeWorker] = [] + + async def acquire(self) -> FakeWorker: + worker = FakeWorker() + self.workers.append(worker) + return worker + + async def release(self, worker) -> None: + self.released.append(worker) + + +@pytest.fixture +def siri_voice() -> SiriVoice: + return SiriVoice( + name="helena", language="de-DE", type="neural", footprint="premium", + gender="female", version=1328, path="/assets/helena.asset", + ) + + +@pytest.fixture +def tts_service(siri_voice) -> TtsService: + return TtsService( + pool=FakePool(), voices=[siri_voice], default_voice=siri_voice, timeout=10 + ) + + +@pytest.fixture +def tts_handler(wyoming_info, cli_args, tts_service): + """Create a handler with TTS enabled and mocked reader/writer.""" + reader = AsyncMock() + writer = AsyncMock() + handler = AppleSTTEventHandler( + wyoming_info, + cli_args, + asyncio.Lock(), + reader, + writer, + tts_service=tts_service, + ) + handler.write_event = AsyncMock() + return handler + + +def written_events(handler) -> list: + return [call.args[0] for call in handler.write_event.call_args_list] + + +async def test_synthesize_streams_audio_envelope(tts_handler, tts_service): + """Legacy synthesize: AudioStart → AudioChunk → AudioStop, then disconnect.""" + event = Synthesize(text="Hallo Welt.").event() + result = await tts_handler.handle_event(event) + + assert result is False + events = written_events(tts_handler) + assert AudioStart.is_type(events[0].type) + assert AudioStart.from_event(events[0]).rate == 48000 + assert AudioChunk.is_type(events[1].type) + assert AudioChunk.from_event(events[1]).audio == b"Hallo Welt." + assert AudioStop.is_type(events[-1].type) + + # Worker was returned to the pool. + pool = tts_service.pool + assert len(pool.workers) == 1 + assert pool.released == pool.workers + + +async def test_synthesize_joins_multiline_text(tts_handler, tts_service): + """Newlines in the request collapse into a single synthesized line.""" + await tts_handler.handle_event(Synthesize(text="Zeile eins.\nZeile zwei.").event()) + worker = tts_service.pool.workers[0] + assert worker.requests[0]["text"] == "Zeile eins. Zeile zwei." + + +async def test_synthesize_empty_text_still_sends_envelope(tts_handler): + """Empty input must still produce AudioStart + AudioStop.""" + await tts_handler.handle_event(Synthesize(text=" \n ").event()) + events = written_events(tts_handler) + assert AudioStart.is_type(events[0].type) + assert AudioStop.is_type(events[1].type) + assert len(events) == 2 + + +async def test_streaming_flow(tts_handler, tts_service): + """synthesize-start/chunk/stop with per-sentence synthesis.""" + assert await tts_handler.handle_event(SynthesizeStart().event()) is True + assert await tts_handler.handle_event(SynthesizeChunk(text="Erster Satz. Zwei").event()) is True + + # Legacy synthesize repeating the full text mid-stream is ignored. + assert await tts_handler.handle_event(Synthesize(text="Erster Satz. Zweiter").event()) is True + + assert await tts_handler.handle_event(SynthesizeChunk(text="ter Satz. ").event()) is True + result = await tts_handler.handle_event(SynthesizeStop().event()) + assert result is False + + worker = tts_service.pool.workers[0] + assert [request["text"] for request in worker.requests] == [ + "Erster Satz.", + "Zweiter Satz.", + ] + + events = written_events(tts_handler) + assert AudioStart.is_type(events[0].type) + audio_chunks = [e for e in events if AudioChunk.is_type(e.type)] + assert len(audio_chunks) == 2 + assert AudioStop.is_type(events[-2].type) + assert SynthesizeStopped.is_type(events[-1].type) + + # The one worker served the whole stream and went back to the pool. + assert len(tts_service.pool.workers) == 1 + assert tts_service.pool.released == [worker] + + +async def test_streaming_flushes_remainder_on_stop(tts_handler, tts_service): + """Text without a final sentence boundary is synthesized at stop.""" + await tts_handler.handle_event(SynthesizeStart().event()) + await tts_handler.handle_event(SynthesizeChunk(text="Kein Satzende").event()) + await tts_handler.handle_event(SynthesizeStop().event()) + + worker = tts_service.pool.workers[0] + assert [request["text"] for request in worker.requests] == ["Kein Satzende"] + + +async def test_streaming_voice_selection(tts_handler, tts_service, siri_voice): + """A requested voice name resolves to the matching system voice path.""" + start = SynthesizeStart(voice=SynthesizeVoice(name="helena-de-DE-premium")) + await tts_handler.handle_event(start.event()) + await tts_handler.handle_event(SynthesizeChunk(text="Hallo. ").event()) + await tts_handler.handle_event(SynthesizeStop().event()) + + worker = tts_service.pool.workers[0] + assert worker.requests[0]["voice_path"] == siri_voice.path + + +async def test_unknown_voice_falls_back_to_default(tts_handler, tts_service, siri_voice): + """An unknown requested voice falls back to the default voice.""" + event = Synthesize(text="Hallo.", voice=SynthesizeVoice(name="nope")).event() + await tts_handler.handle_event(event) + worker = tts_service.pool.workers[0] + assert worker.requests[0]["voice_path"] == siri_voice.path + + +async def test_worker_failure_before_audio_retries_once(tts_handler, tts_service): + """A failure before any audio swaps the worker and retries the text.""" + pool = tts_service.pool + + original_acquire = pool.acquire + first = True + + async def acquire_with_failing_first(): + nonlocal first + worker = await original_acquire() + if first: + worker.fail_next = "engine died" + first = False + return worker + + pool.acquire = acquire_with_failing_first + + await tts_handler.handle_event(Synthesize(text="Hallo Welt.").event()) + + # First worker failed and was stopped; second one served the retry. + assert len(pool.workers) == 2 + assert pool.workers[0].stopped + events = written_events(tts_handler) + audio_chunks = [e for e in events if AudioChunk.is_type(e.type)] + assert len(audio_chunks) == 1 + assert AudioStop.is_type(events[-1].type) + + +async def test_disconnect_disposes_held_worker(tts_handler, tts_service): + """A client dropping mid-stream must not leak the held worker.""" + await tts_handler.handle_event(SynthesizeStart().event()) + worker = tts_service.pool.workers[0] + + await tts_handler.disconnect() + + assert worker.stopped + assert tts_service.pool.released == [] + + +async def test_tts_events_ignored_without_tts_service(handler_without_tts): + """Without a TTS service, synthesize events fall through harmlessly.""" + result = await handler_without_tts.handle_event(Synthesize(text="Hallo.").event()) + assert result is True + handler_without_tts.write_event.assert_not_called() + + +@pytest.fixture +def handler_without_tts(wyoming_info, cli_args): + reader = AsyncMock() + writer = AsyncMock() + handler = AppleSTTEventHandler( + wyoming_info, cli_args, asyncio.Lock(), reader, writer + ) + handler.write_event = AsyncMock() + return handler diff --git a/wyoming_apple_stt/__main__.py b/wyoming_apple_stt/__main__.py index f1ef659..2062b37 100644 --- a/wyoming_apple_stt/__main__.py +++ b/wyoming_apple_stt/__main__.py @@ -7,14 +7,38 @@ import logging from functools import partial -from wyoming.info import AsrModel, AsrProgram, Attribution, Info +from wyoming.info import ( + AsrModel, + AsrProgram, + Attribution, + Info, + TtsProgram, + TtsVoice, +) from wyoming.server import AsyncServer from .handler import AppleSTTEventHandler from .stt import SttService, SttWorkerPool +from .tts import ( + SiriVoice, + TtsService, + TtsWorkerPool, + discover_tts_voices, + resolve_voice, +) _LOGGER = logging.getLogger(__name__) +_APPLE_STT_ATTRIBUTION = Attribution( + name="Apple", + url="https://developer.apple.com/documentation/speech", +) + +_APPLE_TTS_ATTRIBUTION = Attribution( + name="Apple", + url="https://support.apple.com/guide/mac-help/change-siri-settings-mchl3fd77655/mac", +) + async def _discover_languages(bin_path: str, default_language: str) -> list[str]: """Query the Swift CLI for supported languages. @@ -116,12 +140,6 @@ async def _preload_model(bin_path: str, language: str) -> None: ) -_APPLE_STT_ATTRIBUTION = Attribution( - name="Apple", - url="https://developer.apple.com/documentation/speech", -) - - def _build_asr_program(languages: list[str]) -> AsrProgram: """Describe the Apple STT service for Wyoming Info. @@ -151,6 +169,36 @@ def _build_asr_program(languages: list[str]) -> AsrProgram: ) +def _build_tts_program(voices: list[SiriVoice]) -> TtsProgram: + """Describe the Siri TTS service and its system voices for Wyoming Info. + + Args: + voices: Discovered system voices (must be non-empty). + + Returns: + A TtsProgram advertising streaming synthesis support. + """ + return TtsProgram( + name="apple-tts", + description="Apple Siri on-device text-to-speech", + attribution=_APPLE_TTS_ATTRIBUTION, + installed=True, + version=None, + supports_synthesize_streaming=True, + voices=[ + TtsVoice( + name=voice.voice_id, + description=voice.description, + attribution=_APPLE_TTS_ATTRIBUTION, + installed=True, + version=str(voice.version), + languages=[voice.language], + ) + for voice in voices + ], + ) + + async def main() -> None: """Parse args, build Info, and start the Wyoming server.""" parser = argparse.ArgumentParser( @@ -189,6 +237,51 @@ async def main() -> None: default=1, help="Number of pre-warmed STT worker processes to keep ready (default: 1)", ) + parser.add_argument( + "--apple-tts-bin", + default="apple-tts", + help="Path to the apple-tts Swift CLI binary", + ) + parser.add_argument( + "--tts-voice", + default=None, + help="Default TTS voice name (default: first discovered system voice)", + ) + parser.add_argument( + "--tts-timeout", + type=int, + default=60, + help="Max seconds for a single synthesis (default: 60)", + ) + parser.add_argument( + "--tts-idle-workers", + type=int, + default=1, + help="Number of pre-warmed TTS engine processes to keep ready (default: 1)", + ) + parser.add_argument( + "--tts-rate", + type=float, + default=1.0, + help="TTS speaking rate multiplier (default: 1.0)", + ) + parser.add_argument( + "--tts-pitch", + type=float, + default=1.0, + help="TTS pitch multiplier (default: 1.0)", + ) + parser.add_argument( + "--tts-volume", + type=float, + default=1.0, + help="TTS volume multiplier (default: 1.0)", + ) + parser.add_argument( + "--no-tts", + action="store_true", + help="Disable the TTS service even when system voices are available", + ) parser.add_argument( "--debug", action="store_true", @@ -206,9 +299,46 @@ async def main() -> None: await _preload_model(args.apple_stt_bin, args.language) - wyoming_info = Info( - asr=[_build_asr_program(languages)], - ) + tts_service: TtsService | None = None + tts_programs: list[TtsProgram] = [] + if not args.no_tts: + tts_voices = await discover_tts_voices(args.apple_tts_bin) + if tts_voices: + default_voice = resolve_voice(tts_voices, name=args.tts_voice) + if default_voice is None: + if args.tts_voice: + _LOGGER.warning( + "TTS voice '%s' not found, using '%s'", + args.tts_voice, + tts_voices[0].voice_id, + ) + default_voice = tts_voices[0] + + pool = TtsWorkerPool( + args.apple_tts_bin, + preload_voice_path=default_voice.path, + idle_target=args.tts_idle_workers, + ) + tts_service = TtsService( + pool=pool, + voices=tts_voices, + default_voice=default_voice, + rate=args.tts_rate, + pitch=args.tts_pitch, + volume=args.tts_volume, + timeout=args.tts_timeout, + ) + tts_programs = [_build_tts_program(tts_voices)] + _LOGGER.info( + "TTS enabled with %d system voice(s), default '%s'", + len(tts_voices), + default_voice.voice_id, + ) + else: + _LOGGER.warning( + "TTS disabled: no system Siri voices found. Select a Siri voice in " + "System Settings → Siri (or Spoken Content) to enable it." + ) stt_service = SttService( pool=SttWorkerPool( @@ -218,18 +348,31 @@ async def main() -> None: ), timeout=args.timeout, ) + + wyoming_info = Info( + asr=[_build_asr_program(languages)], + tts=tts_programs, + ) + _LOGGER.info( "Pre-warming %d STT worker process(es)...", args.stt_idle_workers ) await stt_service.pool.start() + if tts_service is not None: + _LOGGER.info( + "Pre-warming %d TTS engine process(es)...", args.tts_idle_workers + ) + await tts_service.pool.start() + lock = asyncio.Lock() server = AsyncServer.from_uri(args.uri) _LOGGER.info( - "Wyoming Apple STT server ready on %s (language=%s)", + "Wyoming Apple STT server ready on %s (language=%s, tts=%s)", args.uri, args.language, + "on" if tts_service is not None else "off", ) try: @@ -240,10 +383,13 @@ async def main() -> None: args, lock, stt_service=stt_service, + tts_service=tts_service, ) ) finally: await stt_service.pool.stop() + if tts_service is not None: + await tts_service.pool.stop() def run() -> None: diff --git a/wyoming_apple_stt/handler.py b/wyoming_apple_stt/handler.py index 96143a1..28753d6 100644 --- a/wyoming_apple_stt/handler.py +++ b/wyoming_apple_stt/handler.py @@ -1,4 +1,4 @@ -"""Wyoming event handler for Apple STT.""" +"""Wyoming event handler for Apple STT and Siri TTS.""" import argparse import asyncio @@ -13,22 +13,42 @@ TranscriptStart, TranscriptStop, ) -from wyoming.audio import AudioChunk, AudioChunkConverter, AudioStop +from wyoming.audio import AudioChunk, AudioChunkConverter, AudioStart, AudioStop from wyoming.event import Event from wyoming.info import Describe, Info from wyoming.server import AsyncEventHandler +from wyoming.tts import ( + Synthesize, + SynthesizeChunk, + SynthesizeStart, + SynthesizeStop, + SynthesizeStopped, + SynthesizeVoice, +) from .stt import SttService, SttSession, SttWorker, SttWorkerError +from .tts import ( + CHANNELS, + SAMPLE_RATE, + SAMPLE_WIDTH, + SentenceSplitter, + SiriVoice, + TtsService, + TtsWorker, + TtsWorkerError, + resolve_voice, +) _LOGGER = logging.getLogger(__name__) class AppleSTTEventHandler(AsyncEventHandler): - """Wyoming STT event handler — one instance per client connection. + """Wyoming STT + TTS event handler — one instance per client connection. - Handles the Wyoming protocol event flow: Describe, Transcribe, - AudioChunk, AudioStop. Delegates actual transcription to the - apple-stt Swift CLI via subprocess. + Handles the Wyoming protocol event flow: Describe, Transcribe, AudioChunk, + AudioStop for STT (streamed to a pre-warmed apple-stt worker, with a + buffered one-shot fallback) and Synthesize plus the synthesize-start/chunk/ + stop streaming events for TTS (delegated to a pre-warmed apple-tts worker). """ def __init__( @@ -38,6 +58,7 @@ def __init__( transcription_lock: asyncio.Lock, *args: Any, stt_service: Optional[SttService] = None, + tts_service: Optional[TtsService] = None, **kwargs: Any, ) -> None: super().__init__(*args, **kwargs) @@ -59,6 +80,14 @@ def __init__( self._stt_session_failed = False self._transcript_started = False + self._tts = tts_service + self._tts_worker: Optional[TtsWorker] = None + self._tts_voice: Optional[SiriVoice] = None + self._tts_splitter: Optional[SentenceSplitter] = None + self._tts_audio_started = False + self._tts_streaming = False + self._tts_frames_sent_in_call = False + async def handle_event(self, event: Event) -> bool: """Handle a Wyoming protocol event. @@ -106,16 +135,61 @@ async def handle_event(self, event: Event) -> bool: self._transcript_started = False return False + if self._tts is not None: + if Synthesize.is_type(event.type): + if self._tts_streaming: + # Streaming clients repeat the full text in a legacy + # synthesize event for backwards compatibility; ignore it. + return True + await self._synthesize_complete(Synthesize.from_event(event)) + return False + + if SynthesizeStart.is_type(event.type): + start = SynthesizeStart.from_event(event) + self._tts_streaming = True + self._tts_splitter = SentenceSplitter() + self._tts_audio_started = False + self._tts_voice = self._resolve_requested_voice(start.voice) + self._tts_worker = await self._tts.pool.acquire() + _LOGGER.debug( + "Streaming synthesis started (voice=%s)", self._tts_voice.voice_id + ) + return True + + if SynthesizeChunk.is_type(event.type): + if not self._tts_streaming or self._tts_splitter is None: + return True + text_chunk = SynthesizeChunk.from_event(event) + for sentence in self._tts_splitter.add(text_chunk.text): + await self._speak_text(sentence) + return True + + if SynthesizeStop.is_type(event.type): + if self._tts_splitter is not None: + remainder = self._tts_splitter.finish() + if remainder: + await self._speak_text(remainder) + await self._finish_audio() + await self.write_event(SynthesizeStopped().event()) + await self._release_tts_worker() + self._tts_streaming = False + self._tts_splitter = None + _LOGGER.debug("Streaming synthesis finished") + return False + return True async def disconnect(self) -> None: - """Dispose of a held worker when the client drops mid-request. + """Dispose of held workers when the client drops mid-request. - A worker abandoned mid-transcription has unread frames in its pipe - and cannot be reused, so it is stopped rather than released. + A worker abandoned mid-request has unread frames in its pipe and cannot + be reused, so it is stopped rather than released. """ if self._stt_session is not None or self._stt_worker is not None: await self._teardown_stt_session() + if self._tts_worker is not None: + worker, self._tts_worker = self._tts_worker, None + await worker.stop() async def _stream_audio_to_worker(self, audio: bytes) -> None: """Feed one audio chunk to the streaming session, opening it lazily. @@ -213,6 +287,124 @@ async def _teardown_stt_session(self) -> None: worker, self._stt_worker = self._stt_worker, None await worker.stop() + def _resolve_requested_voice(self, requested: Optional[SynthesizeVoice]) -> SiriVoice: + """Map a client's voice request onto an installed system voice. + + Falls back to the server's default voice when nothing was requested + or the request matches no voice. + """ + assert self._tts is not None + name = requested.name if requested else None + language = requested.language if requested else None + resolved = resolve_voice(self._tts.voices, name=name, language=language) + if resolved is None: + if name or language: + _LOGGER.warning( + "No system voice matches name=%s language=%s, using default %s", + name, + language, + self._tts.default_voice.voice_id, + ) + return self._tts.default_voice + return resolved + + async def _synthesize_complete(self, synthesize: Synthesize) -> None: + """Serve a non-streaming synthesize request end to end.""" + assert self._tts is not None + self._tts_voice = self._resolve_requested_voice(synthesize.voice) + self._tts_audio_started = False + text = " ".join(synthesize.text.splitlines()).strip() + _LOGGER.debug( + "Synthesizing %d chars (voice=%s)", len(text), self._tts_voice.voice_id + ) + + self._tts_worker = await self._tts.pool.acquire() + try: + if text: + await self._speak_text(text) + await self._finish_audio() + finally: + await self._release_tts_worker() + + async def _speak_text(self, text: str) -> None: + """Synthesize one piece of text and stream its audio to the client. + + When the worker fails before producing any audio, it is swapped for a + fresh one and the text retried once; partial-output failures are only + logged, since retrying would duplicate the already-sent audio. + """ + _LOGGER.debug("Speaking %d chars", len(text)) + try: + await self._stream_frames(text) + except TtsWorkerError as exc: + _LOGGER.error("Synthesis failed for %d chars: %s", len(text), exc) + if self._tts_frames_sent_in_call: + # Retrying now would duplicate the audio already delivered. + return + await self._replace_tts_worker() + try: + await self._stream_frames(text) + except TtsWorkerError as retry_exc: + _LOGGER.error("Retry failed, skipping text: %s", retry_exc) + + async def _stream_frames(self, text: str) -> None: + """Run one worker synthesis, forwarding audio frames to the client. + + Sets `_tts_frames_sent_in_call` as soon as any frame goes out, so a + caller catching a mid-stream failure can tell partial output from none. + """ + assert self._tts is not None and self._tts_worker is not None + assert self._tts_voice is not None + self._tts_frames_sent_in_call = False + async for frame in self._tts_worker.synthesize( + text=text, + voice_path=self._tts_voice.path, + rate=self._tts.rate, + pitch=self._tts.pitch, + volume=self._tts.volume, + timeout=self._tts.timeout, + ): + if not self._tts_audio_started: + await self.write_event( + AudioStart( + rate=frame.rate, width=frame.width, channels=frame.channels + ).event() + ) + self._tts_audio_started = True + await self.write_event( + AudioChunk( + audio=frame.audio, + rate=frame.rate, + width=frame.width, + channels=frame.channels, + ).event() + ) + self._tts_frames_sent_in_call = True + + async def _finish_audio(self) -> None: + """Close the audio envelope, opening an empty one if nothing was sent.""" + if not self._tts_audio_started: + await self.write_event( + AudioStart(rate=SAMPLE_RATE, width=SAMPLE_WIDTH, channels=CHANNELS).event() + ) + self._tts_audio_started = True + await self.write_event(AudioStop().event()) + + async def _release_tts_worker(self) -> None: + """Hand the held worker back to the pool.""" + assert self._tts is not None + if self._tts_worker is not None: + worker, self._tts_worker = self._tts_worker, None + await self._tts.pool.release(worker) + + async def _replace_tts_worker(self) -> None: + """Swap a failed worker for a fresh one from the pool.""" + assert self._tts is not None + if self._tts_worker is not None: + await self._tts_worker.stop() + self._tts_worker = None + self._tts_worker = await self._tts.pool.acquire() + async def _transcribe(self) -> str: """Run the apple-stt subprocess and return transcribed text.""" language = self._language or self._cli_args.language diff --git a/wyoming_apple_stt/tts.py b/wyoming_apple_stt/tts.py new file mode 100644 index 0000000..d48f780 --- /dev/null +++ b/wyoming_apple_stt/tts.py @@ -0,0 +1,459 @@ +"""Siri TTS support: voice discovery, sentence splitting, and the warm worker pool.""" + +import asyncio +import json +import logging +import re +from dataclasses import dataclass +from typing import AsyncIterator, Optional + +_LOGGER = logging.getLogger(__name__) + +# Pipe buffer limit for worker stdout; audio frames can be large. +_STREAM_LIMIT = 8 * 1024 * 1024 + +# PCM format the Siri engine produces for current neural voices; used for the +# audio envelope when no frame was produced (e.g. empty input). Actual frames +# carry their own format. +SAMPLE_RATE = 48_000 +SAMPLE_WIDTH = 2 +CHANNELS = 1 + + +@dataclass +class SiriVoice: + """A system-managed Siri voice as reported by `apple-tts --list-voices`.""" + + name: str + language: str + type: str + footprint: str + gender: str + version: int + path: str + + @property + def voice_id(self) -> str: + """Unique, stable identifier used as the Wyoming voice name.""" + return f"{self.name}-{self.language}-{self.footprint}" + + @property + def description(self) -> str: + """Human-readable description shown in Home Assistant.""" + return f"{self.name.capitalize()} ({self.language}, {self.type}, {self.footprint})" + + +async def discover_tts_voices(bin_path: str) -> list[SiriVoice]: + """Query the apple-tts CLI for compatible system Siri voices. + + Runs the binary with --list-voices and parses the JSON array. Returns an + empty list on any failure so the server can start STT-only. + + Args: + bin_path: Path to the apple-tts Swift CLI binary. + + Returns: + List of discovered voices, possibly empty. + """ + try: + process = await asyncio.create_subprocess_exec( + bin_path, "--list-voices", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=10) + if process.returncode != 0: + _LOGGER.warning( + "TTS voice discovery failed (exit %s): %s", + process.returncode, + stderr.decode().strip() or "(no stderr output)", + ) + return [] + entries = json.loads(stdout.decode()) + voices = [SiriVoice(**entry) for entry in entries] + _LOGGER.debug( + "Discovered %d system Siri voices: %s", + len(voices), + [voice.voice_id for voice in voices], + ) + return voices + except asyncio.TimeoutError: + try: + process.kill() + await process.wait() + except ProcessLookupError: + pass + _LOGGER.warning("TTS voice discovery timed out") + except (json.JSONDecodeError, TypeError, OSError) as exc: + _LOGGER.warning("TTS voice discovery failed: %s", exc) + return [] + + +def resolve_voice( + voices: list[SiriVoice], + name: Optional[str] = None, + language: Optional[str] = None, +) -> Optional[SiriVoice]: + """Pick the voice matching a requested name or language. + + Name matches against the voice id first, then the bare voice name. + Language matches the full tag first (case-insensitive), then the bare + language code ("de" matches "de-DE"). + + Args: + voices: Available voices. + name: Requested voice name/id, if any. + language: Requested language tag, if any. + + Returns: + The matching voice, or None when nothing matches. + """ + if name: + for voice in voices: + if voice.voice_id == name: + return voice + for voice in voices: + if voice.name == name: + return voice + + if language: + lowered = language.lower() + for voice in voices: + if voice.language.lower() == lowered: + return voice + short = lowered.split("-")[0] + for voice in voices: + if voice.language.lower().split("-")[0] == short: + return voice + + return None + + +class SentenceSplitter: + """Incremental sentence-boundary splitter for streaming text input. + + Text chunks are appended with add(); complete sentences (terminated by + ., !, ?, or … followed by whitespace) are returned as soon as they are + available, and finish() flushes whatever remains. + """ + + _BOUNDARY = re.compile(r"[.!?…]+[\"'”’)\]]*\s+") + + def __init__(self) -> None: + self._buffer = "" + + def add(self, text: str) -> list[str]: + """Append a text chunk and return any newly completed sentences.""" + self._buffer += text + sentences = [] + while match := self._BOUNDARY.search(self._buffer): + sentence = self._buffer[: match.end()].strip() + if sentence: + sentences.append(sentence) + self._buffer = self._buffer[match.end():] + return sentences + + def finish(self) -> Optional[str]: + """Return the remaining partial sentence, if any, and reset.""" + remainder = self._buffer.strip() + self._buffer = "" + return remainder or None + + +@dataclass +class TtsService: + """Everything the event handler needs to serve TTS requests.""" + + pool: "TtsWorkerPool" + voices: list[SiriVoice] + default_voice: SiriVoice + rate: float = 1.0 + pitch: float = 1.0 + volume: float = 1.0 + timeout: float = 60.0 + + +@dataclass +class AudioFrame: + """One chunk of PCM audio produced by a worker.""" + + audio: bytes + rate: int + width: int + channels: int + + +class TtsWorkerError(Exception): + """Raised when a worker fails to start, dies, or reports a synthesis error.""" + + +class TtsWorker: + """One apple-tts worker subprocess with a preheated engine. + + The worker is started once, keeps its engines cached for its lifetime, + and serves one synthesize command at a time over its stdin/stdout pipe. + """ + + def __init__(self, bin_path: str, preload_voice_path: Optional[str] = None) -> None: + self._bin_path = bin_path + self._preload_voice_path = preload_voice_path + self._process: Optional[asyncio.subprocess.Process] = None + self._stderr_task: Optional[asyncio.Task] = None + + @property + def is_alive(self) -> bool: + """Whether the worker process is running.""" + return self._process is not None and self._process.returncode is None + + async def start(self, timeout: float = 60) -> None: + """Launch the worker and wait until its engine is preheated. + + Args: + timeout: Max seconds to wait for the worker's ready signal. + + Raises: + TtsWorkerError: When the worker cannot be launched or never + becomes ready. + """ + command = [self._bin_path] + if self._preload_voice_path: + command += ["--preload-voice", self._preload_voice_path] + + try: + self._process = await asyncio.create_subprocess_exec( + *command, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + limit=_STREAM_LIMIT, + ) + except OSError as exc: + raise TtsWorkerError(f"failed to launch {self._bin_path}: {exc}") from exc + + self._stderr_task = asyncio.create_task(self._drain_stderr()) + + try: + header = await asyncio.wait_for(self._read_header(), timeout=timeout) + except (asyncio.TimeoutError, TtsWorkerError) as exc: + await self.stop() + raise TtsWorkerError(f"worker did not become ready: {exc}") from exc + + if header.get("type") != "ready": + await self.stop() + raise TtsWorkerError(f"unexpected worker greeting: {header}") + + _LOGGER.debug("TTS worker ready (pid %s)", self._process.pid) + + async def synthesize( + self, + text: str, + voice_path: str, + rate: float = 1.0, + pitch: float = 1.0, + volume: float = 1.0, + timeout: float = 60, + ) -> AsyncIterator[AudioFrame]: + """Synthesize text, yielding PCM frames as the engine produces them. + + Args: + text: Text to speak. + voice_path: Absolute path of the voice's .asset directory. + rate: Speaking rate multiplier. + pitch: Pitch multiplier. + volume: Volume multiplier. + timeout: Max seconds for the whole synthesis. + + Yields: + AudioFrame chunks in production order. + + Raises: + TtsWorkerError: When the worker dies or reports an error. + """ + if not self.is_alive: + raise TtsWorkerError("worker is not running") + assert self._process is not None and self._process.stdin is not None + + command = { + "command": "synthesize", + "text": text, + "voice_path": voice_path, + "rate": rate, + "pitch": pitch, + "volume": volume, + } + self._process.stdin.write((json.dumps(command) + "\n").encode()) + await self._process.stdin.drain() + + deadline = asyncio.get_running_loop().time() + timeout + while True: + remaining = deadline - asyncio.get_running_loop().time() + if remaining <= 0: + raise TtsWorkerError(f"synthesis timed out after {timeout}s") + try: + header = await asyncio.wait_for(self._read_header(), timeout=remaining) + except asyncio.TimeoutError as exc: + raise TtsWorkerError(f"synthesis timed out after {timeout}s") from exc + + frame_type = header.get("type") + if frame_type == "audio": + assert self._process.stdout is not None + audio = await self._process.stdout.readexactly(int(header["length"])) + yield AudioFrame( + audio=audio, + rate=int(header.get("rate", 48000)), + width=int(header.get("width", 2)), + channels=int(header.get("channels", 1)), + ) + elif frame_type == "done": + return + elif frame_type == "error": + raise TtsWorkerError(header.get("message", "unknown synthesis error")) + else: + raise TtsWorkerError(f"unexpected worker frame: {header}") + + async def stop(self) -> None: + """Terminate the worker process and clean up.""" + if self._stderr_task is not None: + self._stderr_task.cancel() + self._stderr_task = None + + if self._process is None: + return + process, self._process = self._process, None + if process.returncode is None: + try: + process.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), timeout=5) + except asyncio.TimeoutError: + process.kill() + await process.wait() + + async def _read_header(self) -> dict: + """Read one JSON header line from the worker's stdout.""" + assert self._process is not None and self._process.stdout is not None + line = await self._process.stdout.readline() + if not line: + raise TtsWorkerError("worker closed its output (process died?)") + try: + header: dict = json.loads(line) + return header + except json.JSONDecodeError as exc: + raise TtsWorkerError(f"invalid worker frame: {line[:200]!r}") from exc + + async def _drain_stderr(self) -> None: + """Forward the worker's stderr lines to the debug log.""" + assert self._process is not None and self._process.stderr is not None + try: + while line := await self._process.stderr.readline(): + _LOGGER.debug("%s", line.decode(errors="replace").rstrip()) + except (asyncio.CancelledError, ValueError): + pass + + +class TtsWorkerPool: + """Keeps pre-warmed apple-tts workers so synthesis starts with zero delay. + + The pool maintains idle_target idle workers with preheated engines. + acquire() hands out a warm worker and immediately begins spawning a + replacement in the background, so a concurrent second request never + waits for engine initialization. + """ + + def __init__( + self, + bin_path: str, + preload_voice_path: Optional[str] = None, + idle_target: int = 1, + ) -> None: + self._bin_path = bin_path + self._preload_voice_path = preload_voice_path + self._idle_target = max(1, idle_target) + self._idle: list[TtsWorker] = [] + self._spawning = 0 + self._spawn_tasks: set[asyncio.Task] = set() + self._closed = False + + async def start(self) -> None: + """Pre-warm the initial idle workers, waiting until they are ready.""" + workers = await asyncio.gather( + *(self._spawn_worker() for _ in range(self._idle_target)), + return_exceptions=True, + ) + for worker in workers: + if isinstance(worker, BaseException): + _LOGGER.warning("Failed to pre-warm TTS worker: %s", worker) + else: + self._idle.append(worker) + + async def acquire(self) -> TtsWorker: + """Take a warm worker, triggering a background replacement spawn. + + Returns: + A ready worker. The caller must hand it back via release(). + + Raises: + TtsWorkerError: When no worker is available and a fresh spawn fails. + """ + worker: Optional[TtsWorker] = None + while self._idle and worker is None: + candidate = self._idle.pop() + if candidate.is_alive: + worker = candidate + else: + await candidate.stop() + + self._replenish() + + if worker is None: + worker = await self._spawn_worker() + return worker + + async def release(self, worker: TtsWorker) -> None: + """Return a worker to the pool, or dispose of it if surplus or dead.""" + if self._closed or not worker.is_alive or len(self._idle) >= self._idle_target: + await worker.stop() + else: + self._idle.append(worker) + + async def stop(self) -> None: + """Shut down all idle workers and cancel pending spawns.""" + self._closed = True + for task in self._spawn_tasks: + task.cancel() + self._spawn_tasks.clear() + idle, self._idle = self._idle, [] + await asyncio.gather(*(worker.stop() for worker in idle)) + + def _replenish(self) -> None: + """Spawn background workers until the idle target is covered.""" + if self._closed: + return + while len(self._idle) + self._spawning < self._idle_target: + self._spawning += 1 + task = asyncio.create_task(self._spawn_into_pool()) + self._spawn_tasks.add(task) + task.add_done_callback(self._spawn_tasks.discard) + + async def _spawn_into_pool(self) -> None: + """Spawn one worker and park it in the idle pool.""" + try: + worker = await self._spawn_worker() + except TtsWorkerError as exc: + _LOGGER.warning("Failed to spawn replacement TTS worker: %s", exc) + return + finally: + self._spawning -= 1 + + if self._closed or len(self._idle) >= self._idle_target: + await worker.stop() + else: + self._idle.append(worker) + + async def _spawn_worker(self) -> TtsWorker: + """Create and start one worker with the preload voice.""" + worker = TtsWorker(self._bin_path, self._preload_voice_path) + await worker.start() + return worker