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: local text to speech with Kokoro voices
Jareer3b2224d5852f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3aaa8ae3..a7f31dcf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,11 @@ behaviour.## Unreleased+- Text to speech: File → Text to speech turns typed narration into an audio+ clip at the playhead, spoken by one of 36 Kokoro voices (American and+ British English, Chinese) at a chosen pace. Generation runs entirely on+ this machine; the voice model downloads once (about 130 MB) from the sheet+ itself or Settings → Speech.- The entire interface is translatable: the app follows the system languagewhen a translation exists, with an override in Settings → General.Translations are plain JSON files contributors can add — see TRANSLATING.md.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex ef4cd2a0..a552fffd 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -26,6 +26,21 @@ Auto-captions can download ggml Whisper models fromhttps://huggingface.co/ggerganov/whisper.cpp (MIT). Models are fetched ondemand and never bundled.+## sherpa-onnx and Kokoro voices++Text to speech links the sherpa-onnx runtime statically+(https://github.com/k2-fsa/sherpa-onnx, Apache-2.0), which itself statically+links onnxruntime (MIT), piper-phonemize (MIT) and espeak-ng+(**GPL-3.0-or-later**, https://github.com/espeak-ng/espeak-ng) for+grapheme-to-phoneme conversion. Because espeak-ng is compiled into the app+binary, distributed builds must comply with the GPL-3.0 for that combined+work; MPL-2.0 sources remain MPL-2.0.++Kokoro voice model bundles (Apache-2.0,+https://huggingface.co/hexgrad/Kokoro-82M) are downloaded on demand from the+sherpa-onnx releases - including espeak-ng's data files - and are never+bundled with the app.+## Effect preview photographThe effect catalogue thumbnails are rendered from a photograph bydiff --git a/desktop/README.md b/desktop/README.mdindex 177c89e0..7383315f 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -43,7 +43,8 @@ src/EffectsPanel.tsx the clip's video effect chain and incoming transitionTextPanel.tsx title styling and custom fontsExportDialog.tsx render settings, progress, title rasterisation- SettingsDialog.tsx transcriber setup+ TtsDialog.tsx text to speech: narration in, a clip at the playhead out+ SettingsDialog.tsx transcriber and speech model setupSaveTemplateDialog.tsx names and saves the open project as a templateTemplateThumb.tsx a template's poster, shared by gallery and libraryConfirmDialog.tsx the are-you-sure sheet for destructive actions@@ -70,6 +71,7 @@ src-tauri/src/projects.rs project folders on disk and the recents listsrc/templates.rs template bundles: save, list, instantiate, deletesrc/transcribe.rs whisper-cli discovery, models, transcription+ src/tts.rs Kokoro text to speech: model downloads, synthesis```## Rules that keep this fastdiff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lockindex 2cba7c31..251f50a7 100644--- a/desktop/src-tauri/Cargo.lock+++ b/desktop/src-tauri/Cargo.lock@@ -415,6 +415,35 @@ dependencies = ["serde",]+[[package]]+name = "bzip2"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"+dependencies = [+ "bzip2-sys",+ "libc",+]++[[package]]+name = "bzip2"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"+dependencies = [+ "libbz2-rs-sys",+]++[[package]]+name = "bzip2-sys"+version = "0.1.13+1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"+dependencies = [+ "cc",+ "pkg-config",+]+[[package]]name = "cairo-rs"version = "0.18.5"@@ -1143,6 +1172,16 @@ dependencies = ["rustc_version",]+[[package]]+name = "filetime"+version = "0.2.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"+dependencies = [+ "cfg-if",+ "libc",+]+[[package]]name = "find-msvc-tools"version = "0.1.11"@@ -2200,6 +2239,12 @@ dependencies = ["once_cell",]+[[package]]+name = "libbz2-rs-sys"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"+[[package]]name = "libc"version = "0.2.189"@@ -3633,6 +3678,28 @@ dependencies = ["digest",]+[[package]]+name = "sherpa-onnx"+version = "1.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93440301c4240bd5d83496ab9adeee889be48d9428f9c01c37e5ae4ef33ba9e2"+dependencies = [+ "serde",+ "serde_json",+ "sherpa-onnx-sys",+]++[[package]]+name = "sherpa-onnx-sys"+version = "1.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d627abc4624c845e628ad87cca4ff9ac265fc643021d155f2721ac589eeb324"+dependencies = [+ "bzip2 0.4.4",+ "tar",+ "ureq",+]+[[package]]name = "shlex"version = "2.0.1"@@ -3924,6 +3991,17 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "tar"+version = "0.4.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"+dependencies = [+ "filetime",+ "libc",+ "xattr",+]+[[package]]name = "target-lexicon"version = "0.12.16"@@ -5771,10 +5849,13 @@ version = "0.2.0"name = "wolfcut-desktop"version = "0.2.0"dependencies = [+ "bzip2 0.6.1","cpal","memmap2","serde","serde_json",+ "sherpa-onnx",+ "tar","tauri","tauri-build","tauri-plugin-dialog",@@ -5898,6 +5979,16 @@ dependencies = ["pkg-config",]+[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]+[[package]]name = "xml-rs"version = "0.8.29"diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 6e5f90af..ab5cb025 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -40,6 +40,13 @@ memmap2 = "0.9"# worth of dependencies for one GET.ureq = "2"+# Text to speech: the official k2-fsa bindings, linked statically so the+# bundle carries no extra dylibs. Kokoro models arrive as tar.bz2 archives,+# hence tar + bzip2 (pure-Rust decoder) for unpacking them.+sherpa-onnx = "1.13"+tar = "0.4"+bzip2 = "0.6"+# TypeScript bindings for the host's own wire types (EditorView and friends),# generated by `cargo test --features types export_bindings` with# TS_RS_EXPORT_DIR pointed at desktop/src/lib/generated - see the READMEdiff --git a/desktop/src-tauri/src/jobs.rs b/desktop/src-tauri/src/jobs.rsindex fae74638..28cc5013 100644--- a/desktop/src-tauri/src/jobs.rs+++ b/desktop/src-tauri/src/jobs.rs@@ -57,6 +57,12 @@ impl Job {pub fn cancel_flag(&self) -> &AtomicBool {&self.cancel}++ /// An owned handle on the same flag, for callbacks that outlive borrows+ /// of the job (an FFI progress callback must be `'static`).+ pub fn cancel_handle(&self) -> Arc<AtomicBool> {+ Arc::clone(&self.cancel)+ }}impl Drop for Job {diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex e0d4f0cf..72031b00 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -14,6 +14,7 @@ mod playback;mod projects;mod templates;mod transcribe;+mod tts;use serde::Serialize;@@ -866,6 +867,10 @@ pub fn run() {jobs::SingleFlight::new(),)));app.manage(transcribe::TranscribeState::new());+ app.manage(tts::TtsDownloadState(std::sync::Arc::new(+ jobs::SingleFlight::new(),+ )));+ app.manage(tts::TtsState::new());app.manage(editor_api::EditorState(std::sync::Mutex::new(None)));app.manage(PoolState(std::sync::Arc::new(std::sync::Mutex::new(wolfcut_media::ReaderPool::with_defaults(),@@ -913,7 +918,13 @@ pub fn run() {transcribe::cancel_model_download,transcribe::delete_transcriber_model,transcribe::transcribe_clip,- transcribe::cancel_transcribe+ transcribe::cancel_transcribe,+ tts::tts_status,+ tts::download_tts_model,+ tts::cancel_tts_model_download,+ tts::delete_tts_model,+ tts::speak_text,+ tts::cancel_speak]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/desktop/src-tauri/src/tts.rs b/desktop/src-tauri/src/tts.rsnew file mode 100644index 00000000..30ba8ded--- /dev/null+++ b/desktop/src-tauri/src/tts.rs@@ -0,0 +1,680 @@+//! Kokoro text-to-speech: text in, a narration WAV in the project folder out.+//!+//! The same local-first shape as transcription (`transcribe.rs`), with one+//! difference: whisper runs as a child process, Kokoro runs 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 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.+//! 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+//! user placed on the timeline is not) and returns its path for the+//! frontend to import like any other media file.++use std::io::Read;+use std::path::PathBuf;+use std::sync::atomic::Ordering;+use std::sync::{Arc, Mutex};++use serde::{Deserialize, Serialize};+use sherpa_onnx::{+ GenerationConfig, OfflineTts, OfflineTtsConfig, OfflineTtsKokoroModelConfig,+ OfflineTtsModelConfig,+};+use tauri::{Emitter, Manager};++use crate::jobs::SingleFlight;+use crate::projects;++/// One downloadable Kokoro bundle. Sizes are approximate, for progress bars+/// when the server declines to send a Content-Length.+struct KnownModel {+ id: &'static str,+ label: &'static str,+ /// One line for the settings row: what this size trades away.+ blurb: &'static str,+ approx_bytes: u64,+}++/// 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.+const KNOWN_MODELS: &[KnownModel] = &[+ KnownModel {+ id: "kokoro-int8-multi-lang-v1_0",+ label: "Kokoro (compact)",+ blurb: "The recommended build: same voices, a third of the download.",+ approx_bytes: 131_839_838,+ },+ KnownModel {+ id: "kokoro-multi-lang-v1_0",+ label: "Kokoro (full precision)",+ blurb: "Bit-perfect weights for the skeptical; rarely audibly better.",+ approx_bytes: 349_418_188,+ },+];++/// The speakers we offer, by Kokoro v1.0 speaker id.+///+/// The model bundles 53 voices across nine languages, but its lexicons (and+/// sherpa's text frontend) only genuinely cover English and Chinese, so only+/// those are listed. The name encodes accent and gender - `af` American+/// female, `bm` British male, `zf` Chinese female - which the frontend+/// decodes for display rather than us shipping 36 label strings.+const VOICES: &[(i32, &str)] = &[+ (0, "af_alloy"),+ (1, "af_aoede"),+ (2, "af_bella"),+ (3, "af_heart"),+ (4, "af_jessica"),+ (5, "af_kore"),+ (6, "af_nicole"),+ (7, "af_nova"),+ (8, "af_river"),+ (9, "af_sarah"),+ (10, "af_sky"),+ (11, "am_adam"),+ (12, "am_echo"),+ (13, "am_eric"),+ (14, "am_fenrir"),+ (15, "am_liam"),+ (16, "am_michael"),+ (17, "am_onyx"),+ (18, "am_puck"),+ (19, "am_santa"),+ (20, "bf_alice"),+ (21, "bf_emma"),+ (22, "bf_isabella"),+ (23, "bf_lily"),+ (24, "bm_daniel"),+ (25, "bm_fable"),+ (26, "bm_george"),+ (27, "bm_lewis"),+ (45, "zf_xiaobei"),+ (46, "zf_xiaoni"),+ (47, "zf_xiaoxiao"),+ (48, "zf_xiaoyi"),+ (49, "zm_yunjian"),+ (50, "zm_yunxi"),+ (51, "zm_yunxia"),+ (52, "zm_yunyang"),+];++fn known(id: &str) -> Option<&'static KnownModel> {+ KNOWN_MODELS.iter().find(|model| model.id == id)+}++fn model_url(id: &str) -> String {+ format!("https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/{id}.tar.bz2")+}++/// Where downloaded models live: `<app data>/tts-models/<id>/`.+fn models_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {+ let dir = app+ .path()+ .app_data_dir()+ .map_err(|error| format!("could not locate the data directory: {error}"))?+ .join("tts-models");+ std::fs::create_dir_all(&dir)+ .map_err(|error| format!("could not create {}: {error}", dir.display()))?;+ Ok(dir)+}++fn model_dir(app: &tauri::AppHandle, id: &str) -> Result<PathBuf, String> {+ // Ids come from our own table; anything else is a bug, not input.+ known(id).ok_or_else(|| format!("unknown model {id:?}"))?;+ Ok(models_dir(app)?.join(id))+}++/// The `.onnx` network inside an unpacked bundle. Located by scanning rather+/// than by name because the archives disagree - `model.onnx` in the full+/// build, `model.int8.onnx` in the quantised one.+fn onnx_file(dir: &std::path::Path) -> Option<PathBuf> {+ std::fs::read_dir(dir).ok()?.flatten().find_map(|entry| {+ let path = entry.path();+ (path.extension().is_some_and(|ext| ext == "onnx")).then_some(path)+ })+}++/// 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.+fn model_downloaded(app: &tauri::AppHandle, id: &str) -> bool {+ model_dir(app, id).is_ok_and(|dir| onnx_file(&dir).is_some())+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ModelStatus {+ id: String,+ label: String,+ blurb: String,+ /// Approximate download size in bytes, for display.+ size_bytes: u64,+ downloaded: bool,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct VoiceInfo {+ /// Kokoro speaker id, what synthesis wants back.+ id: i32,+ /// The upstream voice name, e.g. "af_heart"; the frontend decodes the+ /// accent/gender prefix and title-cases the rest.+ name: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct TtsStatus {+ /// Where models are stored, so the settings panel can say so.+ models_dir: String,+ models: Vec<ModelStatus>,+ voices: Vec<VoiceInfo>,+}++/// What the settings panel and the speech dialog show.+#[tauri::command]+pub fn tts_status(app: tauri::AppHandle) -> Result<TtsStatus, String> {+ let dir = models_dir(&app)?;+ Ok(TtsStatus {+ models_dir: dir.to_string_lossy().into_owned(),+ models: KNOWN_MODELS+ .iter()+ .map(|model| ModelStatus {+ id: model.id.to_owned(),+ label: model.label.to_owned(),+ blurb: model.blurb.to_owned(),+ size_bytes: model.approx_bytes,+ downloaded: model_downloaded(&app, model.id),+ })+ .collect(),+ voices: VOICES+ .iter()+ .map(|(id, name)| VoiceInfo {+ id: *id,+ name: (*name).to_owned(),+ })+ .collect(),+ })+}++/// Progress for one model download, emitted as `tts://download`.+#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+struct DownloadProgress {+ id: String,+ received: u64,+ /// Content-Length when the server sent one, the table estimate otherwise.+ total: u64,+ /// True while the archive is being unpacked - bytes stop moving but the+ /// job is far from done, and the bar should say so.+ unpacking: bool,+ done: bool,+}++/// The slot for the one model download that can run at a time.+pub struct TtsDownloadState(pub Arc<SingleFlight>);++/// Streams one bundle from the sherpa-onnx releases and unpacks it.+///+/// The archive lands in a `.part`, unpacks into a `.staging-<id>` folder, and+/// only the final rename puts `<id>/` in place - killed at any earlier point,+/// nothing is left that could be mistaken for a model.+#[tauri::command]+pub async fn download_tts_model(+ app: tauri::AppHandle,+ state: tauri::State<'_, TtsDownloadState>,+ id: String,+) -> Result<(), String> {+ let job = state.0.begin("voice model download")?;++ tauri::async_runtime::spawn_blocking(move || {+ let cancel = job.cancel_flag();+ let destination = model_dir(&app, &id)?;+ if onnx_file(&destination).is_some() {+ return Ok(());+ }+ let parent = models_dir(&app)?;+ let estimate = known(&id).map(|model| model.approx_bytes).unwrap_or(0);++ // A read timeout, or a stalled connection blocks in `read` forever+ // with the cancel flag unreachable - the flag is only checked between+ // reads. Thirty seconds without a byte means the download is dead.+ let agent = ureq::AgentBuilder::new()+ .timeout_connect(std::time::Duration::from_secs(20))+ .timeout_read(std::time::Duration::from_secs(30))+ .build();+ let response = agent+ .get(&model_url(&id))+ .call()+ .map_err(|error| format!("download failed: {error}"))?;+ let total = response+ .header("Content-Length")+ .and_then(|value| value.parse::<u64>().ok())+ .unwrap_or(estimate);++ let archive = parent.join(format!("{id}.tar.bz2.part"));+ let staging = parent.join(format!(".staging-{id}"));+ let result = (|| {+ let mut file = std::fs::File::create(&archive)+ .map_err(|error| format!("could not create {}: {error}", archive.display()))?;++ let mut reader = response.into_reader();+ let mut buffer = [0u8; 64 * 1024];+ let mut received: u64 = 0;+ let mut last_report: u64 = 0;++ loop {+ if cancel.load(Ordering::Relaxed) {+ return Err("download cancelled".to_owned());+ }+ let read = reader+ .read(&mut buffer)+ .map_err(|error| format!("download interrupted: {error}"))?;+ if read == 0 {+ break;+ }+ std::io::Write::write_all(&mut file, &buffer[..read])+ .map_err(|error| format!("could not write model: {error}"))?;+ received += read as u64;++ // Every 2 MB, not every chunk: the event crosses the IPC bridge.+ if received - last_report >= 2 * 1024 * 1024 {+ last_report = received;+ let _ = app.emit(+ "tts://download",+ DownloadProgress {+ id: id.clone(),+ received,+ total,+ unpacking: false,+ done: false,+ },+ );+ }+ }+ drop(file);++ // Unpacking a 130 MB bz2 takes long enough to deserve its own+ // phase on the progress bar.+ let _ = app.emit(+ "tts://download",+ DownloadProgress {+ id: id.clone(),+ received,+ total: received.max(total),+ unpacking: true,+ done: false,+ },+ );++ let _ = std::fs::remove_dir_all(&staging);+ std::fs::create_dir_all(&staging)+ .map_err(|error| format!("could not create {}: {error}", staging.display()))?;++ let file = std::fs::File::open(&archive)+ .map_err(|error| format!("could not reopen the download: {error}"))?;+ let tar = bzip2::read::BzDecoder::new(std::io::BufReader::new(file));+ let mut entries = tar::Archive::new(tar);+ for entry in entries+ .entries()+ .map_err(|error| format!("could not read the archive: {error}"))?+ {+ if cancel.load(Ordering::Relaxed) {+ return Err("download cancelled".to_owned());+ }+ // `unpack_in` refuses paths that escape the staging folder,+ // so a hostile archive can drop files nowhere else.+ entry+ .and_then(|mut entry| entry.unpack_in(&staging))+ .map_err(|error| format!("could not unpack the archive: {error}"))?;+ }++ let unpacked = staging.join(&id);+ if onnx_file(&unpacked).is_none() {+ return Err("the archive did not contain the expected model".to_owned());+ }+ // A leftover folder from an older torn unpack would fail the+ // rename; it holds no model (checked above), so it goes.+ let _ = std::fs::remove_dir_all(&destination);+ std::fs::rename(&unpacked, &destination)+ .map_err(|error| format!("could not finish {}: {error}", destination.display()))?;++ let _ = app.emit(+ "tts://download",+ DownloadProgress {+ id: id.clone(),+ received,+ total: received.max(total),+ unpacking: false,+ done: true,+ },+ );+ Ok(())+ })();++ // The archive and staging folder are dead weight whether the unpack+ // finished or failed; only `<id>/` matters now.+ let _ = std::fs::remove_file(&archive);+ let _ = std::fs::remove_dir_all(&staging);+ result+ })+ .await+ .map_err(|error| format!("download task failed: {error}"))?+}++/// Asks the running download to stop. Idle is a harmless no-op.+#[tauri::command]+pub fn cancel_tts_model_download(state: tauri::State<'_, TtsDownloadState>) {+ state.0.cancel();+}++/// The one synthesis that can run at a time, plus the loaded engine.+///+/// The engine is cached because loading means parsing a 100-300 MB network;+/// doing that per sentence would make the feature feel broken. The mutex is+/// held for the whole synthesis, which is what lets `delete_tts_model` use+/// `try_lock` to refuse deleting a model mid-use instead of yanking mapped+/// files out from under the session.+pub struct TtsState {+ gate: Arc<SingleFlight>,+ engine: Mutex<Option<CachedEngine>>,+}++struct CachedEngine {+ model_id: String,+ tts: OfflineTts,+}++impl TtsState {+ pub fn new() -> Self {+ Self {+ gate: Arc::new(SingleFlight::new()),+ engine: Mutex::new(None),+ }+ }+}++/// Removes a downloaded model folder, unless the engine is speaking from it.+#[tauri::command]+pub fn delete_tts_model(+ app: tauri::AppHandle,+ state: tauri::State<'_, TtsState>,+ id: String,+) -> Result<(), String> {+ let dir = model_dir(&app, &id)?;+ let mut engine = state+ .engine+ .try_lock()+ .map_err(|_| "speech is being generated - wait for it or cancel it first".to_owned())?;+ if engine.as_ref().is_some_and(|cached| cached.model_id == id) {+ *engine = None;+ }+ std::fs::remove_dir_all(&dir)+ .map_err(|error| format!("could not remove {}: {error}", dir.display()))+}++/// Builds the engine for one model folder.+///+/// 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: &std::path::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| {+ let path = dir.join(name);+ path.is_file().then(|| path.to_string_lossy().into_owned())+ };+ let lexicon: Vec<String> = ["lexicon-us-en.txt", "lexicon-zh.txt"]+ .iter()+ .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 {+ model: Some(network.to_string_lossy().into_owned()),+ voices: existing("voices.bin"),+ tokens: existing("tokens.txt"),+ data_dir: {+ let data = dir.join("espeak-ng-data");+ data.is_dir().then(|| data.to_string_lossy().into_owned())+ },+ dict_dir: {+ let dict = dir.join("dict");+ dict.is_dir().then(|| dict.to_string_lossy().into_owned())+ },+ lexicon: (!lexicon.is_empty()).then(|| lexicon.join(",")),+ ..Default::default()+ },+ 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())+}++/// Progress for one synthesis, emitted as `tts://progress`.+#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+struct SpeakProgress {+ /// 0..1, as reported by the engine.+ fraction: f32,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+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.+ pub voice: i32,+ /// What to say.+ pub text: String,+ /// Speaking rate; 1.0 is the voice's natural pace.+ pub speed: f32,+ /// The project folder the WAV should land in.+ pub project: String,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SpeakResult {+ /// Absolute path of the written WAV, ready for the media import path.+ path: String,+ /// Seconds of audio, so the frontend can toast something useful.+ duration: f64,+}++/// Synthesizes one narration clip into `<project>/audio/`.+#[tauri::command]+pub async fn speak_text(+ app: tauri::AppHandle,+ state: tauri::State<'_, TtsState>,+ request: SpeakRequest,+) -> Result<SpeakResult, String> {+ let job = state.gate.begin("speech generation")?;++ tauri::async_runtime::spawn_blocking(move || {+ // Re-fetched through the app handle because the borrow in `state`+ // cannot cross into a 'static task; the managed value is the same.+ let state = app.state::<TtsState>();+ let cancel = job.cancel_handle();++ let text = request.text.trim();+ 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 speed = if request.speed.is_finite() {+ request.speed.clamp(0.5, 2.0)+ } else {+ 1.0+ };++ let dir = model_dir(&app, &request.model_id)?;+ if onnx_file(&dir).is_none() {+ return Err(format!(+ "model {} is not downloaded - see Settings > Speech",+ request.model_id+ ));+ }++ // The WAV goes in the project so it travels (and dies) with it - and+ // in `audio/`, not `cache/`, because a clip on the timeline points at+ // it: cache is for things that can be regenerated.+ let root = std::path::Path::new(&request.project);+ if !projects::manifest_path(root).is_file() {+ return Err(format!("{} is not a project folder", request.project));+ }+ let out_dir = root.join("audio");+ std::fs::create_dir_all(&out_dir)+ .map_err(|error| format!("could not create {}: {error}", out_dir.display()))?;++ let mut engine = state+ .engine+ .lock()+ .map_err(|_| "speech state poisoned".to_owned())?;+ 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)?;+ *engine = Some(CachedEngine {+ model_id: request.model_id.clone(),+ tts,+ });+ }+ let tts = &engine.as_ref().expect("engine cached above").tts;++ let progress_app = app.clone();+ let progress_cancel = Arc::clone(&cancel);+ let mut last_fraction = -1.0f32;+ let audio = tts+ .generate_with_config(+ text,+ &GenerationConfig {+ sid: request.voice,+ speed,+ ..Default::default()+ },+ Some(move |_samples: &[f32], fraction: f32| -> bool {+ if progress_cancel.load(Ordering::Relaxed) {+ return false;+ }+ // The engine reports once per sentence; only meaningful+ // movement crosses the IPC bridge.+ if fraction - last_fraction >= 0.01 {+ last_fraction = fraction;+ let _ = progress_app.emit("tts://progress", SpeakProgress { fraction });+ }+ true+ }),+ )+ .ok_or_else(|| "speech generation failed".to_owned())?;++ // A cancelled run still returns the samples made so far; the user+ // asked for none of them.+ if cancel.load(Ordering::Relaxed) {+ return Err("speech generation cancelled".to_owned());+ }+ if audio.samples().is_empty() {+ 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()));+ }++ let duration = audio.samples().len() as f64 / f64::from(audio.sample_rate().max(1));+ Ok(SpeakResult {+ path: file.to_string_lossy().into_owned(),+ duration,+ })+ })+ .await+ .map_err(|error| format!("speech task failed: {error}"))?+}++/// Asks the running synthesis to stop at the next sentence boundary.+#[tauri::command]+pub fn cancel_speak(state: tauri::State<'_, TtsState>) {+ state.gate.cancel();+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_known_model_has_a_url_and_size() {+ for model in KNOWN_MODELS {+ assert!(model_url(model.id).ends_with(&format!("{}.tar.bz2", model.id)));+ assert!(model.approx_bytes > 0);+ }+ }++ #[test]+ fn voice_ids_are_unique_and_names_well_formed() {+ let mut seen = std::collections::HashSet::new();+ for (id, name) in VOICES {+ assert!(seen.insert(*id), "duplicate voice id {id}");+ // The frontend decodes accent and gender from the prefix; a name+ // that breaks the pattern would render as gibberish.+ let (prefix, rest) = name.split_once('_').expect("prefix_name shape");+ assert!(+ matches!(prefix, "af" | "am" | "bf" | "bm" | "zf" | "zm"),+ "{name}"+ );+ assert!(!rest.is_empty());+ }+ }++ #[test]+ fn finds_the_onnx_network_by_extension() {+ let scratch = std::env::temp_dir().join(format!("wolfcut-tts-test-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&scratch);+ std::fs::create_dir_all(&scratch).expect("scratch dir");+ assert!(onnx_file(&scratch).is_none());+ std::fs::write(scratch.join("model.int8.onnx"), b"x").expect("writes");+ assert!(onnx_file(&scratch).is_some());+ let _ = std::fs::remove_dir_all(&scratch);+ }+}diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 7cba8e68..32e5da32 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -7,6 +7,7 @@ import { getCurrentWindow } from "@tauri-apps/api/window";import { ConfirmDialog } from "./components/ConfirmDialog";import { ContextMenu, type ContextTarget } from "./components/ContextMenu";import { ExportDialog } from "./components/ExportDialog";+import { TtsDialog } from "./components/TtsDialog";import { Icon } from "./components/Icon";import { ALL_MEDIA, MediaBin, type BinFilter } from "./components/MediaBin";import type { MenuOption } from "./components/Menu";@@ -277,6 +278,7 @@ function Editor({);const [settingsOpen, setSettingsOpen] = useState(false);+ const [speechOpen, setSpeechOpen] = useState(false);// The save-as-template sheet: null closed, otherwise whether the host is// packing the bundle right now.const [templateDialog, setTemplateDialog] = useState<null | { busy: boolean }>(null);@@ -356,6 +358,33 @@ function Editor({[dispatch, session.path],);+ // A finished narration WAV: imported like any dropped file, then placed at+ // the playhead. Throwing lets the speech sheet show the failure in place.+ const insertNarration = useCallback(+ async (path: string) => {+ const summary = await probeMedia(path);+ const mediaId = await dispatch({+ op: "addMedia",+ item: newMediaFromSummary(summary),+ });+ if (!mediaId) throw new Error(t("tts.importFailed"));+ requestAssets(+ assets.current,+ {+ id: mediaId,+ path: summary.path,+ kind: summary.kind,+ duration: summary.duration,+ hasAudio: summary.audio !== null,+ },+ session.path,+ );+ await dispatch({ op: "addClipAtFirstFree", mediaId, start: latest.current.playhead });+ pushToast(t("toast.narrationAdded"), false);+ },+ [dispatch, session.path, pushToast, t],+ );+// Artwork for everything already in the project: a reopened project should// get its thumbnails and waveforms back without re-importing anything.useEffect(() => {@@ -814,6 +843,7 @@ function Editor({const openModifyProject = useCallback(() => setModifyingProject({ busy: false }), []);const openSettings = useCallback(() => setSettingsOpen(true), []);+ const openSpeech = useCallback(() => setSpeechOpen(true), []);const openExport = useCallback(() => setExporting(true), []);// ── keyboard ─────────────────────────────────────────────────────────────@@ -1047,6 +1077,11 @@ function Editor({icon: "slot",onSelect: openTemplateDialog,},+ {+ label: t("menu.file.speech"),+ icon: "volume",+ onSelect: openSpeech,+ },],[{@@ -1146,6 +1181,7 @@ function Editor({onCloseProject,openExport,openSettings,+ openSpeech,openTemplateDialog,placeMediaSet,redoAction,@@ -1484,6 +1520,13 @@ function Editor({{context && <ContextMenu target={context} onClose={() => setContext(null)} />}{settingsOpen && <SettingsDialog onClose={() => setSettingsOpen(false)} />}+ {speechOpen && (+ <TtsDialog+ projectPath={session.path}+ onGenerated={insertNarration}+ onClose={() => setSpeechOpen(false)}+ />+ )}{modifyingProject && (<ModifyProjectDialogdiff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsxindex ff2b19b0..ce4fdae0 100644--- a/desktop/src/components/SettingsDialog.tsx+++ b/desktop/src/components/SettingsDialog.tsx@@ -3,30 +3,43 @@ import { open } from "@tauri-apps/plugin-dialog";import {cancelModelDownload,+ cancelTtsModelDownload,deleteTranscriberModel,+ deleteTtsModel,downloadTranscriberModel,+ downloadTtsModel,engineVersion,onTranscriberDownload,+ onTtsDownload,setTranscriberBinary,transcriberStatus,+ ttsStatus,type TranscriberStatus,+ type TtsStatus,} from "../lib/engine";import { LOCALES, systemLocale, useLocale, type MsgKey } from "../lib/i18n";import {getTranscriberLanguage,getTranscriberModel,+ getTtsModel,setTranscriberLanguage,setTranscriberModel,+ setTtsModel,} from "../lib/settings";import { HelpTip } from "./controls";import { Icon } from "./Icon";/** The pages of the settings dialog, in display order. */-type SettingsTab = "general" | "transcriber" | "about";+type SettingsTab = "general" | "transcriber" | "speech" | "about";-const TABS: { id: SettingsTab; labelKey: MsgKey; icon: "settings" | "waveform" | "info" }[] = [+const TABS: {+ id: SettingsTab;+ labelKey: MsgKey;+ icon: "settings" | "waveform" | "volume" | "info";+}[] = [{ id: "general", labelKey: "settings.tabs.general", icon: "settings" },{ id: "transcriber", labelKey: "settings.tabs.transcriber", icon: "waveform" },+ { id: "speech", labelKey: "settings.tabs.speech", icon: "volume" },{ id: "about", labelKey: "settings.tabs.about", icon: "info" },];@@ -87,6 +100,7 @@ export function SettingsDialog({ onClose }: { onClose: () => void }) {<div className="thin-scroll min-w-0 flex-1 overflow-y-auto px-5 py-4">{tab === "general" && <GeneralSettings />}{tab === "transcriber" && <TranscriberSettings />}+ {tab === "speech" && <SpeechSettings />}{tab === "about" && <AboutSettings />}</div></div>@@ -406,6 +420,203 @@ function TranscriberSettings() {);}+/**+ * The speech (text to speech) page: which Kokoro bundle to keep on disk.+ *+ * The same shape as the transcriber page, minus the binary bar (synthesis+ * runs in-process, there is no tool to locate) and minus a language toggle+ * (the voice picked in the speech dialog carries the language).+ */+function SpeechSettings() {+ const { t } = useLocale();+ const [status, setStatus] = useState<TtsStatus | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [model, setModel] = useState(getTtsModel());+ /** The model being fetched: how far along, and whether it is unpacking. */+ const [download, setDownload] = useState<{+ id: string;+ fraction: number;+ unpacking: boolean;+ } | null>(null);+ const unlisten = useRef<(() => void) | null>(null);++ const refresh = () => {+ ttsStatus()+ .then((next) => {+ setStatus(next);+ setError(null);+ })+ .catch((cause: unknown) => setError(String(cause)));+ };++ useEffect(() => {+ refresh();+ void onTtsDownload((progress) => {+ if (progress.done) {+ setDownload(null);+ refresh();+ } else {+ setDownload({+ id: progress.id,+ fraction: progress.total > 0 ? progress.received / progress.total : 0,+ unpacking: progress.unpacking,+ });+ }+ }).then((stop) => {+ unlisten.current = stop;+ });+ return () => unlisten.current?.();+ }, []);++ const startDownload = (id: string) => {+ setDownload({ id, fraction: 0, unpacking: false });+ downloadTtsModel(id)+ .then(() => {+ setDownload(null);+ refresh();+ })+ .catch((cause: unknown) => {+ setDownload(null);+ setError(String(cause));+ refresh();+ });+ };++ const remove = (id: string) => {+ deleteTtsModel(id)+ .then(refresh)+ .catch((cause: unknown) => setError(String(cause)));+ };++ const chooseModel = (id: string) => {+ setModel(id);+ setTtsModel(id);+ };++ return (+ <div className="flex flex-col gap-5">+ <section>+ <h3 className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-tertiary">+ {t("settings.speech.models")}+ <HelpTip align="start" text={t("settings.speech.modelsHelp")} />+ </h3>++ <ul className="flex flex-col gap-1.5">+ {(status?.models ?? []).map((entry) => {+ const downloading = download?.id === entry.id;+ const selected = model === entry.id;+ return (+ <li+ key={entry.id}+ onClick={() => entry.downloaded && chooseModel(entry.id)}+ className={`flex items-center gap-2.5 rounded-lg px-3 py-2 ring-1 transition-shadow ${+ selected ? "ring-accent" : "ring-hairline"+ } ${entry.downloaded ? "cursor-pointer" : ""} ${+ entry.downloaded && !selected ? "hover:ring-hairline-strong" : ""+ }`}+ >+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ aria-label={t("settings.speech.useModel", { model: entry.label })}+ disabled={!entry.downloaded}+ onClick={() => chooseModel(entry.id)}+ title={+ entry.downloaded+ ? t("settings.speech.useModelHint")+ : t("settings.speech.downloadFirstHint")+ }+ className="flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center+ rounded-full ring-1 ring-hairline-strong+ disabled:cursor-not-allowed disabled:opacity-40"+ >+ {selected && <span className="h-2 w-2 rounded-full bg-accent" />}+ </button>++ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs text-primary">{entry.label}</span>+ <span className="block truncate text-[11px] text-tertiary">{entry.blurb}</span>+ </span>++ <span className="shrink-0 font-technical text-[10px] text-tertiary">+ {formatSize(entry.sizeBytes)}+ </span>++ {downloading ? (+ <span className="flex shrink-0 items-center gap-1.5">+ {download.unpacking ? (+ <span className="text-[10px] text-tertiary">+ {t("settings.speech.unpacking")}+ </span>+ ) : (+ <span className="h-1 w-16 overflow-hidden rounded-full bg-sunken">+ <span+ className="block h-full bg-accent transition-[width]"+ style={{ width: `${Math.round(download.fraction * 100)}%` }}+ />+ </span>+ )}+ <button+ type="button"+ aria-label={t("settings.speech.cancelDownload")}+ onClick={(event) => {+ event.stopPropagation();+ void cancelTtsModelDownload();+ }}+ className="cursor-pointer rounded p-0.5 text-secondary hover:bg-hover+ hover:text-primary"+ >+ <Icon name="close" size={10} />+ </button>+ </span>+ ) : entry.downloaded ? (+ <span className="flex shrink-0 items-center gap-1">+ <Icon name="check" size={12} className="text-success" />+ <button+ type="button"+ aria-label={t("settings.speech.deleteModel", { model: entry.label })}+ title={t("settings.speech.deleteModelHint")}+ onClick={(event) => {+ event.stopPropagation();+ remove(entry.id);+ }}+ className="cursor-pointer rounded p-0.5 text-secondary transition-colors+ hover:bg-hover hover:text-danger"+ >+ <Icon name="trash" size={11} />+ </button>+ </span>+ ) : (+ <button+ type="button"+ disabled={download !== null}+ onClick={(event) => {+ event.stopPropagation();+ startDownload(entry.id);+ }}+ className="shrink-0 cursor-pointer rounded-md bg-panel px-2.5 py-1 text-[11px]+ text-primary ring-1 ring-hairline transition-colors hover:bg-hover+ disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t("settings.speech.download")}+ </button>+ )}+ </li>+ );+ })}+ </ul>++ <p className="mt-2 text-[11px] leading-snug text-tertiary">+ {t("settings.speech.privacyNote")}+ </p>++ {error && <p className="mt-2 text-[11px] leading-snug text-danger">{error}</p>}+ </section>+ </div>+ );+}+function AboutSettings() {const { t } = useLocale();const [version, setVersion] = useState<string | null>(null);diff --git a/desktop/src/components/TtsDialog.tsx b/desktop/src/components/TtsDialog.tsxnew file mode 100644index 00000000..9d26c218--- /dev/null+++ b/desktop/src/components/TtsDialog.tsx@@ -0,0 +1,356 @@+import { useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";++import {+ cancelSpeak,+ cancelTtsModelDownload,+ downloadTtsModel,+ onSpeakProgress,+ onTtsDownload,+ speakText,+ ttsStatus,+ type TtsStatus,+ type TtsVoice,+} from "../lib/engine";+import { useLocale, type MsgKey } from "../lib/i18n";+import { getTtsModel, getTtsVoice, setTtsVoice } from "../lib/settings";+import { ErrorNotice } from "./ErrorNotice";+import { Icon } from "./Icon";++/** Speaking-rate presets, in the terms a person picking one thinks in. */+const PACES: { labelKey: MsgKey; speed: number }[] = [+ { labelKey: "tts.pace.slower", speed: 0.85 },+ { labelKey: "tts.pace.natural", speed: 1.0 },+ { labelKey: "tts.pace.faster", speed: 1.2 },+];++type Phase =+ | { kind: "idle" }+ | { kind: "running"; fraction: number }+ | { kind: "failed"; message: string };++/**+ * Decodes a Kokoro voice name's prefix - `af` American female, `bm` British+ * male, `zf` Chinese female - into the keys of its picker group.+ */+function voiceGroup(name: string): { accent: MsgKey; gender: MsgKey } | null {+ const accent: Record<string, MsgKey> = {+ a: "tts.accent.american",+ b: "tts.accent.british",+ z: "tts.accent.chinese",+ };+ const gender: Record<string, MsgKey> = {+ f: "tts.gender.female",+ m: "tts.gender.male",+ };+ const [prefix] = name.split("_");+ const a = accent[prefix?.[0] ?? ""];+ const g = gender[prefix?.[1] ?? ""];+ return a && g ? { accent: a, gender: g } : null;+}++/** "af_heart" -> "Heart": the part after the prefix, title-cased. */+function voiceLabel(name: string): string {+ const rest = name.split("_")[1] ?? name;+ return rest.charAt(0).toUpperCase() + rest.slice(1);+}++/**+ * The speech sheet: text in, a narration clip at the playhead out.+ *+ * Synthesis runs in the host and reports through an event, so this listens+ * rather than waits - a paragraph takes long enough that a silent button+ * reads as a hang. If the voice model is not on disk yet the sheet offers+ * the download right here instead of sending the user to Settings first.+ */+export function TtsDialog({+ projectPath,+ onGenerated,+ onClose,+}: {+ /** The open project's folder - where the host writes the WAV. */+ projectPath: string;+ /** Places the finished WAV on the timeline; throwing lands in the sheet's+ * error notice. The sheet closes itself afterwards. */+ onGenerated: (path: string, duration: number) => Promise<void>;+ onClose: () => void;+}) {+ const { t } = useLocale();+ const [text, setText] = useState("");+ const [voice, setVoice] = useState(getTtsVoice());+ const [speed, setSpeed] = useState(1.0);+ const [phase, setPhase] = useState<Phase>({ kind: "idle" });+ const [status, setStatus] = useState<TtsStatus | null>(null);+ /** Fraction of the model download, or "unpacking", or null when idle. */+ const [download, setDownload] = useState<{ fraction: number; unpacking: boolean } | null>(null);+ const unlisten = useRef<(() => void)[]>([]);++ const model = getTtsModel();++ const refresh = () => {+ ttsStatus()+ .then(setStatus)+ .catch((cause: unknown) => setPhase({ kind: "failed", message: String(cause) }));+ };++ useEffect(() => {+ const stops = unlisten.current;+ refresh();+ void onSpeakProgress(({ fraction }) => {+ setPhase((current) => (current.kind === "running" ? { kind: "running", fraction } : current));+ }).then((stop) => stops.push(stop));+ void onTtsDownload((progress) => {+ if (progress.done) {+ setDownload(null);+ refresh();+ } else {+ setDownload({+ fraction: progress.total > 0 ? progress.received / progress.total : 0,+ unpacking: progress.unpacking,+ });+ }+ }).then((stop) => stops.push(stop));+ return () => stops.forEach((stop) => stop());+ }, []);++ // A remembered id that no longer names a known model (an old build's+ // catalog, say) falls back to the first offered one instead of a dead sheet.+ const entry =+ status?.models.find((candidate) => candidate.id === model) ?? status?.models[0] ?? null;+ const ready = entry?.downloaded ?? false;+ const running = phase.kind === "running";++ /** Voices in picker order, grouped by accent and gender. */+ const groups: { label: string; voices: TtsVoice[] }[] = [];+ for (const candidate of status?.voices ?? []) {+ const decoded = voiceGroup(candidate.name);+ if (!decoded) continue;+ const label = `${t(decoded.accent)} · ${t(decoded.gender)}`;+ const group = groups.find((existing) => existing.label === label);+ if (group) group.voices.push(candidate);+ else groups.push({ label, voices: [candidate] });+ }++ const fetchModel = () => {+ if (!entry) return;+ setDownload({ fraction: 0, unpacking: false });+ downloadTtsModel(entry.id)+ .then(() => {+ setDownload(null);+ refresh();+ })+ .catch((cause: unknown) => {+ setDownload(null);+ setPhase({ kind: "failed", message: String(cause) });+ refresh();+ });+ };++ const generate = async () => {+ if (running || !ready || !entry || !text.trim()) return;+ setPhase({ kind: "running", fraction: 0 });+ try {+ const result = await speakText({+ modelId: entry.id,+ voice,+ text: text.trim(),+ speed,+ project: projectPath,+ });+ await onGenerated(result.path, result.duration);+ onClose();+ } catch (cause) {+ const message = String(cause);+ // A cancel is the user's own decision, not a failure to report.+ if (message.includes("cancelled")) setPhase({ kind: "idle" });+ else setPhase({ kind: "failed", message });+ }+ };++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-8+ backdrop-blur-[2px]"+ onMouseDown={(event) => {+ // The backdrop closes the sheet the way every sheet closes - but+ // never out from under a running synthesis.+ if (event.target === event.currentTarget && !running) onClose();+ }}+ >+ <div className="surface w-full max-w-md rounded-2xl p-6">+ <div className="mb-5 flex items-center gap-2">+ <Icon name="volume" size={17} className="text-accent" />+ <h2 className="flex-1 text-sm font-semibold text-primary">{t("tts.title")}</h2>+ {!running && (+ <button+ type="button"+ aria-label={t("common.close")}+ onClick={onClose}+ className="cursor-pointer rounded p-1 text-secondary hover:bg-hover hover:text-primary"+ >+ <Icon name="close" size={14} />+ </button>+ )}+ </div>++ {status !== null && !ready ? (+ // No model on disk: the sheet is a download button until there is.+ <div className="py-2">+ <p className="mb-4 text-xs leading-relaxed text-secondary">{t("tts.modelNeeded")}</p>+ {download ? (+ <>+ <div className="mb-2 flex items-baseline justify-between gap-3">+ <span className="text-xs text-primary">+ {download.unpacking ? t("tts.unpacking") : t("tts.downloading")}+ </span>+ {!download.unpacking && (+ <span className="shrink-0 font-technical text-sm tabular-nums text-primary">+ {`${Math.round(download.fraction * 100)}%`}+ </span>+ )}+ </div>+ <div className="h-1.5 overflow-hidden rounded-full bg-active">+ <div+ className="h-full rounded-full bg-accent transition-[width] duration-200"+ style={{ width: `${download.unpacking ? 100 : Math.round(download.fraction * 100)}%` }}+ />+ </div>+ <button+ type="button"+ onClick={() => void cancelTtsModelDownload()}+ className="mt-4 w-full cursor-pointer rounded-lg bg-hover px-4 py-2 text-xs+ text-secondary transition-colors hover:bg-active hover:text-primary"+ >+ {t("common.cancel")}+ </button>+ </>+ ) : (+ <>+ {phase.kind === "failed" && <ErrorNotice message={phase.message} className="mb-4" />}+ <button+ type="button"+ onClick={fetchModel}+ className="flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg+ bg-accent px-4 py-2.5 text-sm font-medium text-on-accent+ transition-colors hover:bg-accent-hover"+ >+ <Icon name="import" size={15} />+ {t("tts.downloadModel", {+ size: entry ? `${Math.round(entry.sizeBytes / 1_000_000)} MB` : "",+ })}+ </button>+ </>+ )}+ </div>+ ) : (+ <>+ <Label>{t("tts.textLabel")}</Label>+ <textarea+ value={text}+ onChange={(event) => setText(event.target.value)}+ placeholder={t("tts.textPlaceholder")}+ rows={5}+ autoFocus+ disabled={running}+ className="mb-5 w-full resize-none rounded-lg border border-hairline bg-sunken px-3+ py-2 text-xs leading-relaxed text-primary placeholder:text-tertiary+ focus:border-accent focus:outline-none disabled:opacity-60"+ />++ <Label>{t("tts.voiceLabel")}</Label>+ <select+ value={voice}+ disabled={running}+ onChange={(event) => {+ const next = Number(event.target.value);+ setVoice(next);+ setTtsVoice(next);+ }}+ className="mb-5 w-full cursor-pointer rounded-lg border border-hairline bg-sunken+ px-3 py-2 text-xs text-primary focus:border-accent focus:outline-none+ disabled:opacity-60"+ >+ {groups.map((group) => (+ <optgroup key={group.label} label={group.label}>+ {group.voices.map((candidate) => (+ <option key={candidate.id} value={candidate.id}>+ {voiceLabel(candidate.name)}+ </option>+ ))}+ </optgroup>+ ))}+ </select>++ <Label>{t("tts.paceLabel")}</Label>+ <div className="mb-5 grid grid-cols-3 gap-1.5">+ {PACES.map((option) => (+ <button+ key={option.labelKey}+ type="button"+ aria-pressed={option.speed === speed}+ disabled={running}+ onClick={() => setSpeed(option.speed)}+ className={`cursor-pointer rounded-lg px-2 py-1.5 text-xs transition-colors ${+ option.speed === speed+ ? "bg-accent text-on-accent"+ : "bg-hover text-secondary hover:bg-active"+ }`}+ >+ {t(option.labelKey)}+ </button>+ ))}+ </div>++ {phase.kind === "failed" && <ErrorNotice message={phase.message} className="mb-4" />}++ {running ? (+ <div>+ <div className="mb-2 flex items-baseline justify-between gap-3">+ <span className="text-xs text-primary">{t("tts.generating")}</span>+ <span className="shrink-0 font-technical text-sm tabular-nums text-primary">+ {`${Math.round(phase.fraction * 100)}%`}+ </span>+ </div>+ <div className="h-1.5 overflow-hidden rounded-full bg-active">+ <div+ className="h-full rounded-full bg-accent transition-[width] duration-200"+ style={{ width: `${Math.max(3, Math.round(phase.fraction * 100))}%` }}+ />+ </div>+ <button+ type="button"+ onClick={() => void cancelSpeak().catch(() => undefined)}+ className="mt-4 w-full cursor-pointer rounded-lg bg-hover px-4 py-2 text-xs+ text-secondary transition-colors hover:bg-active hover:text-primary"+ >+ {t("common.cancel")}+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => void generate()}+ disabled={!text.trim() || !ready}+ className="flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg+ bg-accent px-4 py-2.5 text-sm font-medium text-on-accent+ transition-colors hover:bg-accent-hover disabled:cursor-not-allowed+ disabled:opacity-40"+ >+ <Icon name="volume" size={15} />+ {t("tts.generate")}+ </button>+ )}+ </>+ )}+ </div>+ </div>+ );+}++function Label({ children }: { children: ReactNode }) {+ return (+ <span className="mb-1.5 block text-[11px] font-semibold uppercase tracking-wider text-secondary">+ {children}+ </span>+ );+}diff --git a/desktop/src/lib/engine.ts b/desktop/src/lib/engine.tsindex e7eafed1..9e2c428d 100644--- a/desktop/src/lib/engine.ts+++ b/desktop/src/lib/engine.ts@@ -522,3 +522,102 @@ export async function transcribeClip(export async function cancelTranscribe(): Promise<void> {return invoke<void>("cancel_transcribe");}++// ── text to speech ─────────────────────────────────────────────────────────++/** One Kokoro bundle, as the settings panel sees it. */+export interface TtsModel {+ id: string;+ label: string;+ blurb: string;+ /** Approximate download size in bytes, for display. */+ sizeBytes: number;+ downloaded: boolean;+}++/**+ * One Kokoro speaker. The name encodes accent and gender in its prefix -+ * `af` American female, `bm` British male, `zf` Chinese female - which the+ * speech dialog decodes for display.+ */+export interface TtsVoice {+ /** Kokoro speaker id, what `speakText` wants back. */+ id: number;+ name: string;+}++export interface TtsStatus {+ /** Where models are stored on disk. */+ modelsDir: string;+ models: TtsModel[];+ voices: TtsVoice[];+}++/** Progress of a model download, via `tts://download`. */+export interface TtsDownload {+ id: string;+ received: number;+ total: number;+ /** True while the archive unpacks - bytes stop moving, the job continues. */+ unpacking: boolean;+ done: boolean;+}++export interface SpeakRequest {+ modelId: string;+ /** Kokoro speaker id, from the status' voices table. */+ voice: number;+ text: string;+ /** Speaking rate; 1.0 is the voice's natural pace. */+ speed: number;+ /** The project folder the WAV should land in. */+ project: string;+}++export interface SpeakResult {+ /** Absolute path of the written WAV, ready for the media import path. */+ path: string;+ /** Seconds of audio. */+ duration: number;+}++export async function ttsStatus(): Promise<TtsStatus> {+ return invoke<TtsStatus>("tts_status");+}++/** Downloads one voice model. Resolves once unpacked into place. */+export async function downloadTtsModel(id: string): Promise<void> {+ return invoke<void>("download_tts_model", { id });+}++export async function cancelTtsModelDownload(): Promise<void> {+ return invoke<void>("cancel_tts_model_download");+}++export async function deleteTtsModel(id: string): Promise<void> {+ return invoke<void>("delete_tts_model", { id });+}++/** Subscribes to voice model download progress. Resolves to an unsubscribe function. */+export async function onTtsDownload(+ handler: (progress: TtsDownload) => void,+): Promise<UnlistenFn> {+ return listen<TtsDownload>("tts://download", (event) => handler(event.payload));+}++/** Synthesizes narration into `<project>/audio/` and returns the WAV's path. */+export async function speakText(request: SpeakRequest): Promise<SpeakResult> {+ return invoke<SpeakResult>("speak_text", { request });+}++/** Asks the running synthesis to stop at the next sentence boundary. */+export async function cancelSpeak(): Promise<void> {+ return invoke<void>("cancel_speak");+}++/** Subscribes to synthesis progress (0..1). Resolves to an unsubscribe function. */+export async function onSpeakProgress(+ handler: (progress: { fraction: number }) => void,+): Promise<UnlistenFn> {+ return listen<{ fraction: number }>("tts://progress", (event) => handler(event.payload));+}diff --git a/desktop/src/lib/settings.ts b/desktop/src/lib/settings.tsindex 721304ca..48243086 100644--- a/desktop/src/lib/settings.ts+++ b/desktop/src/lib/settings.ts@@ -29,3 +29,32 @@ export function getTranscriberLanguage(): string {export function setTranscriberLanguage(code: string): void {localStorage.setItem(LANGUAGE_KEY, code);}++const TTS_MODEL_KEY = "wolfcut.tts.model";+const TTS_VOICE_KEY = "wolfcut.tts.voice";++/** The default voice model: the compact build the settings panel recommends. */+export const DEFAULT_TTS_MODEL = "kokoro-int8-multi-lang-v1_0";++/** The default speaker: af_heart, Kokoro's showcase voice. */+export const DEFAULT_TTS_VOICE = 3;++export function getTtsModel(): string {+ return localStorage.getItem(TTS_MODEL_KEY) ?? DEFAULT_TTS_MODEL;+}++export function setTtsModel(id: string): void {+ localStorage.setItem(TTS_MODEL_KEY, id);+}++/** A Kokoro speaker id, from the host's voices table. */+export function getTtsVoice(): number {+ const raw = localStorage.getItem(TTS_VOICE_KEY);+ if (raw === null) return DEFAULT_TTS_VOICE;+ const stored = Number(raw);+ return Number.isInteger(stored) && stored >= 0 ? stored : DEFAULT_TTS_VOICE;+}++export function setTtsVoice(id: number): void {+ localStorage.setItem(TTS_VOICE_KEY, String(id));+}diff --git a/desktop/src/locales/en.json b/desktop/src/locales/en.jsonindex d8d7f7eb..73e8e421 100644--- a/desktop/src/locales/en.json+++ b/desktop/src/locales/en.json@@ -274,6 +274,7 @@"menu.file.save": "Save","menu.file.saveAsTemplate": "Save as template...","menu.file.settings": "Settings...",+ "menu.file.speech": "Text to speech...","menu.file.title": "File","menu.view.goToEnd": "Go to end","menu.view.goToStart": "Go to start",@@ -319,8 +320,20 @@"settings.general.engineNote": "Some text from the engine appears in English.","settings.general.language": "Language","settings.general.systemDefault": "System default ({language})",+ "settings.speech.cancelDownload": "Cancel download",+ "settings.speech.deleteModel": "Delete {model}",+ "settings.speech.deleteModelHint": "Delete the downloaded model",+ "settings.speech.download": "Download",+ "settings.speech.downloadFirstHint": "Download it first",+ "settings.speech.models": "Voice models",+ "settings.speech.modelsHelp": "Both builds carry the same voices and differ only in precision; the compact one is a third of the download and rarely audibly different. The selected build is what Text to speech uses.",+ "settings.speech.privacyNote": "Voices download once and are stored locally. Generating speech never touches the network.",+ "settings.speech.unpacking": "Unpacking...",+ "settings.speech.useModel": "Use {model}",+ "settings.speech.useModelHint": "Use this model","settings.tabs.about": "About","settings.tabs.general": "General",+ "settings.tabs.speech": "Speech","settings.tabs.transcriber": "Transcriber","settings.title": "Settings","settings.transcriber.cancelDownload": "Cancel download",@@ -470,6 +483,7 @@"titleBar.switchLight": "Switch to light","titleBar.switchLightAria": "Switch to light theme","toast.effectNeedsClip": "Select a video or image clip on the timeline first",+ "toast.narrationAdded": "Narration added at the playhead","toast.projectDetailsSaved": "Project details saved","toast.projectSaved": "Project saved","toast.saveFailed": "Save failed: {message}",@@ -492,5 +506,25 @@"transitions.wipe-right.blurb": "The incoming clip sweeps in from the left edge.","transitions.wipe-right.label": "Wipe Right","transitions.zoom.blurb": "Punches in on the cut, then settles.",- "transitions.zoom.label": "Zoom"+ "transitions.zoom.label": "Zoom",+ "tts.accent.american": "American English",+ "tts.accent.british": "British English",+ "tts.accent.chinese": "Chinese",+ "tts.downloadModel": "Download voice model ({size})",+ "tts.downloading": "Downloading...",+ "tts.gender.female": "Female",+ "tts.gender.male": "Male",+ "tts.generate": "Generate speech",+ "tts.generating": "Generating...",+ "tts.importFailed": "The generated audio could not be added to the project",+ "tts.modelNeeded": "Speech is generated by the Kokoro voice model, entirely on this machine. It downloads once; after that, nothing you type ever leaves this computer.",+ "tts.pace.faster": "Faster",+ "tts.pace.natural": "Natural",+ "tts.pace.slower": "Slower",+ "tts.paceLabel": "Pace",+ "tts.textLabel": "Text",+ "tts.textPlaceholder": "Type the narration to read aloud...",+ "tts.title": "Text to speech",+ "tts.unpacking": "Unpacking...",+ "tts.voiceLabel": "Voice"}diff --git a/desktop/src/locales/zh-CN.json b/desktop/src/locales/zh-CN.jsonindex 2caeb902..bd33d269 100644--- a/desktop/src/locales/zh-CN.json+++ b/desktop/src/locales/zh-CN.json@@ -274,6 +274,7 @@"menu.file.save": "保存","menu.file.saveAsTemplate": "保存为模板...","menu.file.settings": "设置...",+ "menu.file.speech": "文字转语音...","menu.file.title": "文件","menu.view.goToEnd": "跳到结尾","menu.view.goToStart": "跳到开头",@@ -319,8 +320,20 @@"settings.general.engineNote": "来自引擎的部分文本仍以英文显示。","settings.general.language": "语言","settings.general.systemDefault": "系统默认({language})",+ "settings.speech.cancelDownload": "取消下载",+ "settings.speech.deleteModel": "删除 {model}",+ "settings.speech.deleteModelHint": "删除已下载的模型",+ "settings.speech.download": "下载",+ "settings.speech.downloadFirstHint": "请先下载",+ "settings.speech.models": "语音模型",+ "settings.speech.modelsHelp": "两个版本的音色完全相同,只是精度不同;精简版体积只有三分之一,音质几乎听不出差别。所选版本即“文字转语音”使用的模型。",+ "settings.speech.privacyNote": "语音模型只需下载一次,保存在本机。生成语音时完全不会联网。",+ "settings.speech.unpacking": "解压中...",+ "settings.speech.useModel": "使用 {model}",+ "settings.speech.useModelHint": "使用此模型","settings.tabs.about": "关于","settings.tabs.general": "通用",+ "settings.tabs.speech": "语音","settings.tabs.transcriber": "转录器","settings.title": "设置","settings.transcriber.cancelDownload": "取消下载",@@ -470,6 +483,7 @@"titleBar.switchLight": "切换到浅色","titleBar.switchLightAria": "切换到浅色主题","toast.effectNeedsClip": "请先在时间线上选择一个视频或图像片段",+ "toast.narrationAdded": "旁白已添加到播放头处","toast.projectDetailsSaved": "项目详情已保存","toast.projectSaved": "项目已保存","toast.saveFailed": "保存失败:{message}",@@ -492,5 +506,25 @@"transitions.wipe-right.blurb": "入场片段从左边缘扫入。","transitions.wipe-right.label": "向右划像","transitions.zoom.blurb": "在剪切点上急推放大,随后回稳。",- "transitions.zoom.label": "缩放"+ "transitions.zoom.label": "缩放",+ "tts.accent.american": "美式英语",+ "tts.accent.british": "英式英语",+ "tts.accent.chinese": "中文",+ "tts.downloadModel": "下载语音模型({size})",+ "tts.downloading": "下载中...",+ "tts.gender.female": "女声",+ "tts.gender.male": "男声",+ "tts.generate": "生成语音",+ "tts.generating": "生成中...",+ "tts.importFailed": "生成的音频无法添加到项目",+ "tts.modelNeeded": "语音由 Kokoro 模型完全在本机生成。模型只需下载一次;此后你输入的文字不会离开这台电脑。",+ "tts.pace.faster": "较快",+ "tts.pace.natural": "自然",+ "tts.pace.slower": "较慢",+ "tts.paceLabel": "语速",+ "tts.textLabel": "文本",+ "tts.textPlaceholder": "输入要朗读的旁白...",+ "tts.title": "文字转语音",+ "tts.unpacking": "解压中...",+ "tts.voiceLabel": "声音"}