rust-tts-wrapper 1.6.1

Cross-platform TTS wrapper with C API — mirrors js-tts-wrapper / SwiftTTSWrapper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Engine factory: create engines by ID and list all registered engines.

use crate::engine::TtsEngine;
use crate::types::EngineDescriptor;
use std::sync::Arc;

/// Parse engine credentials JSON into a string map, coercing JSON scalars
/// (numbers, bools) to their string form. Fixes #58: a single
/// `{"numSteps": 16}` (JSON number) no longer silently empties ALL
/// credentials — it coerces to `"16"` like the engine code expects.
#[must_use]
pub fn parse_credentials(credentials_json: &str) -> std::collections::HashMap<String, String> {
    if credentials_json.is_empty() {
        return std::collections::HashMap::new();
    }
    let parsed: std::collections::HashMap<String, serde_json::Value> =
        match serde_json::from_str(credentials_json) {
            Ok(v) => v,
            Err(e) => {
                eprintln!(
                    "factory: credentials JSON is malformed ({e}) — \
                     engine will start with no credentials"
                );
                return std::collections::HashMap::new();
            }
        };
    parsed
        .into_iter()
        .map(|(k, v)| {
            let s = match v {
                serde_json::Value::String(s) => s,
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                serde_json::Value::Null => String::new(),
                // objects/arrays become their JSON repr (rarely useful,
                // but at least visible in error messages)
                other => other.to_string(),
            };
            (k, s)
        })
        .collect()
}

// The unused-import warning is a false positive — TtsEngine is a trait used as a dyn bound.
#[cfg(all(feature = "avsynth", target_os = "macos"))]
use crate::avsynth_engine::AvSynthEngine;
#[cfg(feature = "cloud")]
use crate::cloud_engine;
#[cfg(feature = "qwen3-local")]
use crate::qwen3_local_engine::Qwen3LocalEngine;
#[cfg(all(feature = "sapi", target_os = "windows"))]
use crate::sapi_engine::SapiEngine;
#[cfg(feature = "sherpaonnx")]
use crate::sherpaonnx_engine::SherpaOnnxEngine;
#[cfg(all(feature = "system", target_os = "linux"))]
use crate::system_engine::SystemEngine;

/// Create an engine by its string identifier.
///
/// `credentials_json` is a JSON object with engine-specific credentials
/// (e.g. `{"apiKey": "..."}`). Pass `""` for engines that don't need credentials.
#[must_use]
#[allow(unused_variables)]
#[allow(clippy::too_many_lines)]
pub fn create_engine(engine_id: &str, credentials_json: &str) -> Option<Arc<dyn TtsEngine>> {
    // Detect engines that exist in the full catalogue but were compiled out
    // by disabled features, so callers get a useful error rather than a
    // generic "unknown engine". Only emit these messages when the
    // caller actually asked for one of the gated engines.
    match engine_id {
        "system" => {
            #[cfg(all(feature = "system", target_os = "linux"))]
            {
                return Some(Arc::new(SystemEngine::new()));
            }
            #[cfg(not(all(feature = "system", target_os = "linux")))]
            {
                eprintln!(
                    "Engine 'system' requires the 'system' feature on Linux. \
                     Current build does not satisfy these conditions."
                );
                return None;
            }
        }
        "avsynth" => {
            #[cfg(all(feature = "avsynth", target_os = "macos"))]
            {
                return Some(Arc::new(AvSynthEngine::new()));
            }
            #[cfg(not(all(feature = "avsynth", target_os = "macos")))]
            {
                eprintln!(
                    "Engine 'avsynth' requires the 'avsynth' feature and macOS. \
                     Current build does not satisfy these conditions."
                );
                return None;
            }
        }
        "sapi" => {
            #[cfg(all(feature = "sapi", target_os = "windows"))]
            {
                return Some(Arc::new(SapiEngine::new()));
            }
            #[cfg(not(all(feature = "sapi", target_os = "windows")))]
            {
                eprintln!(
                    "Engine 'sapi' requires the 'sapi' feature and Windows. \
                     Current build does not satisfy these conditions."
                );
                return None;
            }
        }
        "sherpaonnx" => {
            #[cfg(feature = "sherpaonnx")]
            {
                return Some(Arc::new(SherpaOnnxEngine::new(credentials_json)));
            }
            #[cfg(not(feature = "sherpaonnx"))]
            {
                eprintln!(
                    "Engine 'sherpaonnx' is not enabled in this build. \
                     Rebuild with --features sherpaonnx."
                );
                return None;
            }
        }
        "qwen3-local" => {
            #[cfg(feature = "qwen3-local")]
            {
                let creds = parse_credentials(credentials_json);
                return match Qwen3LocalEngine::new(&creds) {
                    Ok(engine) => Some(Arc::new(engine)),
                    Err(e) => {
                        eprintln!("Engine 'qwen3-local' failed to load: {e}");
                        None
                    }
                };
            }
            #[cfg(not(feature = "qwen3-local"))]
            {
                eprintln!(
                    "Engine 'qwen3-local' is not enabled in this build. \
                     Rebuild with --features qwen3-local."
                );
                return None;
            }
        }
        "omnivoice-local" => {
            #[cfg(feature = "omnivoice-local")]
            {
                use crate::omnivoice_local_engine::{OmniVoiceLocalEngine, OmniVoiceLocalParams};
                let creds = parse_credentials(credentials_json);
                let params = OmniVoiceLocalParams {
                    model_path: creds.get("modelPath").cloned().unwrap_or_default(),
                    codec_path: creds.get("codecPath").cloned().unwrap_or_default(),
                    num_steps: creds
                        .get("numSteps")
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(32),
                    seed: creds.get("seed").and_then(|s| s.parse().ok()).unwrap_or(42),
                    instruct: creds.get("instruct").cloned(),
                    language: creds.get("language").cloned().unwrap_or_default(),
                    ..Default::default()
                };
                return match OmniVoiceLocalEngine::new(params) {
                    Ok(engine) => Some(Arc::new(engine)),
                    Err(e) => {
                        eprintln!("Engine 'omnivoice-local' failed to load: {e}");
                        None
                    }
                };
            }
            #[cfg(not(feature = "omnivoice-local"))]
            {
                eprintln!(
                    "Engine 'omnivoice-local' is not enabled in this build. \
                     Rebuild with --features omnivoice-local."
                );
                return None;
            }
        }
        "floravox" => {
            #[cfg(feature = "floravox")]
            {
                return Some(Arc::new(crate::floravox_engine::FloravoxEngine::new(
                    credentials_json,
                )));
            }
            #[cfg(not(feature = "floravox"))]
            {
                eprintln!(
                    "Engine 'floravox' is not enabled in this build. \
                     Rebuild with --features floravox."
                );
                return None;
            }
        }
        _ => {}
    }

    // Cloud catch-all. If the cloud feature is on we delegate; otherwise the
    // engine id is unknown to this build.
    #[cfg(feature = "cloud")]
    {
        let result = cloud_engine::create_cloud_engine(engine_id, credentials_json);
        if result.is_none() {
            eprintln!(
                "Unknown engine '{engine_id}'. Available engines: {}",
                engine_list()
                    .iter()
                    .map(|e| e.id.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        result
    }

    #[cfg(not(feature = "cloud"))]
    {
        eprintln!(
            "Unknown engine '{engine_id}' (cloud feature is disabled; only \
             built-in engines are available). Available engines: {}",
            engine_list()
                .iter()
                .map(|e| e.id.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
        None
    }
}

/// Return the number of registered engines.
#[must_use]
pub fn engine_count() -> usize {
    engine_list().len()
}

/// Return a list of all registered engine descriptors.
#[must_use]
#[allow(clippy::vec_init_then_push)]
#[allow(clippy::too_many_lines)]
pub fn engine_list() -> Vec<EngineDescriptor> {
    #[allow(unused_mut)]
    let mut engines = Vec::new();

    #[cfg(all(feature = "system", target_os = "linux"))]
    engines.push(EngineDescriptor {
        id: "system".into(),
        name: "System (Speech Dispatcher)".into(),
        needs_credentials: false,
        credential_keys_json: "[]".into(),
    });

    #[cfg(all(feature = "avsynth", target_os = "macos"))]
    engines.push(EngineDescriptor {
        id: "avsynth".into(),
        name: "macOS AVSpeechSynthesizer".into(),
        needs_credentials: false,
        credential_keys_json: "[]".into(),
    });

    #[cfg(all(feature = "sapi", target_os = "windows"))]
    engines.push(EngineDescriptor {
        id: "sapi".into(),
        name: "Windows SAPI".into(),
        needs_credentials: false,
        credential_keys_json: "[]".into(),
    });

    #[cfg(feature = "sherpaonnx")]
    engines.push(EngineDescriptor {
        id: "sherpaonnx".into(),
        name: "Sherpa-ONNX".into(),
        needs_credentials: false,
        credential_keys_json: "[]".into(),
    });

    #[cfg(feature = "qwen3-local")]
    engines.push(EngineDescriptor {
        id: "qwen3-local".into(),
        name: "Qwen3-TTS local (qwen3-tts.cpp)".into(),
        needs_credentials: true,
        credential_keys_json: r#"["modelsDir","threads","temperature","topK","maxTokens"]"#.into(),
    });

    #[cfg(feature = "floravox")]
    engines.push(EngineDescriptor {
        id: "floravox".into(),
        name: "floravox".into(),
        needs_credentials: true,
        credential_keys_json: r#"["modelsDir","modelId","misaki","chars","speaker"]"#.into(),
    });

    #[cfg(feature = "omnivoice-local")]
    engines.push(EngineDescriptor {
        id: "omnivoice-local".into(),
        name: "OmniVoice local (600+ languages, offline)".into(),
        needs_credentials: true,
        credential_keys_json:
            r#"["modelPath","codecPath","numSteps","seed","instruct","language"]"#.into(),
    });

    #[cfg(feature = "pocket-timing")]
    engines.push(EngineDescriptor {
        id: "pocket".into(),
        name: "Pocket TTS (attention-timed, phoneme-driven)".into(),
        needs_credentials: true,
        credential_keys_json: r#"["bundleDir","reference"]"#.into(),
    });

    #[cfg(feature = "cloud")]
    {
        let cloud = [
            ("openai", "OpenAI", true, r#"["apiKey"]"#),
            (
                "elevenlabs",
                "ElevenLabs",
                true,
                r#"["apiKey","modelId","voiceId","language"]"#,
            ),
            ("azure", "Azure", true, r#"["subscriptionKey","region"]"#),
            ("edge", "Microsoft Edge (Read Aloud)", false, "[]"),
            ("google", "Google Cloud", true, r#"["apiKey"]"#),
            (
                "gemini",
                "Google Gemini (3.8 TTS)",
                true,
                r#"["apiKey","modelId","voice","style"]"#,
            ),
            (
                "qwen",
                "Qwen (Alibaba Cloud Model Studio)",
                true,
                r#"["apiKey","modelId","region","instruction","wsUrl","customizationUrl"]"#,
            ),
            (
                "polly",
                "Amazon Polly",
                true,
                r#"["accessKeyId","secretAccessKey","region"]"#,
            ),
            ("cartesia", "Cartesia", true, r#"["apiKey"]"#),
            ("deepgram", "Deepgram", true, r#"["apiKey"]"#),
            ("playht", "PlayHT", true, r#"["apiKey","userId"]"#),
            ("fishaudio", "Fish Audio", true, r#"["apiKey"]"#),
            ("hume", "Hume AI", true, r#"["apiKey"]"#),
            ("mistral", "Mistral", true, r#"["apiKey"]"#),
            ("murf", "Murf", true, r#"["apiKey"]"#),
            ("resemble", "Resemble AI", true, r#"["apiKey"]"#),
            ("unrealspeech", "Unreal Speech", true, r#"["apiKey"]"#),
            ("upliftai", "UpliftAI", true, r#"["apiKey"]"#),
            (
                "watson",
                "IBM Watson",
                true,
                r#"["apiKey","region","instanceId"]"#,
            ),
            ("witai", "Wit.ai", true, r#"["token"]"#),
            ("xai", "xAI", true, r#"["apiKey"]"#),
            ("modelslab", "ModelsLab", true, r#"["apiKey"]"#),
        ];
        for (id, name, creds, keys) in &cloud {
            engines.push(EngineDescriptor {
                id: (*id).into(),
                name: (*name).into(),
                needs_credentials: *creds,
                credential_keys_json: (*keys).into(),
            });
        }
    }

    engines
}

#[cfg(test)]
mod credentials_tests {
    use super::parse_credentials;

    #[test]
    fn json_numbers_coerce_to_strings() {
        let creds = parse_credentials(r#"{"modelPath":"/m.gguf","numSteps":16,"seed":42}"#);
        assert_eq!(creds.get("modelPath").map(String::as_str), Some("/m.gguf"));
        assert_eq!(creds.get("numSteps").map(String::as_str), Some("16"));
        assert_eq!(creds.get("seed").map(String::as_str), Some("42"));
    }

    #[test]
    fn json_bools_coerce() {
        let creds = parse_credentials(r#"{"verbose":true,"fast":false}"#);
        assert_eq!(creds.get("verbose").map(String::as_str), Some("true"));
        assert_eq!(creds.get("fast").map(String::as_str), Some("false"));
    }

    #[test]
    fn malformed_json_warns_not_silences() {
        let creds = parse_credentials(r#"{"broken": tru}"#);
        assert!(creds.is_empty());
    }

    #[test]
    fn empty_input_is_empty_map() {
        assert!(parse_credentials("").is_empty());
    }

    #[test]
    fn mixed_types_all_coerce() {
        let creds =
            parse_credentials(r#"{"path":"/a/b","count":3,"ratio":0.5,"flag":true,"name":"test"}"#);
        assert_eq!(creds.len(), 5);
        assert_eq!(creds.get("count").map(String::as_str), Some("3"));
        assert_eq!(creds.get("ratio").map(String::as_str), Some("0.5"));
    }
}