The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
feat(speech): Pocket TTS and Chatterbox Turbo beside Kokoro, and the selected clip's voice
Jareer6b5d59c2479a
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 933f7e58..3d0f49d3 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -89,6 +89,24 @@ releases - including espeak-ng's data files. Concat mirrors those bundlesand downloads them on demand from that mirror, and never bundles them withthe app. See "The model mirror" below.+The Pocket TTS bundle is Kyutai's Pocket TTS (CC-BY-4.0,+https://huggingface.co/kyutai/pocket-tts, https://kyutai.org) as exported+to ONNX by KevinAHM (https://huggingface.co/KevinAHM/pocket-tts-onnx,+CC-BY-4.0) and packaged in the sherpa-onnx releases, with two sample+recordings from Kyutai's delayed-streams-modeling repository as its named+voices. It is downloaded on demand like the Kokoro bundles. Reading in the+voice of a recording is a use the person doing it is answerable for:+Concat offers it for the narrator's own voice, and Kyutai asks that no+one's voice be cloned without their consent.++Chatterbox Turbo (MIT, https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX,+Resemble AI) is driven through ONNX Runtime directly, from Resemble's own+ONNX export, downloaded on demand like the other voices. Its GPT-2+tokenizer is read by the tokenizers crate (Apache-2.0). Resemble's Python+package stamps a Perth watermark on what it speaks; the ONNX pipeline+carries no such step and Concat adds none, which MIT permits and which+anyone passing the sound off as a person's should know is not there.+## ONNX RuntimeThe cutout models run on Microsoft's ONNX Runtime@@ -142,8 +160,9 @@ what is mirrored, and the digest each download is checked against, ismirror.Mirroring is redistribution, and each model keeps the licence it arrived-under - Apache-2.0 for the Kokoro bundles, SlimSAM and IS-Net, MIT for the-whisper conversions, GPL-3.0 for Robust Video Matting. Those terms are met+under - Apache-2.0 for the Kokoro bundles, SlimSAM and IS-Net, CC-BY-4.0+for Pocket TTS, BSD-3-Clause for Real-ESRGAN, MIT for Chatterbox Turbo and+the whisper conversions, GPL-3.0 for Robust Video Matting. Those terms are metby the attributions above and by the licence files each mirrored archivecarries; a mirrored file is a verbatim copy, never a modification. Nothingin the mirror is bundled with the app, and Concat claims no rights over anydiff --git a/models/manifest.toml b/models/manifest.tomlindex a7ab61a9..ec6736a8 100644--- a/models/manifest.toml+++ b/models/manifest.toml@@ -70,6 +70,18 @@ sha256 = ""licence = "Apache-2.0"upstream = "https://huggingface.co/Xenova/slimsam-77-uniform/resolve/main/onnx/prompt_encoder_mask_decoder.onnx"+# Enhance's restoration model. In the cutout family because the family is+# the engine table a row is checked against, and this one lives in the+# vision crate's beside the cutout models.+[[model]]+id = "enhance-upscale"+family = "cutout"+file = "realesr-general-x4v3.onnx"+bytes = 4866417+sha256 = "1940a93ee08283a0a7286183186357b1688fe9fa8ede74604b424586aaddf112"+licence = "BSD-3-Clause"+upstream = "https://huggingface.co/CoderViking/realesr-general-x4v3-onnx/resolve/main/realesr-general-x4v3.onnx"+# ── Text to speech ───────────────────────────────────────────────────────# src/crates/concat-speech/src/tts.rs. Kokoro v1.0 multi-language, the# official sherpa-onnx conversions; the two differ only in quantisation.@@ -92,6 +104,105 @@ sha256 = ""licence = "Apache-2.0"upstream = "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/kokoro-multi-lang-v1_0.tar.bz2"+# Kyutai's Pocket TTS, the sherpa-onnx int8 conversion: English, and any+# voice it is given a few seconds of. The weights are CC-BY-4.0 (Kyutai);+# the ONNX export is KevinAHM/pocket-tts-onnx under the same terms.+[[model]]+id = "pocket-tts-int8-2026-01-26"+family = "tts"+file = "sherpa-onnx-pocket-tts-int8-2026-01-26.tar.bz2"+bytes = 98336520+sha256 = "2f3b88823cbbb9bf0b2477ec8ae7b3fec417b3a87b6bb5f256dba66f2ad967cb"+licence = "CC-BY-4.0"+upstream = "https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/sherpa-onnx-pocket-tts-int8-2026-01-26.tar.bz2"++# ── Chatterbox ───────────────────────────────────────────────────────────+# src/crates/concat-speech/src/chatterbox.rs. Resemble AI's Chatterbox+# Turbo, the quantised ONNX export: nine files that make one bundle, each+# a row since the mirror is flat. The `file` names carry the bundle's+# name; the engine puts each back under the name its graph expects.++[[model]]+id = "chatterbox-turbo-tokenizer.json"+family = "chatterbox"+file = "chatterbox-turbo-tokenizer.json"+bytes = 3562272+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/tokenizer.json"++[[model]]+id = "chatterbox-turbo-embed_tokens_quantized.onnx"+family = "chatterbox"+file = "chatterbox-turbo-embed_tokens_quantized.onnx"+bytes = 2887+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/embed_tokens_quantized.onnx"++[[model]]+id = "chatterbox-turbo-language_model_quantized.onnx"+family = "chatterbox"+file = "chatterbox-turbo-language_model_quantized.onnx"+bytes = 279670+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/language_model_quantized.onnx"++[[model]]+id = "chatterbox-turbo-speech_encoder_quantized.onnx"+family = "chatterbox"+file = "chatterbox-turbo-speech_encoder_quantized.onnx"+bytes = 1205728+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/speech_encoder_quantized.onnx"++[[model]]+id = "chatterbox-turbo-conditional_decoder_quantized.onnx"+family = "chatterbox"+file = "chatterbox-turbo-conditional_decoder_quantized.onnx"+bytes = 2202035+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/conditional_decoder_quantized.onnx"++[[model]]+id = "chatterbox-turbo-embed_tokens_quantized.onnx_data"+family = "chatterbox"+file = "chatterbox-turbo-embed_tokens_quantized.onnx_data"+bytes = 67297376+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/embed_tokens_quantized.onnx_data"++[[model]]+id = "chatterbox-turbo-conditional_decoder_quantized.onnx_data"+family = "chatterbox"+file = "chatterbox-turbo-conditional_decoder_quantized.onnx_data"+bytes = 326548688+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/conditional_decoder_quantized.onnx_data"++[[model]]+id = "chatterbox-turbo-speech_encoder_quantized.onnx_data"+family = "chatterbox"+file = "chatterbox-turbo-speech_encoder_quantized.onnx_data"+bytes = 354676576+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/speech_encoder_quantized.onnx_data"++[[model]]+id = "chatterbox-turbo-language_model_quantized.onnx_data"+family = "chatterbox"+file = "chatterbox-turbo-language_model_quantized.onnx_data"+bytes = 367962860+sha256 = ""+licence = "MIT"+upstream = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/language_model_quantized.onnx_data"+# ── Transcription ────────────────────────────────────────────────────────# src/crates/concat-speech/src/transcribe.rs. whisper.cpp's GGML# conversions of OpenAI's whisper.diff --git a/scripts/models.py b/scripts/models.pyindex c7155af6..f18b0be5 100755--- a/scripts/models.py+++ b/scripts/models.py@@ -35,6 +35,7 @@ HOST_MODELS = CRATES / "concat-host" / "src" / "models.rs"TABLES = {"cutout": CRATES / "concat-vision" / "src" / "models.rs","tts": CRATES / "concat-speech" / "src" / "tts.rs",+ "chatterbox": CRATES / "concat-speech" / "src" / "chatterbox.rs","whisper": CRATES / "concat-speech" / "src" / "transcribe.rs",}diff --git a/src/Cargo.lock b/src/Cargo.lockindex fb7c04a5..e6c2ea34 100644--- a/src/Cargo.lock+++ b/src/Cargo.lock@@ -152,6 +152,7 @@ dependencies = ["cfg-if","getrandom 0.3.4","once_cell",+ "serde","version_check","zerocopy",]@@ -693,6 +694,12 @@ dependencies = ["tower-service",]+[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"+[[package]]name = "base64"version = "0.22.1"@@ -747,15 +754,30 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec 0.8.0",+]+[[package]]name = "bit-set"version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd"dependencies = [- "bit-vec",+ "bit-vec 0.9.1",]+[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]name = "bit-vec"version = "0.9.1"@@ -998,6 +1020,15 @@ dependencies = ["wayland-client",]+[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]+[[package]]name = "cc"version = "1.4.4"@@ -1190,6 +1221,21 @@ dependencies = ["memchr",]+[[package]]+name = "compact_str"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"+dependencies = [+ "castaway",+ "cfg-if",+ "itoa",+ "rustversion",+ "ryu",+ "serde",+ "static_assertions",+]+[[package]]name = "concat"version = "0.2.3"@@ -1304,6 +1350,7 @@ dependencies = ["cpal","log","memmap2",+ "png 0.17.16","serde","serde_json","sha2",@@ -1379,10 +1426,12 @@ dependencies = ["bzip2 0.6.1","concat-host","concat-media",+ "ort","serde","serde_json","sherpa-onnx","tar",+ "tokenizers","ureq 2.12.1","whisper-rs",]@@ -1675,6 +1724,56 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "daachorse"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5614204febbc33cc07a2806aa6440b904ac012b68eecc37f4493ea4a76455a3d"++[[package]]+name = "darling"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.119",+]++[[package]]+name = "darling_macro"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"+dependencies = [+ "darling_core",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "dary_heap"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"+dependencies = [+ "serde",+]+[[package]]name = "dasp_sample"version = "0.11.0"@@ -1720,6 +1819,37 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "derive_builder"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"+dependencies = [+ "derive_builder_macro",+]++[[package]]+name = "derive_builder_core"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "derive_builder_macro"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"+dependencies = [+ "derive_builder_core",+ "syn 2.0.119",+]+[[package]]name = "derive_more"version = "2.1.1"@@ -1955,6 +2085,12 @@ version = "3.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"+[[package]]+name = "esaxx-rs"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"+[[package]]name = "euclid"version = "0.22.14"@@ -2001,6 +2137,17 @@ dependencies = ["zune-inflate",]+[[package]]+name = "fancy-regex"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8"+dependencies = [+ "bit-set 0.8.0",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fastrand"version = "2.5.0"@@ -3342,6 +3489,12 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"+[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+[[package]]name = "idna"version = "1.1.0"@@ -3951,6 +4104,22 @@ dependencies = ["libc",]+[[package]]+name = "macro_rules_attribute"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c"+dependencies = [+ "macro_rules_attribute-proc_macro",+ "pastey 0.2.3",+]++[[package]]+name = "macro_rules_attribute-proc_macro"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c"+[[package]]name = "matchit"version = "0.8.4"@@ -4066,6 +4235,28 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "monostate"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"+dependencies = [+ "monostate-impl",+ "serde",+ "serde_core",+]++[[package]]+name = "monostate-impl"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "moxcms"version = "0.8.1"@@ -4108,7 +4299,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df"dependencies = ["arrayvec",- "bit-set",+ "bit-set 0.9.1","bitflags 2.13.1","cfg-if","cfg_aliases",@@ -5615,6 +5806,17 @@ dependencies = ["rayon-core",]+[[package]]+name = "rayon-cond"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"+dependencies = [+ "either",+ "itertools 0.14.0",+ "rayon",+]+[[package]]name = "rayon-core"version = "1.13.0"@@ -5927,6 +6129,12 @@ dependencies = ["unicode-script",]+[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]name = "same-file"version = "1.0.6"@@ -6474,6 +6682,18 @@ dependencies = ["bitflags 2.13.1",]+[[package]]+name = "spm_precompiled"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"+dependencies = [+ "base64 0.13.1",+ "nom 7.1.3",+ "serde",+ "unicode-segmentation",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -6823,6 +7043,39 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"+[[package]]+name = "tokenizers"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7afbf6e88718afcc138bad01d6ccc3051dbbc3b2ce9793d8b8a3aeb610969cfc"+dependencies = [+ "ahash",+ "compact_str",+ "daachorse",+ "dary_heap",+ "derive_builder",+ "esaxx-rs",+ "fancy-regex",+ "getrandom 0.3.4",+ "itertools 0.14.0",+ "log",+ "macro_rules_attribute",+ "monostate",+ "paste",+ "rand",+ "rayon",+ "rayon-cond",+ "regex",+ "regex-syntax",+ "serde",+ "serde_json",+ "spm_precompiled",+ "thiserror 2.0.20",+ "unicode-normalization-alignments",+ "unicode-segmentation",+ "unicode_categories",+]+[[package]]name = "tokio"version = "1.53.1"@@ -7147,6 +7400,15 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"+[[package]]+name = "unicode-normalization-alignments"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"+dependencies = [+ "smallvec",+]+[[package]]name = "unicode-properties"version = "0.1.4"@@ -7189,6 +7451,12 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]+name = "unicode_categories"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"+[[package]]name = "untrusted"version = "0.9.0"@@ -7693,8 +7961,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7"dependencies = ["arrayvec",- "bit-set",- "bit-vec",+ "bit-set 0.9.1",+ "bit-vec 0.9.1","bitflags 2.13.1","bytemuck","cfg_aliases",@@ -7755,7 +8023,7 @@ dependencies = ["android_system_properties","arrayvec","ash",- "bit-set",+ "bit-set 0.9.1","bitflags 2.13.1","block2 0.6.2","bytemuck",diff --git a/src/crates/concat-speech/Cargo.toml b/src/crates/concat-speech/Cargo.tomlindex 941590d7..05379172 100644--- a/src/crates/concat-speech/Cargo.toml+++ b/src/crates/concat-speech/Cargo.toml@@ -22,6 +22,13 @@ ureq = "2"tar = "0.4"bzip2 = "0.6"+# Chatterbox: driven through ONNX Runtime directly, since sherpa-onnx has no+# such model, with its GPT-2 tokenizer read by the tokenizers crate - the+# pure-Rust regex backend, so no C library rides along. Behind `chatterbox`,+# which the desktop app turns on: a gigabyte of model is not for a phone.+ort = { workspace = true, optional = true }+tokenizers = { version = "0.23", optional = true, default-features = false, features = ["fancy-regex"] }+# Transcription: whisper.cpp in-process. Built from source by cmake at build# time; on macOS with Metal so the encoder runs on the GPU.whisper-rs = "0.16"@@ -57,5 +64,8 @@ sherpa-onnx = { version = "1.13", default-features = false, features = ["shared"[target.'cfg(target_os = "macos")'.dependencies]whisper-rs = { version = "0.16", features = ["metal"] }+[features]+chatterbox = ["dep:ort", "dep:tokenizers"]+[lints]workspace = truediff --git a/src/crates/concat-speech/src/chatterbox.rs b/src/crates/concat-speech/src/chatterbox.rsnew file mode 100644index 00000000..c5a34700--- /dev/null+++ b/src/crates/concat-speech/src/chatterbox.rs@@ -0,0 +1,768 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! Chatterbox Turbo: Resemble AI's open voice, run through ONNX Runtime.+//!+//! sherpa-onnx has no such model, so this one is driven here directly,+//! the way Resemble's own reference script drives its ONNX export. Four+//! networks: a speech encoder that turns a few seconds of someone talking+//! into what the voice sounds like, a text embedding, a language model+//! that writes speech tokens one at a time with a key-value cache behind+//! it, and a decoder that turns the tokens into sound. The text can carry+//! tags the model was taught - `[laugh]`, `[chuckle]`, `[sigh]` - and it+//! reads them as what they say.+//!+//! The bundle is the quantised export, nine files and a little over a+//! gigabyte, fetched one by one into `<app data>/tts-models/<id>/onnx/`+//! under the names the graphs expect their weights beside them as. Each+//! file lands in a `.part` and is renamed whole, so a torn download is+//! never mistaken for a model.+//!+//! Every voice is a recording: there are no speakers built in. The sheet+//! offers the selected clip's own. Resemble's Python stamps its output+//! with a watermark; the ONNX path carries no such step, and this one+//! adds none.++use std::path::{Path, PathBuf};+use std::sync::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};++use ort::session::Session;+use ort::value::Tensor;++use crate::DownloadProgress;++/// The bundle id, as the settings panel and a request name it.+pub const BUNDLE_ID: &str = "chatterbox-turbo-q8";++/// What the model speaks at.+pub const SAMPLE_RATE: u32 = 24_000;+/// Speech tokens a second: how long a token is in sound.+const TOKENS_PER_SECOND: f32 = 25.0;+/// The token the language model starts writing after.+const START_SPEECH_TOKEN: i64 = 6561;+/// The token that means it has finished.+const STOP_SPEECH_TOKEN: i64 = 6562;+/// A token of silence, three of which end every utterance.+const SILENCE_TOKEN: i64 = 4299;+/// The language model's shape: attention heads, their width, its depth.+const KV_HEADS: usize = 16;+const HEAD_DIM: usize = 64;+const LAYERS: usize = 24;+/// Resemble's reference setting: a token the model has written is that+/// much less likely to be written again.+const REPETITION_PENALTY: f32 = 1.2;+/// The most tokens one chunk of text may take: forty seconds of speech.+const MAX_NEW_TOKENS: usize = 1024;+/// A chunk of text longer than this is read as two.+const CHUNK_CHARS: usize = 250;+/// Between chunks.+const GAP_SECONDS: f32 = 0.25;++/// One file of the bundle, as the mirror and the table name it.+struct KnownModel {+ /// What the file is called on the mirror: the bundle's name and the+ /// file's own, so two exports never collide on one flat release.+ id: &'static str,+ /// What the file is called on disk, which is what the graphs expect+ /// of their weights.+ local: &'static str,+ upstream: &'static str,+ bytes: u64,+ sha256: &'static str,+}++/// Where every file comes from; the test holds the table to it.+#[cfg(test)]+const UPSTREAM: &str = "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/";++/// The nine files, largest last so a torn download costs the least.+const FILES: &[KnownModel] = &[+ KnownModel {+ id: "chatterbox-turbo-tokenizer.json",+ local: "tokenizer.json",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/tokenizer.json",+ bytes: 3_562_272,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-embed_tokens_quantized.onnx",+ local: "onnx/embed_tokens_quantized.onnx",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/embed_tokens_quantized.onnx",+ bytes: 2_887,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-language_model_quantized.onnx",+ local: "onnx/language_model_quantized.onnx",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/language_model_quantized.onnx",+ bytes: 279_670,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-speech_encoder_quantized.onnx",+ local: "onnx/speech_encoder_quantized.onnx",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/speech_encoder_quantized.onnx",+ bytes: 1_205_728,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-conditional_decoder_quantized.onnx",+ local: "onnx/conditional_decoder_quantized.onnx",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/conditional_decoder_quantized.onnx",+ bytes: 2_202_035,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-embed_tokens_quantized.onnx_data",+ local: "onnx/embed_tokens_quantized.onnx_data",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/embed_tokens_quantized.onnx_data",+ bytes: 67_297_376,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-conditional_decoder_quantized.onnx_data",+ local: "onnx/conditional_decoder_quantized.onnx_data",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/conditional_decoder_quantized.onnx_data",+ bytes: 326_548_688,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-speech_encoder_quantized.onnx_data",+ local: "onnx/speech_encoder_quantized.onnx_data",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/speech_encoder_quantized.onnx_data",+ bytes: 354_676_576,+ sha256: "",+ },+ KnownModel {+ id: "chatterbox-turbo-language_model_quantized.onnx_data",+ local: "onnx/language_model_quantized.onnx_data",+ upstream: "https://huggingface.co/ResembleAI/chatterbox-turbo-ONNX/resolve/main/onnx/language_model_quantized.onnx_data",+ bytes: 367_962_860,+ sha256: "",+ },+];++/// The whole bundle's size, for the settings row.+pub const BUNDLE_BYTES: u64 = 1_123_738_092;++/// Whether every file of the bundle is in `dir`, whole.+pub fn installed(dir: &Path) -> bool {+ FILES.iter().all(|file| {+ std::fs::metadata(dir.join(file.local)).is_ok_and(|meta| meta.is_file() && meta.len() > 0)+ })+}++/// Fetches whatever of the bundle is not in `dir` yet, file by file, the+/// mirror first and Resemble's upstream second, reporting the bytes of+/// the whole as one download. Blocks: run it on its own thread.+pub fn download(+ dir: &Path,+ cancel: &AtomicBool,+ progress: &mut dyn FnMut(DownloadProgress),+) -> Result<(), String> {+ let total: u64 = FILES.iter().map(|file| file.bytes).sum();+ let mut before: u64 = 0;+ for file in FILES {+ let target = dir.join(file.local);+ if std::fs::metadata(&target).is_ok_and(|meta| meta.is_file() && meta.len() > 0) {+ before += file.bytes;+ continue;+ }+ if let Some(parent) = target.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("could not create {}: {error}", parent.display()))?;+ }+ let partial = target.with_extension(match target.extension().and_then(|e| e.to_str()) {+ Some(extension) => format!("{extension}.part"),+ None => "part".to_owned(),+ });+ let so_far = before;+ crate::fetch_model(+ file.id,+ file.upstream,+ &partial,+ BUNDLE_ID,+ file.bytes,+ file.sha256,+ cancel,+ &mut |report: DownloadProgress| {+ progress(DownloadProgress {+ id: BUNDLE_ID.to_owned(),+ received: so_far + report.received.min(file.bytes),+ total,+ unpacking: false,+ done: false,+ });+ },+ )?;+ std::fs::rename(&partial, &target)+ .map_err(|error| format!("could not finish {}: {error}", target.display()))?;+ before += file.bytes;+ if cancel.load(Ordering::Relaxed) {+ return Err("download cancelled".to_owned());+ }+ }+ progress(DownloadProgress {+ id: BUNDLE_ID.to_owned(),+ received: total,+ total,+ unpacking: false,+ done: true,+ });+ Ok(())+}++/// The four networks and the tokenizer, loaded once.+pub struct Engine {+ tokenizer: tokenizers::Tokenizer,+ speech_encoder: Mutex<Session>,+ embed_tokens: Mutex<Session>,+ language_model: Mutex<Session>,+ decoder: Mutex<Session>,+}++/// What the speech encoder heard in a recording: everything the other+/// networks need to speak in that voice.+struct Voice {+ /// `[1, T, 1024]`, prepended to the text's embedding.+ features: (Vec<usize>, Vec<f32>),+ /// The recording's own speech tokens, which the output continues.+ prompt: Vec<i64>,+ /// `[1, 192]`.+ embedding: (Vec<usize>, Vec<f32>),+ /// `[1, F, 80]`.+ spectrum: (Vec<usize>, Vec<f32>),+}++fn session(path: &Path) -> Result<Session, String> {+ let threads = std::thread::available_parallelism()+ .map(|count| count.get())+ .unwrap_or(1)+ .clamp(1, 8);+ Session::builder()+ .map_err(|error| format!("onnx runtime: {error}"))?+ .with_intra_threads(threads)+ .map_err(|error| format!("onnx runtime: {error}"))?+ .commit_from_file(path)+ .map_err(|error| format!("{}: {error}", path.display()))+}++/// One named input, as a session takes it.+type Fed = (+ std::borrow::Cow<'static, str>,+ ort::session::SessionInputValue<'static>,+);++fn feed(name: impl Into<std::borrow::Cow<'static, str>>, value: ort::value::Value) -> Fed {+ (name.into(), value.into())+}++fn tensor_f32(dims: Vec<usize>, data: Vec<f32>) -> Result<ort::value::Value, String> {+ Tensor::from_array((dims, data))+ .map(|tensor| tensor.into_dyn())+ .map_err(|error| format!("chatterbox input: {error}"))+}++fn tensor_i64(dims: Vec<usize>, data: Vec<i64>) -> Result<ort::value::Value, String> {+ Tensor::from_array((dims, data))+ .map(|tensor| tensor.into_dyn())+ .map_err(|error| format!("chatterbox input: {error}"))+}++fn take_f32(+ outputs: &ort::session::SessionOutputs<'_>,+ name: &str,+) -> Result<(Vec<usize>, Vec<f32>), String> {+ let value = outputs+ .get(name)+ .ok_or_else(|| format!("chatterbox: the model has no output {name:?}"))?;+ let (shape, data) = value+ .try_extract_tensor::<f32>()+ .map_err(|error| format!("chatterbox output {name}: {error}"))?;+ Ok((+ shape.iter().map(|&d| d.max(0) as usize).collect(),+ data.to_vec(),+ ))+}++fn take_i64(outputs: &ort::session::SessionOutputs<'_>, name: &str) -> Result<Vec<i64>, String> {+ let value = outputs+ .get(name)+ .ok_or_else(|| format!("chatterbox: the model has no output {name:?}"))?;+ let (_, data) = value+ .try_extract_tensor::<i64>()+ .map_err(|error| format!("chatterbox output {name}: {error}"))?;+ Ok(data.to_vec())+}++impl Engine {+ /// Loads the bundle in `dir`.+ pub fn load(dir: &Path) -> Result<Engine, String> {+ if !installed(dir) {+ return Err("the Chatterbox bundle is incomplete - re-download it".to_owned());+ }+ let tokenizer = tokenizers::Tokenizer::from_file(dir.join("tokenizer.json"))+ .map_err(|error| format!("chatterbox tokenizer: {error}"))?;+ let onnx = dir.join("onnx");+ Ok(Engine {+ tokenizer,+ speech_encoder: Mutex::new(session(&onnx.join("speech_encoder_quantized.onnx"))?),+ embed_tokens: Mutex::new(session(&onnx.join("embed_tokens_quantized.onnx"))?),+ language_model: Mutex::new(session(&onnx.join("language_model_quantized.onnx"))?),+ decoder: Mutex::new(session(&onnx.join("conditional_decoder_quantized.onnx"))?),+ })+ }++ /// Reads `text` in the voice of `reference`, mono samples at+ /// [`SAMPLE_RATE`]. Long text is read a chunk at a time with a short+ /// gap between; `progress` is told `0..=1` as tokens are written, and+ /// `cancel` stops it at the next token.+ pub fn speak(+ &self,+ text: &str,+ reference: &[f32],+ cancel: &AtomicBool,+ progress: &mut dyn FnMut(f32),+ ) -> Result<Vec<f32>, String> {+ let voice = self.hear(reference)?;+ let chunks = chunks(text);+ if chunks.is_empty() {+ return Err("nothing to say: the text is empty".to_owned());+ }+ let expected: usize = chunks.iter().map(|chunk| expected_tokens(chunk)).sum();+ let mut written = 0usize;+ let mut samples = Vec::new();+ for (index, chunk) in chunks.iter().enumerate() {+ if index > 0 {+ samples.extend(std::iter::repeat_n(+ 0.0f32,+ (SAMPLE_RATE as f32 * GAP_SECONDS) as usize,+ ));+ }+ let tokens = self.write(chunk, &voice, cancel, &mut |count| {+ progress(((written + count) as f32 / expected.max(1) as f32).min(0.95));+ })?;+ written += tokens.len();+ let wave = self.decode(&voice, &tokens)?;+ samples.extend(wave);+ }+ progress(1.0);+ Ok(samples)+ }++ /// The speech encoder over the recording.+ fn hear(&self, reference: &[f32]) -> Result<Voice, String> {+ if reference.len() < SAMPLE_RATE as usize / 2 {+ return Err("too little sound to take a voice from".to_owned());+ }+ let mut encoder = self+ .speech_encoder+ .lock()+ .map_err(|_| "chatterbox: encoder poisoned")?;+ let audio = tensor_f32(vec![1, reference.len()], reference.to_vec())?;+ let outputs = encoder+ .run(vec![feed("audio_values", audio)])+ .map_err(|error| format!("chatterbox speech encoder: {error}"))?;+ Ok(Voice {+ features: take_f32(&outputs, "audio_features")?,+ prompt: take_i64(&outputs, "audio_tokens")?,+ embedding: take_f32(&outputs, "speaker_embeddings")?,+ spectrum: take_f32(&outputs, "speaker_features")?,+ })+ }++ /// The language model over one chunk: the speech tokens it writes,+ /// without the start and stop tokens.+ fn write(+ &self,+ chunk: &str,+ voice: &Voice,+ cancel: &AtomicBool,+ progress: &mut dyn FnMut(usize),+ ) -> Result<Vec<i64>, String> {+ let encoding = self+ .tokenizer+ .encode(chunk, false)+ .map_err(|error| format!("chatterbox tokenizer: {error}"))?;+ let text_ids: Vec<i64> = encoding.get_ids().iter().map(|&id| i64::from(id)).collect();+ if text_ids.is_empty() {+ return Ok(Vec::new());+ }+ let mut embed = self+ .embed_tokens+ .lock()+ .map_err(|_| "chatterbox: embedding poisoned")?;+ let mut model = self+ .language_model+ .lock()+ .map_err(|_| "chatterbox: model poisoned")?;++ // The first step reads the voice, the text and the start token+ // together; every later step reads one token with the cache.+ let embed_ids =+ |embed: &mut Session, ids: &[i64]| -> Result<(Vec<usize>, Vec<f32>), String> {+ let outputs = embed+ .run(vec![feed(+ "input_ids",+ tensor_i64(vec![1, ids.len()], ids.to_vec())?,+ )])+ .map_err(|error| format!("chatterbox embedding: {error}"))?;+ take_f32(&outputs, "inputs_embeds")+ };+ let (_, text_embeds) = embed_ids(&mut embed, &text_ids)?;+ let (_, start_embed) = embed_ids(&mut embed, &[START_SPEECH_TOKEN])?;+ let width = voice.features.0[2];+ let mut embeds = voice.features.1.clone();+ embeds.extend_from_slice(&text_embeds);+ embeds.extend_from_slice(&start_embed);+ let mut seq_len = embeds.len() / width;+ let mut total_len = seq_len;+ let mut position = 0usize;++ let mut cache: Vec<Option<ort::value::Value>> = (0..LAYERS * 2).map(|_| None).collect();+ let mut generated: Vec<i64> = vec![START_SPEECH_TOKEN];+ for step in 0..MAX_NEW_TOKENS {+ if cancel.load(Ordering::Relaxed) {+ return Err("speech generation cancelled".to_owned());+ }+ let mut inputs: Vec<Fed> = Vec::with_capacity(3 + LAYERS * 2);+ inputs.push(feed(+ "inputs_embeds",+ tensor_f32(vec![1, seq_len, width], std::mem::take(&mut embeds))?,+ ));+ inputs.push(feed(+ "attention_mask",+ tensor_i64(vec![1, total_len], vec![1; total_len])?,+ ));+ inputs.push(feed(+ "position_ids",+ tensor_i64(+ vec![1, seq_len],+ (position..position + seq_len).map(|p| p as i64).collect(),+ )?,+ ));+ for layer in 0..LAYERS {+ for (slot, kind) in ["key", "value"].iter().enumerate() {+ let value = match cache[layer * 2 + slot].take() {+ Some(value) => value,+ None => tensor_f32(vec![1, KV_HEADS, 0, HEAD_DIM], Vec::new())?,+ };+ inputs.push(feed(format!("past_key_values.{layer}.{kind}"), value));+ }+ }+ let mut outputs = model+ .run(inputs)+ .map_err(|error| format!("chatterbox language model: {error}"))?;+ let (logits_shape, logits) = take_f32(&outputs, "logits")?;+ let vocab = logits_shape[2];+ let last = &logits[(logits_shape[1] - 1) * vocab..];+ let next = next_token(last, &generated, REPETITION_PENALTY);+ for layer in 0..LAYERS {+ for (slot, kind) in ["key", "value"].iter().enumerate() {+ let name = format!("present.{layer}.{kind}");+ cache[layer * 2 + slot] =+ Some(outputs.remove(name.as_str()).ok_or_else(|| {+ format!("chatterbox: the model has no output {name:?}")+ })?);+ }+ }+ generated.push(next);+ progress(step + 1);+ if next == STOP_SPEECH_TOKEN {+ break;+ }+ position += seq_len;+ let (_, next_embed) = embed_ids(&mut embed, &[next])?;+ embeds = next_embed;+ seq_len = 1;+ total_len += 1;+ }+ Ok(spoken(&generated))+ }++ /// The decoder over the recording's tokens, the written ones, and a+ /// beat of silence: sound.+ fn decode(&self, voice: &Voice, tokens: &[i64]) -> Result<Vec<f32>, String> {+ let all = with_prompt(&voice.prompt, tokens);+ let mut decoder = self+ .decoder+ .lock()+ .map_err(|_| "chatterbox: decoder poisoned")?;+ let outputs = decoder+ .run(vec![+ feed("speech_tokens", tensor_i64(vec![1, all.len()], all)?),+ feed(+ "speaker_embeddings",+ tensor_f32(voice.embedding.0.clone(), voice.embedding.1.clone())?,+ ),+ feed(+ "speaker_features",+ tensor_f32(voice.spectrum.0.clone(), voice.spectrum.1.clone())?,+ ),+ ])+ .map_err(|error| format!("chatterbox decoder: {error}"))?;+ let (_, wave) = take_f32(&outputs, "waveform")?;+ Ok(wave)+ }+}++/// The most likely next token, with every token already written made+/// [`REPETITION_PENALTY`] times less likely: a score below zero is+/// multiplied by the penalty, one above divided by it, as Resemble's+/// reference does.+pub fn next_token(logits: &[f32], written: &[i64], penalty: f32) -> i64 {+ let mut best = 0usize;+ let mut best_score = f32::NEG_INFINITY;+ for (index, &score) in logits.iter().enumerate() {+ let score = if written.contains(&(index as i64)) {+ if score < 0.0 {+ score * penalty+ } else {+ score / penalty+ }+ } else {+ score+ };+ if score > best_score {+ best_score = score;+ best = index;+ }+ }+ best as i64+}++/// The speech in a written sequence: without the start token, and+/// without the stop token when it ended on one.+pub fn spoken(generated: &[i64]) -> Vec<i64> {+ let body = generated.get(1..).unwrap_or(&[]);+ match body.split_last() {+ Some((&last, rest)) if last == STOP_SPEECH_TOKEN => rest.to_vec(),+ _ => body.to_vec(),+ }+}++/// What the decoder reads: the recording's own tokens, then the written+/// ones, then three of silence so the sound ends rather than stops.+pub fn with_prompt(prompt: &[i64], tokens: &[i64]) -> Vec<i64> {+ let mut all = Vec::with_capacity(prompt.len() + tokens.len() + 3);+ all.extend_from_slice(prompt);+ all.extend_from_slice(tokens);+ all.extend_from_slice(&[SILENCE_TOKEN; 3]);+ all+}++/// `text` as the chunks it is read in: sentences, joined up to+/// [`CHUNK_CHARS`] each, so the model never writes more at once than it+/// keeps straight and a long script still reads as one.+pub fn chunks(text: &str) -> Vec<String> {+ let mut sentences: Vec<String> = Vec::new();+ let mut current = String::new();+ let mut chars = text.chars().peekable();+ while let Some(c) = chars.next() {+ current.push(c);+ // A full stop ends a sentence when a space follows, so "2.5" does+ // not; a line break ends one whatever follows.+ let ends = c == '\n'+ || (matches!(c, '.' | '!' | '?')+ && chars.peek().is_none_or(|next| next.is_whitespace()));+ if ends {+ sentences.push(std::mem::take(&mut current));+ }+ }+ sentences.push(current);+ let mut chunks: Vec<String> = Vec::new();+ for sentence in sentences {+ // One space between words, whatever the script's own spacing.+ let sentence = sentence.split_whitespace().collect::<Vec<_>>().join(" ");+ if sentence.is_empty() {+ continue;+ }+ let sentence = sentence.as_str();+ match chunks.last_mut() {+ Some(last) if last.chars().count() + 1 + sentence.chars().count() <= CHUNK_CHARS => {+ last.push(' ');+ last.push_str(sentence);+ }+ _ => chunks.push(sentence.to_owned()),+ }+ }+ chunks+}++/// About how many speech tokens `chunk` takes, for the readout: fifteen+/// characters a second is ordinary narration.+fn expected_tokens(chunk: &str) -> usize {+ ((chunk.chars().count() as f32 / 15.0) * TOKENS_PER_SECOND) as usize + 10+}++/// `samples` as a 16-bit mono WAV file.+pub fn wav_bytes(samples: &[f32], rate: u32) -> Vec<u8> {+ let data_len = (samples.len() * 2) as u32;+ let mut out = Vec::with_capacity(44 + samples.len() * 2);+ out.extend_from_slice(b"RIFF");+ out.extend_from_slice(&(36 + data_len).to_le_bytes());+ out.extend_from_slice(b"WAVE");+ out.extend_from_slice(b"fmt ");+ out.extend_from_slice(&16u32.to_le_bytes());+ out.extend_from_slice(&1u16.to_le_bytes());+ out.extend_from_slice(&1u16.to_le_bytes());+ out.extend_from_slice(&rate.to_le_bytes());+ out.extend_from_slice(&(rate * 2).to_le_bytes());+ out.extend_from_slice(&2u16.to_le_bytes());+ out.extend_from_slice(&16u16.to_le_bytes());+ out.extend_from_slice(b"data");+ out.extend_from_slice(&data_len.to_le_bytes());+ for &sample in samples {+ let value = (sample.clamp(-1.0, 1.0) * 32767.0).round() as i16;+ out.extend_from_slice(&value.to_le_bytes());+ }+ out+}++/// Where the bundle lives under the models folder.+pub fn bundle_dir(models: &Path) -> PathBuf {+ models.join(BUNDLE_ID)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_table_names_nine_distinct_files_with_the_bundle_in_front() {+ assert_eq!(FILES.len(), 9);+ let mut ids: Vec<&str> = FILES.iter().map(|file| file.id).collect();+ ids.sort_unstable();+ ids.dedup();+ assert_eq!(ids.len(), 9, "an id serves two files");+ assert_eq!(+ FILES.iter().map(|file| file.bytes).sum::<u64>(),+ BUNDLE_BYTES+ );+ for file in FILES {+ assert!(file.id.starts_with("chatterbox-turbo-"), "{}", file.id);+ assert!(file.upstream.starts_with(UPSTREAM), "{}", file.upstream);+ assert!(+ file.upstream+ .ends_with(file.local.rsplit('/').next().unwrap())+ );+ assert!(file.bytes > 0);+ assert!(!file.local.starts_with('/'));+ }+ // Graphs before their weights: the small files land first.+ let graphs = FILES+ .iter()+ .position(|f| f.local.ends_with(".onnx"))+ .unwrap();+ let data = FILES+ .iter()+ .position(|f| f.local.ends_with(".onnx_data"))+ .unwrap();+ assert!(graphs < data);+ // Nothing is installed in an empty folder, and nothing panics.+ let dir = std::env::temp_dir().join(format!("concat-chatterbox-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ assert!(!installed(&dir));+ std::fs::create_dir_all(dir.join("onnx")).expect("mkdir");+ std::fs::write(dir.join("tokenizer.json"), b"{}").expect("write");+ assert!(!installed(&dir), "one file is not the bundle");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_penalty_turns_a_written_token_away_and_the_best_is_picked() {+ // Unwritten: the largest wins.+ assert_eq!(next_token(&[0.1, 0.9, 0.5], &[], 1.2), 1);+ // Written and positive: divided, so a close second overtakes it.+ assert_eq!(next_token(&[0.8, 0.9, 0.5], &[1], 1.2), 0);+ // Written and negative: multiplied further down.+ assert_eq!(next_token(&[-0.5, -0.55, -1.0], &[0], 1.2), 1);+ // A penalty of one changes nothing.+ assert_eq!(next_token(&[0.8, 0.9, 0.5], &[1], 1.0), 1);+ // Ties go to the first; an empty vocabulary gives token 0 rather+ // than panicking.+ assert_eq!(next_token(&[0.3, 0.3], &[], 1.2), 0);+ assert_eq!(next_token(&[], &[], 1.2), 0);+ assert_eq!(next_token(&[f32::NAN, 0.1], &[], 1.2), 1, "NaN never wins");+ }++ #[test]+ fn the_start_and_stop_are_stripped_and_the_prompt_and_silence_added() {+ assert_eq!(+ spoken(&[START_SPEECH_TOKEN, 5, 6, STOP_SPEECH_TOKEN]),+ vec![5, 6]+ );+ assert_eq!(+ spoken(&[START_SPEECH_TOKEN, 5, 6]),+ vec![5, 6],+ "ran out without a stop"+ );+ assert_eq!(+ spoken(&[START_SPEECH_TOKEN, STOP_SPEECH_TOKEN]),+ Vec::<i64>::new()+ );+ assert_eq!(spoken(&[START_SPEECH_TOKEN]), Vec::<i64>::new());+ assert_eq!(spoken(&[]), Vec::<i64>::new());+ assert_eq!(+ with_prompt(&[1, 2], &[5, 6]),+ vec![1, 2, 5, 6, SILENCE_TOKEN, SILENCE_TOKEN, SILENCE_TOKEN]+ );+ assert_eq!(with_prompt(&[], &[]), vec![SILENCE_TOKEN; 3]);+ }++ #[test]+ fn text_is_read_a_few_sentences_at_a_time() {+ assert!(chunks("").is_empty());+ assert!(chunks(" \n ").is_empty());+ assert_eq!(chunks("Hello there."), vec!["Hello there."]);+ assert_eq!(chunks("One. Two! Three?"), vec!["One. Two! Three?"]);+ assert_eq!(+ chunks("Version 2.5 is out. Yes."),+ vec!["Version 2.5 is out. Yes."],+ "a dot inside a number is not an end"+ );+ assert_eq!(+ chunks("First line\nSecond line"),+ vec!["First line Second line"]+ );+ let long = "This sentence is exactly fifty characters long, ok. ".repeat(10);+ let parts = chunks(&long);+ assert!(parts.len() >= 2, "{parts:?}");+ for part in &parts {+ assert!(+ part.chars().count() <= CHUNK_CHARS,+ "{}",+ part.chars().count()+ );+ }+ assert_eq!(+ parts.join(" ").split_whitespace().count(),+ long.split_whitespace().count()+ );+ // One sentence longer than a chunk is still one chunk: it is not cut mid-word.+ let run = "word ".repeat(80);+ assert_eq!(chunks(&run).len(), 1);+ assert!(expected_tokens("Hello there, how are you today?") > 10);+ }++ #[test]+ fn a_wav_is_forty_four_bytes_of_header_and_the_samples() {+ let wav = wav_bytes(&[0.0, 1.0, -1.0, 2.0], 24_000);+ assert_eq!(wav.len(), 44 + 8);+ assert_eq!(&wav[0..4], b"RIFF");+ assert_eq!(&wav[8..12], b"WAVE");+ assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 24_000);+ assert_eq!(u16::from_le_bytes(wav[22..24].try_into().unwrap()), 1);+ assert_eq!(u32::from_le_bytes(wav[40..44].try_into().unwrap()), 8);+ assert_eq!(i16::from_le_bytes(wav[44..46].try_into().unwrap()), 0);+ assert_eq!(i16::from_le_bytes(wav[46..48].try_into().unwrap()), 32767);+ assert_eq!(i16::from_le_bytes(wav[48..50].try_into().unwrap()), -32767);+ assert_eq!(+ i16::from_le_bytes(wav[50..52].try_into().unwrap()),+ 32767,+ "clamped"+ );+ assert_eq!(wav_bytes(&[], 8_000).len(), 44);+ }+}diff --git a/src/crates/concat-speech/src/lib.rs b/src/crates/concat-speech/src/lib.rsindex 80c5d723..ff84a031 100644--- a/src/crates/concat-speech/src/lib.rs+++ b/src/crates/concat-speech/src/lib.rs@@ -17,6 +17,8 @@//! (sherpa-onnx's static libraries) stays out of everything that does not//! speak.+#[cfg(feature = "chatterbox")]+pub mod chatterbox;pub mod transcribe;pub mod tts;diff --git a/src/crates/concat-speech/src/tts.rs b/src/crates/concat-speech/src/tts.rsindex 87746146..a52db37f 100644--- a/src/crates/concat-speech/src/tts.rs+++ b/src/crates/concat-speech/src/tts.rs@@ -1,26 +1,36 @@// SPDX-License-Identifier: AGPL-3.0-or-later// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors-//! Kokoro text-to-speech: text in, a narration WAV in the project folder out.+//! Text-to-speech: text in, a narration WAV in the project folder out.//!//! The same local-first shape as transcription, with one difference:-//! whisper runs as a child process, Kokoro runs in-process through+//! whisper runs as a child process, the voices run in-process through//! sherpa-onnx (the official k2-fsa bindings, statically linked).//! In-process because there is no `kokoro-cli` worth shipping, and because//! sherpa's progress callback gives us cancellation anyway - returning//! `false` from it stops synthesis mid-sentence.//!+//! Three families of model, one front. **Kokoro** is one network with+//! many built-in speakers, addressed by integer id: the English and+//! Chinese ones its lexicons cover are the voices it offers. **Pocket+//! TTS** has no speakers of its own: every voice is a few seconds of+//! someone talking, which it reads in. Its bundle carries two such+//! samples, and the sheet adds a third voice that is the sound of+//! whatever clip is selected - the narrator's own voice, from footage+//! already in the project. **Chatterbox Turbo** reads in a recording the+//! same way, closer to a studio voice, at a gigabyte and a wait; it runs+//! through ONNX Runtime directly ([`crate::chatterbox`]) rather than+//! sherpa, on the desktop only.+//!//! Three pieces://!-//! 1. **Models.** Kokoro ships as a tar.bz2 bundle (the network, the voice-//! bank, espeak-ng data, lexicons), downloaded on demand from the-//! sherpa-onnx releases into `<app data>/tts-models/<id>/`. Streamed to a-//! `.part`, unpacked through a staging folder and renamed - a torn-//! download or unpack must never look usable.-//! 2. **Voices.** Kokoro is one model with many built-in speakers, addressed-//! by integer id. The table below names the ones we offer - the English-//! and Chinese speakers, the languages this model's lexicons actually-//! cover.+//! 1. **Models.** Each ships as a tar.bz2 bundle from the sherpa-onnx+//! releases, downloaded on demand into `<app data>/tts-models/<id>/`.+//! Streamed to a `.part`, unpacked through a staging folder and renamed+//! - a torn download or unpack must never look usable.+//! 2. **Voices.** One table per family, below. A voice id says which+//! family it belongs to, and the sheet shows the voices of the model it+//! has chosen.//! 3. **Synthesis.** The engine loads once and is cached until the model//! changes or is deleted; each request writes a WAV into the project's//! `audio/` folder (not `cache/` - cache is regenerable, narration the@@ -35,13 +45,39 @@ use concat_host::{AppDirs, SingleFlight, projects};use serde::{Deserialize, Serialize};use sherpa_onnx::{GenerationConfig, OfflineTts, OfflineTtsConfig, OfflineTtsKokoroModelConfig,- OfflineTtsModelConfig,+ OfflineTtsModelConfig, OfflineTtsPocketModelConfig,};use crate::DownloadProgress;-/// One downloadable Kokoro bundle. Sizes are approximate, for progress bars-/// when the server declines to send a Content-Length.+/// Which network a bundle is, and so which voices it reads with and how+/// the engine is configured for it.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum Family {+ /// Kokoro v1.0: built-in speakers by id.+ #[default]+ Kokoro,+ /// Kyutai's Pocket TTS: a voice is a reference recording.+ Pocket,+ /// Resemble's Chatterbox Turbo: a voice is a reference recording,+ /// and the engine is ONNX Runtime rather than sherpa.+ Chatterbox,+}++/// The family a model id belongs to, by the bundle's name.+pub fn family_of(id: &str) -> Family {+ if id.starts_with("sherpa-onnx-pocket-tts") {+ Family::Pocket+ } else if id.starts_with("chatterbox") {+ Family::Chatterbox+ } else {+ Family::Kokoro+ }+}++/// One downloadable bundle. Sizes are approximate, for progress bars when+/// the server declines to send a Content-Length.struct KnownModel {id: &'static str,label: &'static str,@@ -56,11 +92,28 @@ struct KnownModel {/// The models the settings panel offers, smallest first.///-/// Both are Kokoro v1.0 multi-language (English + Chinese) from the official-/// sherpa-onnx conversions; they differ only in quantisation. The int8 build-/// is the default recommendation - a third of the download for a difference-/// most ears never find.+/// The Kokoro pair are v1.0 multi-language (English + Chinese) from the+/// official sherpa-onnx conversions; they differ only in quantisation. The+/// int8 build is the default recommendation - a third of the download for+/// a difference most ears never find. Pocket TTS is the sherpa-onnx int8+/// conversion of Kyutai's 100M model: English, and it reads in any voice+/// it is given a few seconds of.const KNOWN_MODELS: &[KnownModel] = &[+ #[cfg(feature = "chatterbox")]+ KnownModel {+ id: crate::chatterbox::BUNDLE_ID,+ label: "Chatterbox Turbo (studio)",+ blurb: "The closest to a studio voice; reads in the selected clip's voice. English, slow, a gigabyte.",+ approx_bytes: crate::chatterbox::BUNDLE_BYTES,+ sha256: "",+ },+ KnownModel {+ id: "sherpa-onnx-pocket-tts-int8-2026-01-26",+ label: "Pocket TTS (cloning)",+ blurb: "Reads in any voice, including one from a clip on the timeline. English.",+ approx_bytes: 98_336_520,+ sha256: "2f3b88823cbbb9bf0b2477ec8ae7b3fec417b3a87b6bb5f256dba66f2ad967cb",+ },KnownModel {id: "kokoro-int8-multi-lang-v1_0",label: "Kokoro (compact)",@@ -123,6 +176,69 @@ const VOICES: &[(i32, &str)] = &[(52, "zm_yunyang"),];+/// The voices Pocket TTS offers, by our own id, out of Kokoro's range.+///+/// Two are recordings the bundle carries, named here by the file beside+/// the network; the third is the clone: no file of its own, since the+/// recording is the clip the sheet was given, decoded at request time.+pub const POCKET_VOICES: &[(i32, &str, Option<&str>)] = &[+ (1000, "pocket_bria", Some("test_wavs/bria.wav")),+ (1001, "pocket_loona", Some("test_wavs/loona.wav")),+ (POCKET_CLONE, "pocket_clone", None),+];++/// The voice that is the selected clip's own.+pub const POCKET_CLONE: i32 = 1099;++/// Chatterbox's voices: only the selected clip's own, since the model has+/// no speakers of its own and ships no recording of anyone's.+pub const CHATTERBOX_VOICES: &[(i32, &str)] = &[(CHATTERBOX_CLONE, "chatterbox_clone")];++/// The selected clip's own voice, read by Chatterbox.+pub const CHATTERBOX_CLONE: i32 = 2099;++/// Whether a voice is the selected clip's own, in any family.+pub fn is_clone(voice: i32) -> bool {+ voice == POCKET_CLONE || voice == CHATTERBOX_CLONE+}++/// Pocket TTS reads the voice from this many seconds of a recording at+/// most; more costs time and adds nothing.+pub const REFERENCE_SECONDS: f64 = 10.0;++/// Which family a voice id belongs to.+pub fn voice_family(voice: i32) -> Option<Family> {+ if VOICES.iter().any(|(id, _)| *id == voice) {+ Some(Family::Kokoro)+ } else if POCKET_VOICES.iter().any(|(id, _, _)| *id == voice) {+ Some(Family::Pocket)+ } else if CHATTERBOX_VOICES.iter().any(|(id, _)| *id == voice) {+ Some(Family::Chatterbox)+ } else {+ None+ }+}++/// The upstream name of a voice, in either family.+fn voice_name(voice: i32) -> Option<&'static str> {+ VOICES+ .iter()+ .find(|(id, _)| *id == voice)+ .map(|(_, name)| *name)+ .or_else(|| {+ POCKET_VOICES+ .iter()+ .find(|(id, _, _)| *id == voice)+ .map(|(_, name, _)| *name)+ })+ .or_else(|| {+ CHATTERBOX_VOICES+ .iter()+ .find(|(id, _)| *id == voice)+ .map(|(_, name)| *name)+ })+}+fn known(id: &str) -> Option<&'static KnownModel> {KNOWN_MODELS.iter().find(|model| model.id == id)}@@ -163,8 +279,17 @@ fn onnx_file(dir: &Path) -> Option<PathBuf> {/// A bundle counts as downloaded once its network is in place. The rename at/// the end of unpacking makes this atomic: no folder, or a complete one.+/// Chatterbox arrives as files rather than an archive, and counts once+/// every one of them is there.fn model_downloaded(dirs: &AppDirs, id: &str) -> bool {- model_dir(dirs, id).is_ok_and(|dir| onnx_file(&dir).is_some())+ let Ok(dir) = model_dir(dirs, id) else {+ return false;+ };+ match family_of(id) {+ #[cfg(feature = "chatterbox")]+ Family::Chatterbox => crate::chatterbox::installed(&dir),+ _ => onnx_file(&dir).is_some(),+ }}/// One model, as the settings panel shows it.@@ -173,6 +298,8 @@ fn model_downloaded(dirs: &AppDirs, id: &str) -> bool {pub struct ModelStatus {/// The bundle id.pub id: String,+ /// Which family, and so which voices it reads with.+ pub family: Family,/// Display name.pub label: String,/// One line on what this size trades away.@@ -187,11 +314,26 @@ pub struct ModelStatus {#[derive(Serialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub struct VoiceInfo {- /// Kokoro speaker id, what synthesis wants back.+ /// The voice id, what synthesis wants back: Kokoro's speaker id, or+ /// one of [`POCKET_VOICES`].pub id: i32,/// The upstream voice name, e.g. "af_heart"; the caller decodes the- /// accent/gender prefix and title-cases the rest.+ /// accent/gender prefix and title-cases the rest. Pocket voices are+ /// `pocket_<name>`.pub name: String,+ /// The family whose models read with this voice.+ pub family: Family,+}++/// A recording to read in the voice of: the clip the sheet was given.+#[derive(Deserialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Reference {+ /// The media file.+ pub path: String,+ /// Seconds into the file the voice is heard from.+ #[serde(default)]+ pub start: f64,}/// What the settings panel and the speech dialog show.@@ -212,8 +354,12 @@ pub struct TtsStatus {pub struct SpeakRequest {/// Which model to use, e.g. "kokoro-int8-multi-lang-v1_0".pub model_id: String,- /// Kokoro speaker id, from the voices table.+ /// The voice, from the voices table; it must belong to the model's+ /// family.pub voice: i32,+ /// For [`POCKET_CLONE`]: the recording to read in the voice of.+ #[serde(default)]+ pub reference: Option<Reference>,/// What to say.pub text: String,/// Speaking rate; 1.0 is the voice's natural pace.@@ -232,9 +378,17 @@ pub struct SpeakResult {pub duration: f64,}+/// A loaded model: sherpa's engine for the families it runs, or+/// Chatterbox's own.+enum Engine {+ Sherpa(OfflineTts),+ #[cfg(feature = "chatterbox")]+ Chatterbox(Box<crate::chatterbox::Engine>),+}+struct CachedEngine {model_id: String,- tts: OfflineTts,+ tts: Engine,}/// The one synthesis and the one download that can run at a time, plus the@@ -276,6 +430,7 @@ impl Speech {.iter().map(|model| ModelStatus {id: model.id.to_owned(),+ family: family_of(model.id),label: model.label.to_owned(),blurb: model.blurb.to_owned(),size_bytes: model.approx_bytes,@@ -287,7 +442,18 @@ impl Speech {.map(|(id, name)| VoiceInfo {id: *id,name: (*name).to_owned(),+ family: Family::Kokoro,})+ .chain(POCKET_VOICES.iter().map(|(id, name, _)| VoiceInfo {+ id: *id,+ name: (*name).to_owned(),+ family: Family::Pocket,+ }))+ .chain(CHATTERBOX_VOICES.iter().map(|(id, name)| VoiceInfo {+ id: *id,+ name: (*name).to_owned(),+ family: Family::Chatterbox,+ })).collect(),})}@@ -307,6 +473,10 @@ impl Speech {let job = self.downloads.begin("voice model download")?;let cancel = job.cancel_flag();let destination = model_dir(dirs, id)?;+ #[cfg(feature = "chatterbox")]+ if family_of(id) == Family::Chatterbox {+ return crate::chatterbox::download(&destination, cancel, &mut progress);+ }if onnx_file(&destination).is_some() {return Ok(());}@@ -421,8 +591,16 @@ impl Speech {if text.is_empty() {return Err("nothing to say: the text is empty".to_owned());}- if !VOICES.iter().any(|(id, _)| *id == request.voice) {- return Err(format!("unknown voice {}", request.voice));+ let family = family_of(&request.model_id);+ match voice_family(request.voice) {+ Some(owner) if owner == family => {}+ Some(_) => {+ return Err(format!(+ "voice {} does not belong to {}",+ request.voice, request.model_id+ ));+ }+ None => return Err(format!("unknown voice {}", request.voice)),}let speed = if request.speed.is_finite() {request.speed.clamp(0.5, 2.0)@@ -431,7 +609,7 @@ impl Speech {};let dir = model_dir(dirs, &request.model_id)?;- if onnx_file(&dir).is_none() {+ if !model_downloaded(dirs, &request.model_id) {return Err(format!("model {} is not downloaded - see Settings > Speech",request.model_id@@ -456,7 +634,18 @@ impl Speech {if engine.as_ref().map(|cached| cached.model_id.as_str()) != Some(request.model_id.as_str()){// Load before overwriting: a failed load keeps the old engine.- let tts = load_engine(&dir)?;+ let tts = match family {+ Family::Kokoro => Engine::Sherpa(load_kokoro(&dir)?),+ Family::Pocket => Engine::Sherpa(load_pocket(&dir)?),+ #[cfg(feature = "chatterbox")]+ Family::Chatterbox => {+ Engine::Chatterbox(Box::new(crate::chatterbox::Engine::load(&dir)?))+ }+ #[cfg(not(feature = "chatterbox"))]+ Family::Chatterbox => {+ return Err("Chatterbox is not part of this build".to_owned());+ }+ };*engine = Some(CachedEngine {model_id: request.model_id.clone(),tts,@@ -464,17 +653,75 @@ impl Speech {}let tts = &engine.as_ref().expect("engine cached above").tts;+ // Wall-clock millis plus process id: unique enough for files created+ // by one human clicking a button, and stable for the media bin name.+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|elapsed| elapsed.as_millis())+ .unwrap_or(0);+ let voice_name = voice_name(request.voice).unwrap_or("voice");+ let file = out_dir.join(format!("speech-{voice_name}-{stamp}.wav"));++ // Chatterbox is its own loop: the recording in, the samples out,+ // and the file written here. Sherpa's families go on below.+ #[cfg(feature = "chatterbox")]+ let tts = match tts {+ Engine::Chatterbox(chatterbox) => {+ let samples = reference_samples(&dir, request)?;+ let mut progress = progress;+ let spoken = chatterbox.speak(text, &samples, &cancel, &mut |fraction| {+ progress(fraction);+ })?;+ if spoken.is_empty() {+ return Err("the engine produced no audio for this text".to_owned());+ }+ let rate = crate::chatterbox::SAMPLE_RATE;+ std::fs::write(&file, crate::chatterbox::wav_bytes(&spoken, rate))+ .map_err(|error| format!("could not write {}: {error}", file.display()))?;+ return Ok(SpeakResult {+ path: file.to_string_lossy().into_owned(),+ duration: spoken.len() as f64 / f64::from(rate),+ });+ }+ Engine::Sherpa(tts) => tts,+ };+ #[cfg(not(feature = "chatterbox"))]+ let Engine::Sherpa(tts) = tts;++ // Kokoro picks its speaker by id; Pocket reads the voice out of a+ // recording, decoded here to what the model listens at.+ let generation = match family {+ Family::Kokoro => GenerationConfig {+ sid: request.voice,+ speed,+ ..Default::default()+ },+ _ => {+ let samples = reference_samples(&dir, request)?;+ GenerationConfig {+ speed,+ reference_audio: Some(samples),+ reference_sample_rate: REFERENCE_RATE as i32,+ extra: Some(+ [(+ "max_reference_audio_len".to_owned(),+ serde_json::json!(REFERENCE_SECONDS),+ )]+ .into_iter()+ .collect(),+ ),+ ..Default::default()+ }+ }+ };+let progress_cancel = Arc::clone(&cancel);let mut progress = progress;let mut last_fraction = -1.0f32;let audio = tts.generate_with_config(text,- &GenerationConfig {- sid: request.voice,- speed,- ..Default::default()- },+ &generation,Some(move |_samples: &[f32], fraction: f32| -> bool {if progress_cancel.load(Ordering::Relaxed) {return false;@@ -499,19 +746,6 @@ impl Speech {return Err("the engine produced no audio for this text".to_owned());}- // Wall-clock millis plus process id: unique enough for files created- // by one human clicking a button, and stable for the media bin name.- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|elapsed| elapsed.as_millis())- .unwrap_or(0);- let voice_name = VOICES- .iter()- .find(|(id, _)| *id == request.voice)- .map(|(_, name)| *name)- .unwrap_or("voice");- let file = out_dir.join(format!("speech-{voice_name}-{stamp}.wav"));-if !audio.save(&file.to_string_lossy()) {return Err(format!("could not write {}", file.display()));}@@ -534,11 +768,128 @@ impl Speech {}}-/// Builds the engine for one model folder.+/// What Pocket TTS listens to a voice at: the rate of its own codec, and+/// the rate its bundled recordings are in.+const REFERENCE_RATE: u32 = 24_000;++/// The recording a Pocket request reads the voice from, as mono samples+/// at [`REFERENCE_RATE`]: one of the bundle's own for a named voice, or+/// the request's reference for the clone, cut to [`REFERENCE_SECONDS`]+/// from where the voice is heard.+fn reference_samples(dir: &Path, request: &SpeakRequest) -> Result<Vec<f32>, String> {+ let (path, start) = if is_clone(request.voice) {+ let reference = request.reference.as_ref().ok_or_else(|| {+ "no clip to take the voice from - select a clip with a voice in it".to_owned()+ })?;+ (+ PathBuf::from(&reference.path),+ if reference.start.is_finite() {+ reference.start.max(0.0)+ } else {+ 0.0+ },+ )+ } else {+ let file = POCKET_VOICES+ .iter()+ .find(|(id, _, _)| *id == request.voice)+ .and_then(|(_, _, file)| *file)+ .ok_or_else(|| format!("voice {} has no recording", request.voice))?;+ (dir.join(file), 0.0)+ };+ let options = concat_media::AudioOptions {+ start: (start > 0.0).then_some(start),+ duration: Some(REFERENCE_SECONDS),+ rate: REFERENCE_RATE,+ channels: 1,+ format: concat_media::SampleFormat::F32,+ ..Default::default()+ };+ let mut decoder = concat_media::AudioDecoder::open(&path, &options)+ .map_err(|error| format!("could not read the voice from {}: {error}", path.display()))?;+ let samples = decoder+ .collect_f32()+ .map_err(|error| format!("could not read the voice from {}: {error}", path.display()))?;+ // Half a second is the least a voice can be told from; under that the+ // model reads in nobody's.+ if samples.len() < REFERENCE_RATE as usize / 2 {+ return Err(format!(+ "too little sound in {} to take a voice from",+ path.display()+ ));+ }+ Ok(samples)+}++/// The file in `dir` whose name starts with `prefix` and ends `.onnx`:+/// `lm_main.onnx` in a full bundle, `lm_main.int8.onnx` in a quantised one.+fn onnx_starting(dir: &Path, prefix: &str) -> Option<String> {+ let mut found: Vec<PathBuf> = std::fs::read_dir(dir)+ .ok()?+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| {+ path.extension().is_some_and(|ext| ext == "onnx")+ && path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with(prefix))+ })+ .collect();+ found.sort();+ found+ .first()+ .map(|path| path.to_string_lossy().into_owned())+}++/// Builds the engine for a Pocket TTS bundle: the five networks and the+/// two tables the sherpa-onnx example names.+fn load_pocket(dir: &Path) -> Result<OfflineTts, String> {+ let part = |prefix: &str| {+ onnx_starting(dir, prefix)+ .ok_or_else(|| format!("the model folder has no {prefix} network - re-download it"))+ };+ let table = |name: &str| {+ let path = dir.join(name);+ path.is_file()+ .then(|| path.to_string_lossy().into_owned())+ .ok_or_else(|| format!("the model folder has no {name} - re-download it"))+ };+ let config = OfflineTtsConfig {+ model: OfflineTtsModelConfig {+ pocket: OfflineTtsPocketModelConfig {+ lm_flow: Some(part("lm_flow")?),+ lm_main: Some(part("lm_main")?),+ encoder: Some(part("encoder")?),+ decoder: Some(part("decoder")?),+ text_conditioner: Some(part("text_conditioner")?),+ vocab_json: Some(table("vocab.json")?),+ token_scores_json: Some(table("token_scores.json")?),+ // The voices offered plus a few clones, before the oldest+ // embedding is worked out again.+ voice_embedding_cache_capacity: 8,+ },+ num_threads: threads(),+ ..Default::default()+ },+ ..Default::default()+ };+ OfflineTts::create(&config)+ .ok_or_else(|| "the speech engine failed to load - try re-downloading the model".to_owned())+}++/// The threads the engine may use: every core up to eight.+fn threads() -> i32 {+ std::thread::available_parallelism()+ .map(|count| count.get().min(8))+ .unwrap_or(4) as i32+}++/// Builds the engine for a Kokoro bundle.////// The lexicon list mirrors the official sherpa-onnx invocation for this/// bundle: US English and Chinese, joined by commas, each only if present.-fn load_engine(dir: &Path) -> Result<OfflineTts, String> {+fn load_kokoro(dir: &Path) -> Result<OfflineTts, String> {let network = onnx_file(dir).ok_or_else(|| "the model folder has no .onnx network - re-download it".to_owned())?;let existing = |name: &str| {@@ -550,10 +901,6 @@ fn load_engine(dir: &Path) -> Result<OfflineTts, String> {.filter_map(|name| existing(name)).collect();- let threads = std::thread::available_parallelism()- .map(|count| count.get().min(8))- .unwrap_or(4) as i32;-let config = OfflineTtsConfig {model: OfflineTtsModelConfig {kokoro: OfflineTtsKokoroModelConfig {@@ -571,7 +918,7 @@ fn load_engine(dir: &Path) -> Result<OfflineTts, String> {lexicon: (!lexicon.is_empty()).then(|| lexicon.join(",")),..Default::default()},- num_threads: threads,+ num_threads: threads(),..Default::default()},..Default::default()@@ -585,6 +932,109 @@ fn load_engine(dir: &Path) -> Result<OfflineTts, String> {mod tests {use super::*;+ #[test]+ fn a_voice_belongs_to_one_family_and_a_model_says_which_it_reads_with() {+ assert_eq!(family_of("kokoro-int8-multi-lang-v1_0"), Family::Kokoro);+ assert_eq!(family_of("kokoro-multi-lang-v1_0"), Family::Kokoro);+ assert_eq!(+ family_of("sherpa-onnx-pocket-tts-int8-2026-01-26"),+ Family::Pocket+ );+ assert_eq!(voice_family(3), Some(Family::Kokoro));+ assert_eq!(voice_family(52), Some(Family::Kokoro));+ assert_eq!(voice_family(1000), Some(Family::Pocket));+ assert_eq!(voice_family(POCKET_CLONE), Some(Family::Pocket));+ assert_eq!(voice_family(CHATTERBOX_CLONE), Some(Family::Chatterbox));+ assert_eq!(family_of("chatterbox-turbo-q8"), Family::Chatterbox);+ assert!(is_clone(POCKET_CLONE) && is_clone(CHATTERBOX_CLONE) && !is_clone(3));+ assert_eq!(voice_family(53), None);+ assert_eq!(voice_family(-1), None);+ // No id serves two families, and every voice has a name.+ for (id, _) in VOICES {+ assert!(!POCKET_VOICES.iter().any(|(other, _, _)| other == id));+ assert!(voice_name(*id).is_some());+ }+ for (id, name, _) in POCKET_VOICES {+ assert_eq!(voice_name(*id), Some(*name));+ assert!(!CHATTERBOX_VOICES.iter().any(|(other, _)| other == id));+ }+ for (id, name) in CHATTERBOX_VOICES {+ assert_eq!(voice_name(*id), Some(*name));+ }+ assert_eq!(voice_name(999), None);+ for model in KNOWN_MODELS {+ assert!(known(model.id).is_some());+ }+ }++ #[test]+ fn the_clone_voice_needs_a_recording_and_a_named_voice_has_one() {+ let dir = std::env::temp_dir().join(format!("concat-pocket-{}", std::process::id()));+ std::fs::create_dir_all(&dir).expect("mkdir");+ let request = |voice: i32, reference: Option<Reference>| SpeakRequest {+ model_id: "sherpa-onnx-pocket-tts-int8-2026-01-26".to_owned(),+ voice,+ reference,+ text: "hello".to_owned(),+ speed: 1.0,+ project: String::new(),+ };+ let error = reference_samples(&dir, &request(POCKET_CLONE, None)).expect_err("no clip");+ assert!(error.contains("select a clip"), "{error}");+ // A recording that is not there names itself.+ let error = reference_samples(&dir, &request(1000, None)).expect_err("no file");+ assert!(error.contains("bria.wav"), "{error}");+ let error = reference_samples(+ &dir,+ &request(+ POCKET_CLONE,+ Some(Reference {+ path: dir.join("nobody.mp4").to_string_lossy().into_owned(),+ start: f64::NAN,+ }),+ ),+ )+ .expect_err("no file");+ assert!(error.contains("nobody.mp4"), "{error}");+ // A voice with no recording in the table is refused, not read.+ let error = reference_samples(&dir, &request(1098, None)).expect_err("no such voice");+ assert!(error.contains("1098"), "{error}");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_bundles_networks_are_found_by_their_prefix_whatever_the_quantisation() {+ let dir = std::env::temp_dir().join(format!("concat-pocket-files-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).expect("mkdir");+ for name in [+ "lm_main.int8.onnx",+ "lm_flow.onnx",+ "decoder.int8.onnx",+ "text_conditioner.onnx",+ "vocab.json",+ ] {+ std::fs::write(dir.join(name), b"x").expect("write");+ }+ let found = |prefix: &str| onnx_starting(&dir, prefix).unwrap_or_default();+ assert!(found("lm_main").ends_with("lm_main.int8.onnx"));+ assert!(found("lm_flow").ends_with("lm_flow.onnx"));+ assert!(found("decoder").ends_with("decoder.int8.onnx"));+ assert!(found("text_conditioner").ends_with("text_conditioner.onnx"));+ assert_eq!(+ onnx_starting(&dir, "encoder"),+ None,+ "decoder is not encoder"+ );+ assert_eq!(+ onnx_starting(&dir, "vocab"),+ None,+ "a table is not a network"+ );+ assert_eq!(onnx_starting(&dir.join("nowhere"), "lm_main"), None);+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn every_known_model_is_asked_of_the_mirror_before_upstream() {for model in KNOWN_MODELS {diff --git a/src/crates/concat/Cargo.toml b/src/crates/concat/Cargo.tomlindex ab1b3e56..3f1cb648 100644--- a/src/crates/concat/Cargo.toml+++ b/src/crates/concat/Cargo.toml@@ -96,7 +96,7 @@ concat-media.workspace = trueconcat-project.workspace = trueconcat-export.workspace = trueconcat-host = { workspace = true, features = ["gpu"] }-concat-speech.workspace = true+concat-speech = { workspace = true, features = ["chatterbox"] }# The Settings sheet's Remote page: the Concat API on a socket while the# window is open. JSON-RPC only; the gRPC feature stays with concat-cli.concat-server.workspace = truediff --git a/src/crates/concat/src/panes/speech.rs b/src/crates/concat/src/panes/speech.rsindex 1c650ee3..7e346d20 100644--- a/src/crates/concat/src/panes/speech.rs+++ b/src/crates/concat/src/panes/speech.rs@@ -14,7 +14,7 @@ use std::sync::Arc;use concat_host::media::{self, MediaSummary};use concat_project::Command;use concat_project::model::ClipKind;-use concat_speech::tts::VoiceInfo;+use concat_speech::tts::{CHATTERBOX_CLONE, Family, Reference, VoiceInfo, family_of, is_clone};use slint::SharedString;use crate::host::{on_ui, spawn};@@ -27,6 +27,8 @@ use crate::ui::SpeechSheetData;/// The default Kokoro speaker: `af_heart`.const DEFAULT_VOICE: i32 = 3;+/// The default Pocket voice: Bria, the bundle's first recording.+const DEFAULT_POCKET_VOICE: i32 = 1000;/// The paces the speech sheet offers, as the voice's rate multiplier.const PACES: [f32; 3] = [0.85, 1.0, 1.15];@@ -58,10 +60,12 @@ pub struct SpeechPane {/// reads a script of its own at the playhead.pub clip: Option<String>,pub text: String,- /// Row in `speakers`.+ /// Row in the chosen model's voices; see [`SpeechPane::offered`].pub voice: usize,/// Row in the installed voice model list.pub model: usize,+ /// The family of the chosen model, which is which voices are offered.+ pub family: Family,/// 0 slower, 1 natural, 2 faster.pub pace: usize,pub running: bool,@@ -86,29 +90,41 @@ impl SpeechPane {.cloned();let installed = installed(&studio.settings.voices);let model = installed.iter().position(|model| model.active).unwrap_or(0);- let wanted = studio.prefs.tts_voice.unwrap_or(DEFAULT_VOICE);- let voice = self- .speakers- .iter()- .position(|speaker| speaker.id == wanted)- .unwrap_or(0);+ let family = installed+ .get(model)+ .map(|model| family_of(&model.id))+ .unwrap_or(Family::Kokoro);*self = SpeechPane {open: true,clip: title.as_ref().map(|clip| clip.id.clone()),text: title.and_then(|clip| clip.text.map(|text| text.content)).unwrap_or_default(),- voice,+ voice: 0,model,+ family,pace: 1,speakers: std::mem::take(&mut self.speakers),..SpeechPane::default()};+ // The voice chosen last time, if the model reads with it.+ let wanted = studio.prefs.tts_voice;+ self.voice = self.voice_row(wanted);}SpeechMsg::Close => self.open = false,SpeechMsg::TextEdited(text) => self.text = text,SpeechMsg::VoiceChanged(index) => self.voice = index.max(0) as usize,- SpeechMsg::ModelChanged(index) => self.model = index.max(0) as usize,+ SpeechMsg::ModelChanged(index) => {+ self.model = index.max(0) as usize;+ // Another model may read with other voices: the list is+ // rebuilt, and the row points at a voice on it.+ let chosen = self.offered().get(self.voice).map(|voice| voice.id);+ self.family = installed(&studio.settings.voices)+ .get(self.model)+ .map(|model| family_of(&model.id))+ .unwrap_or(Family::Kokoro);+ self.voice = self.voice_row(chosen);+ }SpeechMsg::PaceChanged(index) => self.pace = (index.max(0) as usize).min(2),SpeechMsg::Begin => self.run(studio),SpeechMsg::Cancel => {@@ -164,10 +180,35 @@ impl SpeechPane {self.message = t("Download a voice model in Settings › Speech first");return;};- let Some(voice) = self.speakers.get(self.voice).map(|speaker| speaker.id) else {+ let Some(voice) = self.offered().get(self.voice).map(|speaker| speaker.id) else {self.message = t("No voice to read with");return;};+ // The clone reads in the voice of the selected clip: its file,+ // from where the clip starts in it.+ let reference = if is_clone(voice) {+ let recording = studio+ .sole_selection()+ .and_then(|id| studio.clip(&id))+ .filter(|clip| clip.kind == ClipKind::Video || clip.kind == ClipKind::Audio)+ .and_then(|clip| {+ studio+ .project()+ .media_by_id(&clip.media_id)+ .filter(|media| media.has_audio)+ .map(|media| Reference {+ path: media.path.clone(),+ start: clip.source_start,+ })+ });+ let Some(recording) = recording else {+ self.message = t("Select a clip with a voice in it to clone");+ return;+ };+ Some(recording)+ } else {+ None+ };let Some(project) = studio.session.as_ref()@@ -187,6 +228,7 @@ impl SpeechPane {let request = concat_speech::tts::SpeakRequest {model_id: model,voice,+ reference,text,speed: PACES[self.pace.min(2)],project,@@ -221,7 +263,7 @@ impl SpeechPane {let seconds = chars as f32 / CHARS_PER_SECOND / PACES[self.pace.min(2)];let whole = seconds.round() as i32;let voice = self- .speakers+ .offered().get(self.voice).map(|speaker| voice_label(&speaker.name).0).unwrap_or_default();@@ -231,17 +273,41 @@ impl SpeechPane {)}- /// The voice list's rows: each speaker's name.- pub fn speaker_rows(&self) -> Vec<SharedString> {+ /// The voices the chosen model reads with, in table order.+ pub fn offered(&self) -> Vec<&VoiceInfo> {self.speakers+ .iter()+ .filter(|speaker| speaker.family == self.family)+ .collect()+ }++ /// The row of `wanted` among the offered voices, or of the family's+ /// default, or the first.+ fn voice_row(&self, wanted: Option<i32>) -> usize {+ let offered = self.offered();+ let default = match self.family {+ Family::Kokoro => DEFAULT_VOICE,+ Family::Pocket => DEFAULT_POCKET_VOICE,+ Family::Chatterbox => CHATTERBOX_CLONE,+ };+ wanted+ .and_then(|id| offered.iter().position(|voice| voice.id == id))+ .or_else(|| offered.iter().position(|voice| voice.id == default))+ .unwrap_or(0)+ }++ /// The voice list's rows: each offered voice's name.+ pub fn speaker_rows(&self) -> Vec<SharedString> {+ self.offered().iter().map(|speaker| voice_label(&speaker.name).0.into()).collect()}- /// The voice list's second lines: each speaker's accent and gender.+ /// The voice list's second lines: each voice's accent and gender, or+ /// where a Pocket voice comes from.pub fn speaker_detail_rows(&self) -> Vec<SharedString> {- self.speakers+ self.offered().iter().map(|speaker| voice_label(&speaker.name).1.into()).collect()@@ -271,8 +337,22 @@ impl SpeechPane {}/// "af_heart" as a person would say it: the name, and the accent and-/// gender its prefix encodes.+/// gender its prefix encodes. A Pocket voice says where it comes from.fn voice_label(name: &str) -> (String, String) {+ if name == "pocket_clone" || name == "chatterbox_clone" {+ return (+ t("The selected clip's voice"),+ t("Reads in the voice heard in the clip selected on the timeline"),+ );+ }+ if let Some(rest) = name.strip_prefix("pocket_") {+ let mut chars = rest.chars();+ let title = match chars.next() {+ Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),+ None => String::new(),+ };+ return (title, t("A recording that comes with Pocket TTS"));+ }let (prefix, rest) = name.split_once('_').unwrap_or(("", name));let mut chars = rest.chars();let title = match chars.next() {@@ -315,5 +395,9 @@ mod tests {assert!(detail.contains("American"));assert!(detail.contains("female"));assert_eq!(voice_label("nova").0, "Nova");+ assert_eq!(voice_label("pocket_bria").0, "Bria");+ assert!(voice_label("pocket_bria").1.contains("Pocket"));+ assert!(voice_label("pocket_clone").0.contains("clip"));+ assert!(voice_label("chatterbox_clone").0.contains("clip"));}}