rust-tts-wrapper 0.1.0

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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! # rust-tts-wrapper
//!
//! Cross-platform TTS (Text-to-Speech) wrapper with a C ABI.
//! Mirrors [`js-tts-wrapper`] and `SwiftTTSWrapper`, supporting 21 engines:
//! system (speech-dispatcher), Sherpa-ONNX (191 local models), and 19 cloud providers.
//!
//! [`js-tts-wrapper`]: https://github.com/AACTools/js-tts-wrapper
//!
//! ## Quick start (C)
//!
//! ```c
//! tts_ctx* ctx = tts_create("system", NULL);
//! tts_speak(ctx, "Hello world");
//! tts_destroy(ctx);
//! ```

#![allow(
    clippy::missing_panics_doc,
    clippy::not_unsafe_ptr_arg_deref,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::ptr_as_ptr,
    clippy::cast_ptr_alignment,
    clippy::doc_markdown,
    clippy::multiple_crate_versions,
    clippy::field_reassign_with_default,
    non_camel_case_types,
    dead_code
)]

#[cfg(feature = "cloud")]
mod cloud_engine;
pub mod engine;
pub mod factory;
#[cfg(feature = "sherpaonnx")]
mod sherpaonnx_engine;
#[cfg(feature = "system")]
mod system_engine;
pub mod types;

use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::ptr;
use std::sync::Mutex;

use engine::TtsEngine;
use factory::create_engine;

type BoxedEngine = Box<dyn TtsEngine>;

/// Opaque context holding an engine instance and its per-instance settings.
pub type CAudioCb = Option<extern "C" fn(*const u8, usize, *mut std::ffi::c_void)>;
pub type CBoundaryCb = Option<extern "C" fn(*const c_char, f32, f32, *mut std::ffi::c_void)>;
type BoxedAudioCb = Box<dyn FnMut(&[u8])>;
type BoxedBoundaryCb = Box<dyn FnMut(&str, f32, f32)>;

pub struct tts_ctx {
    engine: Mutex<BoxedEngine>,
    voice_id: Mutex<Option<String>>,
    rate: Mutex<f32>,
    pitch: Mutex<f32>,
    volume: Mutex<f32>,
    last_error: Mutex<String>,
    on_audio: Mutex<CAudioCb>,
    on_audio_userdata: Mutex<*mut std::ffi::c_void>,
    on_boundary: Mutex<CBoundaryCb>,
    on_boundary_userdata: Mutex<*mut std::ffi::c_void>,
}

static LAST_ERROR: Mutex<Option<CString>> = Mutex::new(None);

fn set_error(msg: &str) {
    if let Ok(mut guard) = LAST_ERROR.lock() {
        *guard = Some(CString::new(msg).unwrap_or_else(|_| CString::new("error").unwrap()));
    }
}

/// Create a new TTS engine instance.
///
/// Returns an opaque context pointer on success, or null on failure.
/// Call [`tts_get_last_error`] to retrieve the error message on failure.
///
/// # Safety
///
/// `engine_id` must be a valid null-terminated C string.
/// `credentials_json` may be null or a valid null-terminated JSON string.
#[no_mangle]
pub extern "C" fn tts_create(
    engine_id: *const c_char,
    credentials_json: *const c_char,
) -> *mut tts_ctx {
    if engine_id.is_null() {
        set_error("engine_id is null");
        return ptr::null_mut();
    }
    let engine_id_str = unsafe { CStr::from_ptr(engine_id) }
        .to_string_lossy()
        .into_owned();
    let creds = if credentials_json.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(credentials_json) }
            .to_string_lossy()
            .into_owned()
    };

    if let Some(engine) = create_engine(&engine_id_str, &creds) {
        let ctx = Box::new(tts_ctx {
            engine: Mutex::new(engine),
            voice_id: Mutex::new(None),
            rate: Mutex::new(1.0),
            pitch: Mutex::new(1.0),
            volume: Mutex::new(1.0),
            last_error: Mutex::new(String::new()),
            on_audio: Mutex::new(None),
            on_audio_userdata: Mutex::new(ptr::null_mut()),
            on_boundary: Mutex::new(None),
            on_boundary_userdata: Mutex::new(ptr::null_mut()),
        });
        Box::into_raw(ctx)
    } else {
        set_error(&format!("Unknown engine: {engine_id_str}"));
        ptr::null_mut()
    }
}

/// Destroy a TTS context and free all associated resources.
///
/// # Safety
///
/// `ctx` must be a pointer previously returned by [`tts_create`],
/// or null (no-op).
#[no_mangle]
pub extern "C" fn tts_destroy(ctx: *mut tts_ctx) {
    if !ctx.is_null() {
        unsafe {
            drop(Box::from_raw(ctx));
        }
    }
}

/// Speak `text` asynchronously using the engine in `ctx`.
///
/// Returns 0 on success, -1 on failure.
///
/// # Safety
///
/// `ctx` must be a valid pointer from [`tts_create`].
/// `text` must be a valid null-terminated C string.
#[no_mangle]
pub extern "C" fn tts_speak(ctx: *mut tts_ctx, text: *const c_char) -> i32 {
    if ctx.is_null() || text.is_null() {
        return -1;
    }
    let ctx_ref = unsafe { &*ctx };
    let text_str = unsafe { CStr::from_ptr(text) }
        .to_string_lossy()
        .into_owned();
    let voice = ctx_ref.voice_id.lock().unwrap().clone();
    let rate = *ctx_ref.rate.lock().unwrap();
    let pitch = *ctx_ref.pitch.lock().unwrap();
    let volume = *ctx_ref.volume.lock().unwrap();

    let audio_cb = *ctx_ref.on_audio.lock().unwrap();
    let audio_userdata = *ctx_ref.on_audio_userdata.lock().unwrap();
    let boundary_cb = *ctx_ref.on_boundary.lock().unwrap();
    let boundary_userdata = *ctx_ref.on_boundary_userdata.lock().unwrap();

    let mut on_audio_closure: Option<BoxedAudioCb> = match audio_cb {
        Some(cb) => Some(Box::new(move |bytes: &[u8]| {
            cb(bytes.as_ptr(), bytes.len(), audio_userdata);
        })),
        None => None,
    };

    let mut on_boundary_closure: Option<BoxedBoundaryCb> = match boundary_cb {
        Some(cb) => Some(Box::new(move |word: &str, start: f32, end: f32| {
            if let Ok(c_word) = CString::new(word) {
                cb(c_word.as_ptr(), start, end, boundary_userdata);
            }
        })),
        None => None,
    };

    let engine = ctx_ref.engine.lock().unwrap();
    match engine.speak(
        &text_str,
        voice.as_deref(),
        rate,
        pitch,
        volume,
        on_audio_closure
            .as_mut()
            .map(|f| &mut **f as &mut dyn FnMut(&[u8])),
        on_boundary_closure
            .as_mut()
            .map(|f| &mut **f as &mut dyn FnMut(&str, f32, f32)),
    ) {
        Ok(()) => 0,
        Err(e) => {
            *ctx_ref.last_error.lock().unwrap() = e.to_string();
            -1
        }
    }
}

/// Speak `text` synchronously (blocks until complete).
///
/// Returns 0 on success, -1 on failure.
///
/// # Safety
///
/// `ctx` must be a valid pointer from [`tts_create`].
/// `text` must be a valid null-terminated C string.
#[no_mangle]
pub extern "C" fn tts_speak_sync(ctx: *mut tts_ctx, text: *const c_char) -> i32 {
    if ctx.is_null() || text.is_null() {
        return -1;
    }
    let ctx_ref = unsafe { &*ctx };
    let text_str = unsafe { CStr::from_ptr(text) }
        .to_string_lossy()
        .into_owned();
    let voice = ctx_ref.voice_id.lock().unwrap().clone();
    let rate = *ctx_ref.rate.lock().unwrap();
    let pitch = *ctx_ref.pitch.lock().unwrap();
    let volume = *ctx_ref.volume.lock().unwrap();

    let audio_cb = *ctx_ref.on_audio.lock().unwrap();
    let audio_userdata = *ctx_ref.on_audio_userdata.lock().unwrap();
    let boundary_cb = *ctx_ref.on_boundary.lock().unwrap();
    let boundary_userdata = *ctx_ref.on_boundary_userdata.lock().unwrap();

    let mut on_audio_closure: Option<BoxedAudioCb> = match audio_cb {
        Some(cb) => Some(Box::new(move |bytes: &[u8]| {
            cb(bytes.as_ptr(), bytes.len(), audio_userdata);
        })),
        None => None,
    };

    let mut on_boundary_closure: Option<BoxedBoundaryCb> = match boundary_cb {
        Some(cb) => Some(Box::new(move |word: &str, start: f32, end: f32| {
            if let Ok(c_word) = CString::new(word) {
                cb(c_word.as_ptr(), start, end, boundary_userdata);
            }
        })),
        None => None,
    };

    let engine = ctx_ref.engine.lock().unwrap();
    match engine.speak_sync(
        &text_str,
        voice.as_deref(),
        rate,
        pitch,
        volume,
        on_audio_closure
            .as_mut()
            .map(|f| &mut **f as &mut dyn FnMut(&[u8])),
        on_boundary_closure
            .as_mut()
            .map(|f| &mut **f as &mut dyn FnMut(&str, f32, f32)),
    ) {
        Ok(()) => 0,
        Err(e) => {
            *ctx_ref.last_error.lock().unwrap() = e.to_string();
            -1
        }
    }
}

/// Stop any in-progress speech.
///
/// # Safety
///
/// `ctx` must be a valid pointer from [`tts_create`].
#[no_mangle]
pub extern "C" fn tts_stop(ctx: *mut tts_ctx) {
    if ctx.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    let engine = ctx_ref.engine.lock().unwrap();
    let _ = engine.stop();
}

/// Retrieve the list of available voices for the engine.
///
/// On success, writes a heap-allocated array to `*out_voices` and its length
/// to `*out_count`. Caller must free with [`tts_free_voices`].
///
/// Returns 0 on success, -1 on failure.
///
/// # Safety
///
/// `ctx` must be valid. `out_voices` and `out_count` must be non-null.
#[no_mangle]
pub extern "C" fn tts_get_voices(
    ctx: *mut tts_ctx,
    out_voices: *mut *mut types::tts_voice,
    out_count: *mut i32,
) -> i32 {
    if ctx.is_null() || out_voices.is_null() || out_count.is_null() {
        return -1;
    }
    let ctx_ref = unsafe { &*ctx };
    let engine = ctx_ref.engine.lock().unwrap();
    match engine.get_voices() {
        Ok(voices) => {
            let len = voices.len();
            if len == 0 {
                unsafe {
                    *out_voices = ptr::null_mut();
                    *out_count = 0;
                }
                return 0;
            }
            let layout = std::alloc::Layout::array::<types::tts_voice>(len).unwrap();
            let arr_ptr = unsafe { std::alloc::alloc(layout).cast::<types::tts_voice>() };
            for (i, v) in voices.iter().enumerate() {
                unsafe {
                    let entry = arr_ptr.add(i);
                    std::ptr::write(
                        entry,
                        types::tts_voice {
                            id: CString::new(v.id.clone()).unwrap().into_raw(),
                            name: CString::new(v.name.clone()).unwrap().into_raw(),
                            language: CString::new(v.primary_language().to_string())
                                .unwrap()
                                .into_raw(),
                            gender: CString::new(v.gender.to_string()).unwrap().into_raw(),
                            engine: CString::new(v.provider.clone()).unwrap().into_raw(),
                        },
                    );
                }
            }
            unsafe {
                *out_voices = arr_ptr;
                *out_count = len as i32;
            }
            0
        }
        Err(e) => {
            *ctx_ref.last_error.lock().unwrap() = e.to_string();
            -1
        }
    }
}

/// Free a voice array previously returned by [`tts_get_voices`].
///
/// # Safety
///
/// `voices` must be a pointer from `tts_get_voices` with the matching `count`.
#[no_mangle]
pub extern "C" fn tts_free_voices(voices: *mut types::tts_voice, count: i32) {
    if voices.is_null() || count <= 0 {
        return;
    }
    for i in 0..count {
        unsafe {
            let v = voices.add(i as usize);
            if !(*v).id.is_null() {
                let _ = CString::from_raw((*v).id);
            }
            if !(*v).name.is_null() {
                let _ = CString::from_raw((*v).name);
            }
            if !(*v).language.is_null() {
                let _ = CString::from_raw((*v).language);
            }
            if !(*v).gender.is_null() {
                let _ = CString::from_raw((*v).gender);
            }
            if !(*v).engine.is_null() {
                let _ = CString::from_raw((*v).engine);
            }
        }
    }
    let layout = std::alloc::Layout::array::<types::tts_voice>(count as usize).unwrap();
    unsafe {
        std::alloc::dealloc(voices.cast::<u8>(), layout);
    }
}

/// Set the voice for subsequent speak calls.
///
/// # Safety
///
/// `ctx` must be valid. `voice_id` must be a valid null-terminated C string.
#[no_mangle]
pub extern "C" fn tts_set_voice(ctx: *mut tts_ctx, voice_id: *const c_char) {
    if ctx.is_null() || voice_id.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    let id = unsafe { CStr::from_ptr(voice_id) }
        .to_string_lossy()
        .into_owned();
    *ctx_ref.voice_id.lock().unwrap() = Some(id);
}

/// Set the speech rate (1.0 = normal).
///
/// # Safety
///
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_set_rate(ctx: *mut tts_ctx, rate: f32) {
    if ctx.is_null() {
        return;
    }
    *unsafe { &*ctx }.rate.lock().unwrap() = rate;
}

/// Set the speech pitch (1.0 = normal).
///
/// # Safety
///
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_set_pitch(ctx: *mut tts_ctx, pitch: f32) {
    if ctx.is_null() {
        return;
    }
    *unsafe { &*ctx }.pitch.lock().unwrap() = pitch;
}

/// Set the speech volume (1.0 = normal).
///
/// # Safety
///
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_set_volume(ctx: *mut tts_ctx, volume: f32) {
    if ctx.is_null() {
        return;
    }
    *unsafe { &*ctx }.volume.lock().unwrap() = volume;
}

/// Set the callback for streaming audio chunks.
///
/// # Safety
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_set_on_audio(
    ctx: *mut tts_ctx,
    cb: CAudioCb,
    userdata: *mut std::ffi::c_void,
) {
    if ctx.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    *ctx_ref.on_audio.lock().unwrap() = cb;
    *ctx_ref.on_audio_userdata.lock().unwrap() = userdata;
}

/// Set the callback for word boundary events.
///
/// # Safety
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_set_on_boundary(
    ctx: *mut tts_ctx,
    cb: CBoundaryCb,
    userdata: *mut std::ffi::c_void,
) {
    if ctx.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    *ctx_ref.on_boundary.lock().unwrap() = cb;
    *ctx_ref.on_boundary_userdata.lock().unwrap() = userdata;
}

/// Return the number of registered engines.
#[no_mangle]
pub extern "C" fn tts_get_engine_count() -> i32 {
    factory::engine_count() as i32
}

/// Write engine descriptors into a caller-allocated array.
///
/// `out_engines` must point to at least [`tts_get_engine_count`] entries.
/// Caller must free each entry's strings and the array with [`tts_free_engine_info`].
///
/// # Safety
///
/// `out_engines` must be non-null and point to enough space.
#[no_mangle]
pub extern "C" fn tts_get_engines(out_engines: *mut types::tts_engine_info) {
    if out_engines.is_null() {
        return;
    }
    let engines = factory::engine_list();
    for (i, e) in engines.iter().enumerate() {
        unsafe {
            let entry = out_engines.add(i);
            std::ptr::write(
                entry,
                types::tts_engine_info {
                    id: CString::new(e.id.clone()).unwrap().into_raw(),
                    name: CString::new(e.name.clone()).unwrap().into_raw(),
                    needs_credentials: e.needs_credentials,
                    credential_keys_json: CString::new(e.credential_keys_json.clone())
                        .unwrap()
                        .into_raw(),
                },
            );
        }
    }
}

/// Free an engine info array previously returned by [`tts_get_engines`].
///
/// # Safety
///
/// `engines` must be a pointer from `tts_get_engines` with the matching `count`.
#[no_mangle]
pub extern "C" fn tts_free_engine_info(engines: *mut types::tts_engine_info, count: i32) {
    if engines.is_null() || count <= 0 {
        return;
    }
    for i in 0..count {
        unsafe {
            let e = engines.add(i as usize);
            if !(*e).id.is_null() {
                let _ = CString::from_raw((*e).id);
            }
            if !(*e).name.is_null() {
                let _ = CString::from_raw((*e).name);
            }
            if !(*e).credential_keys_json.is_null() {
                let _ = CString::from_raw((*e).credential_keys_json);
            }
        }
    }
    let layout = std::alloc::Layout::array::<types::tts_engine_info>(count as usize).unwrap();
    unsafe {
        std::alloc::dealloc(engines.cast::<u8>(), layout);
    }
}

/// Return the last error message as a C string, or null if none.
///
/// The returned pointer is valid until the next call to any TTS function.
#[no_mangle]
pub extern "C" fn tts_get_last_error() -> *const c_char {
    match LAST_ERROR.lock() {
        Ok(guard) => match guard.as_ref() {
            Some(cs) => cs.as_ptr(),
            None => ptr::null(),
        },
        Err(_) => ptr::null(),
    }
}

/// Pause in-progress speech.
///
/// # Safety
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_pause(ctx: *mut tts_ctx) {
    if ctx.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    let engine = ctx_ref.engine.lock().unwrap();
    let _ = engine.pause();
}

/// Resume paused speech.
///
/// # Safety
/// `ctx` must be valid.
#[no_mangle]
pub extern "C" fn tts_resume(ctx: *mut tts_ctx) {
    if ctx.is_null() {
        return;
    }
    let ctx_ref = unsafe { &*ctx };
    let engine = ctx_ref.engine.lock().unwrap();
    let _ = engine.resume();
}

/// Synthesize text to audio bytes without playback.
/// Writes a heap-allocated buffer to `*out_bytes` and its length to `*out_len`.
/// Caller must free with [`tts_free_bytes`].
/// Returns 0 on success, -1 on failure.
///
/// # Safety
/// `ctx` must be valid. `out_bytes` and `out_len` must be non-null.
#[no_mangle]
pub extern "C" fn tts_synth_to_bytes(
    ctx: *mut tts_ctx,
    text: *const c_char,
    out_bytes: *mut *mut u8,
    out_len: *mut usize,
) -> i32 {
    if ctx.is_null() || text.is_null() || out_bytes.is_null() || out_len.is_null() {
        return -1;
    }
    let ctx_ref = unsafe { &*ctx };
    let text_str = unsafe { CStr::from_ptr(text) }
        .to_string_lossy()
        .into_owned();
    let voice = ctx_ref.voice_id.lock().unwrap().clone();
    let rate = *ctx_ref.rate.lock().unwrap();
    let pitch = *ctx_ref.pitch.lock().unwrap();
    let volume = *ctx_ref.volume.lock().unwrap();

    let engine = ctx_ref.engine.lock().unwrap();
    match engine.synth_to_bytes(&text_str, voice.as_deref(), rate, pitch, volume) {
        Ok(data) => {
            if data.is_empty() {
                unsafe {
                    *out_bytes = ptr::null_mut();
                    *out_len = 0;
                }
                return 0;
            }
            let len = data.len();
            let layout = std::alloc::Layout::array::<u8>(len).unwrap();
            let ptr = unsafe { std::alloc::alloc(layout) };
            unsafe {
                ptr::copy_nonoverlapping(data.as_ptr(), ptr, len);
                *out_bytes = ptr;
                *out_len = len;
            }
            0
        }
        Err(e) => {
            *ctx_ref.last_error.lock().unwrap() = e.to_string();
            -1
        }
    }
}

/// Free a byte buffer returned by [`tts_synth_to_bytes`].
///
/// # Safety
/// `bytes` must be from `tts_synth_to_bytes` with the matching `len`.
#[no_mangle]
pub extern "C" fn tts_free_bytes(bytes: *mut u8, len: usize) {
    if bytes.is_null() || len == 0 {
        return;
    }
    let layout = std::alloc::Layout::array::<u8>(len).unwrap();
    unsafe {
        std::alloc::dealloc(bytes, layout);
    }
}