Skip to content

fix(tts): wire real sherpa-onnx synthesis into Pocket TTS - #78

Merged
libravault-xyz merged 3 commits into
devfrom
fix/tts-testability-and-gaps
Aug 2, 2026
Merged

libravault-xyz merged 3 commits into
devfrom
fix/tts-testability-and-gaps

Conversation

@libravault-xyz

@libravault-xyz libravault-xyz commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Pocket TTS (on-device neural narration) had a complete architecture on Android but no actual synthesis: PocketTtsEngine's initialize()/speak() were TODOs, and the AAR they depended on (third-party/sherpa-onnx/sherpa-onnx-android.aar) was a documented stub that only compiled — no real native code. iOS had no Pocket TTS equivalent at all. This PR closes both gaps.

The previous approach (compiling sherpa-onnx from source locally via NDK/CMake) turned out to be the wrong path: the build script targeted an app module that produces an APK, not a library AAR. sherpa-onnx doesn't publish to Maven Central either — but it does publish prebuilt binaries directly on GitHub Releases for both engine and voice models, on both platforms, which is what this PR uses instead.

Android

  • Real AAR: build-aar.sh now downloads sherpa-onnx's prebuilt v1.13.4 Android release binaries instead of attempting an NDK/CMake source build. Verified the rewritten script reproduces the AAR from scratch.
  • Vendored JNI wrapper: sherpa-onnx's Kotlin Tts.kt (Apache-2.0) copied into core/tts/.../pocket/sherpa/.
  • PocketTtsEngine wired for real: initialize() waits on PocketModelManager, speak() bridges sherpa-onnx's synchronous callback-based generation into a Flow feeding PocketPlayback, speed applies per-call via GenerationConfig.
  • Two real PocketModelManager bugs fixed: POCKET_TTS_MODEL_URL pointed at the engine tarball instead of a voice model, and extraction used GZIPInputStream against sherpa-onnx's actual .tar.bz2 (bzip2) archives. Also fixed: a successfully-downloaded model was never marked ready, so it would have silently re-downloaded on every launch.
  • TtsEngineProvider/PocketTtsEngine testability: injected CoroutineScope via a shared Hilt binding (TtsModule) instead of each hardcoding CoroutineScope(Dispatchers.Default) — closes the gap deferred from test: backfill unit test coverage for repos always mocked in ViewModel tests #74.

iOS (new)

  • PocketTTSEngine.swift wraps the same sherpa-onnx C API (vendored as Sources/KmpInterop/PocketTTS/SherpaOnnx.swift, from the same v1.13.4 tag as the Android AAR) via a bridging header, streaming generated audio through AVAudioEngine/AVAudioPlayerNode.
  • Two static xcframeworks needed: sherpa-onnx itself, and its onnxruntime dependency (sherpa's iOS release binary does not statically include onnxruntime, unlike its size might suggest). Both fetched at build/CI time by third-party/sherpa-onnx/setup-ios.sh (~230MB combined) rather than committed to git — the Android AAR is a conscious ~11MB exception to "don't commit large binaries"; this is 20x bigger, so it's fetched fresh instead (cached in CI).
  • The voice model ships bundled in the app, not downloaded on first use like Android: Foundation has no tar/bzip2 decompression, and the only on-device alternative (linking libbz2.dylib directly) needs headers Apple doesn't ship publicly — a private-API App Store rejection risk. Extracting at build time (where a real tar exists) sidesteps this. Real, deliberate UX difference from Android, documented in SHERPA_ONNX_SETUP.md.
  • TTSEngineProtocol gives the existing TTSEngineBridge (system voice) and the new PocketTTSEngine a shared shape. AppState.ttsEngineType (persisted, exposed in Settings) drives LibravaultDomainBridge.switchTTSEngine(to:), mirroring Android's TtsEngineProvider — including the "start on the reliable system engine, then upgrade" ordering, made race-safe against AppState's own init-time preference load.
  • ios-app-build.yml fetches (and caches) the frameworks/model before building. This dev environment has no Xcode/macOS — xcodebuild in CI is the only thing that can actually verify the Swift/pbxproj changes compile and link. Watching that job closely once this PR is open.

Licensing catch (Android, carries over to iOS's identical voice choice)

PocketVoiceCatalog's original design (WAV reference-audio voice cloning, a bundled "bria" voice) was built around sherpa-onnx's own "Pocket TTS" model family — CC-BY-NC 4.0, non-commercial only, confirmed from the model's own README. LibraVault doesn't have a live paid tier today (KNOWN_LIMITATIONS.md: "no Pro tier beyond the simple unlock"), but does ship Play Billing/license-verification infrastructure (core/licensing) toward one that hasn't launched — a non-commercial-licensed model still risked a cleanup once that goes live, and the "paid Pro tier" framing in an earlier version of this PR/commit history overstated that as already-settled fact rather than in-progress infrastructure (now corrected here and in memory). Piper's usual default voices (lessac, amy) turned out to also be unusable — both are derivatives of a Blizzard-2013-licensed voice whose license also forbids commercial use. Landed on ljspeech, trained from scratch on the public-domain LJSpeech dataset. Full reasoning in SHERPA_ONNX_SETUP.md.

Also in this PR

Added a "Backbone candidate: Zamba2" section to MAMBA_TTS_V2_PLAN.md (the already-existing, explicitly-backlogged custom-model research plan) evaluating Zyphra's Zamba2 hybrid Mamba2+attention architecture as a more concrete alternative to the plan's generic "Mamba backbone" — with the honest caveat that Zamba2's published advantage is measured on long-context prefill workloads Pocket TTS doesn't actually have, and at parameter counts ~100x larger than this plan's 12-30M target. Not a decision, just a documented option for whoever picks that plan up.

Known follow-ups (documented, not done here)

  • Real on-device audio testing on either platform — nothing has actually heard either engine speak on physical hardware or a running Simulator yet. This PR's verification is unit-test + APK-assembly level (Android) and CI-build level (iOS), not a live audio run.
  • core:tts's native libs (~30MB) are bundled into the F-Droid APK too, even though Pocket TTS is runtime-disabled there — core:tts is a shared, non-flavor-scoped dependency via feature:settings. Predates this change, worth revisiting given MAMBA_TTS_V2_PLAN.md's F-Droid purity discussion.

Test plan

  • ./gradlew testFdroidDebugUnitTest testPlayDebugUnitTest testDebugUnitTest — full suite, all modules, both flavors — green
  • ./gradlew :app:assembleFdroidDebug :app:assemblePlayDebug — both flavors package successfully; confirmed the real sherpa-onnx .so libraries are present in the APK
  • Ran build-aar.sh and setup-ios.sh end-to-end locally and confirmed they reproduce/fetch correctly
  • New Swift unit tests (PocketModelManagerTests, UserPreferencesPersistenceTests additions) pass logic review — not yet run under xcodebuild test, pending CI
  • iOS CI build/test (ios-app-build.yml) — pending, will report back once it runs
  • Reviewed the diff (including a self-caught duplicate-KDoc bug from the earlier commit)

🤖 Generated with Claude Code

libravault-xyz and others added 2 commits August 2, 2026 11:10
… injection for testability

Pocket TTS (on-device neural narration, Play flavor only) had a complete
architecture but no actual synthesis: PocketTtsEngine's initialize()/speak()
were TODOs, and the AAR they depended on was a documented stub that only
compiled - no real native code.

Research into completing this found the previous approach (compiling
sherpa-onnx from source locally via NDK/CMake) was the wrong path: the build
script targeted an app module that produces an APK, not a library AAR.
sherpa-onnx doesn't publish to Maven Central either, but it does publish
prebuilt binaries directly on GitHub Releases for both engine and voice
models - a much simpler, lower-risk integration than compiling C++ locally.

- Replaced the stub AAR with a real one built from sherpa-onnx's own
  prebuilt v1.13.4 Android release binaries (third-party/sherpa-onnx/
  build-aar.sh now downloads instead of NDK/CMake-building; verified the
  rewritten script reproduces the AAR).
- Vendored sherpa-onnx's Kotlin JNI wrapper (Apache-2.0) as
  core/tts/.../pocket/sherpa/Tts.kt.
- Wired PocketTtsEngine's TODOs to the real OfflineTts API: initialize()
  waits on PocketModelManager, speak() bridges sherpa-onnx's synchronous
  callback-based generation into a Flow that feeds PocketPlayback, speed
  is applied per-call via GenerationConfig.
- Fixed two real bugs in PocketModelManager found while wiring it up:
  POCKET_TTS_MODEL_URL pointed at the engine tarball instead of a voice
  model, and extraction used GZIPInputStream against sherpa-onnx's actual
  .tar.bz2 archives (now BZip2CompressorInputStream). Also fixed a bug
  where a successfully-downloaded model was never marked ready, so it
  would have silently re-downloaded on every app launch.
- Reworked PocketVoiceCatalog: its original design (WAV reference-audio
  voice cloning, a bundled "bria" voice) was built around sherpa-onnx's own
  "Pocket TTS" model family - which turned out to be CC-BY-NC 4.0,
  non-commercial only, and can't ship in this app's paid Pro tier. Using a
  Piper VITS voice instead required checking that voice's license too:
  the obvious defaults (lessac, amy) are derivatives of a Blizzard-2013
  voice whose license also forbids commercial use. Landed on `ljspeech`,
  trained from scratch on the public-domain LJSpeech dataset. See
  SHERPA_ONNX_SETUP.md for the full reasoning.
- Injected TtsEngineProvider's and PocketTtsEngine's CoroutineScope
  (previously each hardcoded their own CoroutineScope(Dispatchers.Default))
  via a shared Hilt binding in TtsModule, closing the testability gap PR #74
  deferred, and using the same fix to make PocketTtsEngine's new
  ensureModelAvailable()-driven state machine testable too.

Verified: full unit test suite (both flavors, all modules) green, and both
flavors' debug APKs assemble successfully with the real native libraries
correctly packaged (confirmed via `stripDebugSymbols`' packaging log and
inspecting the APK contents directly).

Known follow-up (not done here, documented in POCKET_TTS_PROGRESS.md):
iOS has no Pocket TTS equivalent yet - sherpa-onnx does publish a prebuilt
iOS xcframework, so it's feasible, but is a separate, CI-dependent change
(no Xcode/macOS toolchain in this dev environment to verify Swift changes
locally). Also worth a follow-up: core:tts (and its ~30MB of native libs)
is a shared, non-flavor-scoped dependency, so it's bundled into the F-Droid
APK too even though Pocket TTS is runtime-disabled there - this predates
this change (the same was true of the stub AAR) but is worth revisiting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Self-review of #78 caught two stacked /** */ comments on the same
declaration - only the second one actually attaches as the function's
KDoc, leaving the first as a dangling, tool-invisible comment.
@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: FAILED

❌ iOS Simulator Build & Tests - cancelled
✅ Android Core Modules - success

View run details

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Tests - success
✅ Android Core Modules - success

View run details

…ng framing

Two fixes on top of the Android sherpa-onnx work in this branch:

1. Corrected an inaccurate claim in the earlier commit/PR/memory: LibraVault
   does NOT have a live paid tier today (KNOWN_LIMITATIONS.md: "no Pro tier
   beyond the simple unlock"). It does ship Play Billing/license-verification
   infrastructure (core/licensing) toward one that hasn't launched - the
   licensing reasoning for picking a permissively-licensed voice model still
   holds (avoid a cleanup once that goes live), but the docs/PR description
   overstated the current state as settled fact. Fixed in build.gradle.kts's
   comment, SHERPA_ONNX_SETUP.md, and memory.

2. iOS now has a Pocket TTS engine, matching Android:
   - PocketTTSEngine.swift wraps sherpa-onnx's C API (vendored as
     Sources/KmpInterop/PocketTTS/SherpaOnnx.swift, from the same v1.13.4 tag
     as the Android AAR) via a bridging header, streaming generated audio
     through AVAudioEngine/AVAudioPlayerNode.
   - Two static xcframeworks are needed - sherpa-onnx itself, and its
     onnxruntime dependency (sherpa's iOS release binary does NOT statically
     include onnxruntime, unlike what its size might suggest). Both are
     ~230MB combined, fetched at build/CI time by
     third-party/sherpa-onnx/setup-ios.sh rather than committed - matches
     this project's precedent of keeping large binaries out of git where
     avoidable (the Android AAR is a conscious exception at ~11MB; this is
     20x bigger).
   - The voice model (same URL/checksum/licensing as Android) is bundled
     into the app at build time instead of downloaded on first use like
     Android does: Foundation has no tar/bzip2 decompression, and the only
     on-device alternative (linking libbz2.dylib directly) needs headers
     Apple doesn't ship publicly - a private-API App Store rejection risk.
     Extracting at build time, where a real `tar` exists, sidesteps this
     entirely. Documented as a real platform-driven UX difference from
     Android, not an oversight.
   - TTSEngineProtocol gives the existing TTSEngineBridge (system voice) and
     the new PocketTTSEngine a shared shape. AppState.ttsEngineType
     (persisted via UserPreferencesPersistence, exposed in Settings > Voice)
     drives LibravaultDomainBridge.switchTTSEngine(to:), mirroring Android's
     TtsEngineProvider - including the same "always start on the reliable
     system engine, upgrade to Pocket TTS after" ordering, made race-safe
     against AppState's own init-time preference load.
   - ios-app-build.yml fetches (and caches) the frameworks/model before
     building; xcodebuild itself is the only thing that can actually verify
     this compiles and links, since this dev environment has no Xcode/macOS.

Also added a "Backbone candidate: Zamba2" section to MAMBA_TTS_V2_PLAN.md
(the already-existing, explicitly-backlogged custom-model research plan),
evaluating Zyphra's Zamba2 hybrid Mamba2+attention architecture as a more
concrete alternative to the plan's generic "Mamba backbone" - with the
honest caveat that Zamba2's published advantage is measured on long-context
prefill workloads Pocket TTS doesn't actually have (short per-utterance
text), and at parameter counts ~100x larger than this plan's 12-30M target.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: FAILED

❌ iOS Simulator Build & Tests - failure
✅ Android Core Modules - success

View run details

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Tests - success
✅ Android Core Modules - success

View run details

@libravault-xyz
libravault-xyz merged commit 200a1f6 into dev Aug 2, 2026
7 of 8 checks passed
@libravault-xyz
libravault-xyz deleted the fix/tts-testability-and-gaps branch August 2, 2026 17:13
libravault-xyz added a commit that referenced this pull request Aug 2, 2026
…PDF rendering

Patch release covering real sherpa-onnx Pocket TTS synthesis on Android and
iOS (#78), native PDFKit page rendering on iOS (#79), and the audiobook
orientation-lock fix (#77).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
libravault-xyz added a commit that referenced this pull request Aug 2, 2026
ios-testflight.yml archives independently of ios-app-build.yml and never
got the setup-ios.sh step added in PR #78 - build 24's archive failed with
"There is no XCFramework found at .../sherpa-onnx.xcframework" because the
target links it but nothing had fetched it yet.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant