audio-cpp 0.2.0

audio.cpp(ggml 音频推理引擎)的高层安全 Rust 封装
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
//! 类型化任务请求([`Request`])构造器。
//!
//! 上层 API 的所有请求入口(离线 [`crate::Session::run_offline`]、流式
//! [`crate::Session::start`] / [`crate::Session::prepare`])都接受
//! [`IntoRequest`]:既可以是本模块的类型化 [`Request`] 枚举,也可以是任意
//! JSON 字符串(透传给 C 边界)。用 [`Request`] 构造时无需手工拼接 / 转义
//! JSON,Windows 路径也无需手动转义反斜杠。
//!
//! 每个任务一种变体,携带各自参数:
//! ```rust
//! use audio_cpp::Request;
//!
//! // 离线 VAD:音频 + 阈值选项
//! let r1 = Request::vad("./speech.wav").option("vad_threshold", 0.5);
//! // 离线 / 流式 ASR
//! let r2 = Request::asr("./speech.wav");
//! let r3 = Request::asr("./speech.wav").option("audio_chunk_seconds", 3.0);
//! // TTS:文本(可选说话人参考,如 Qwen3 TTS 声音克隆)
//! let r4 = Request::tts("Hello!");
//! let r5 = Request::tts("Hello!").reference("./ref.wav").reference_text("参考文本");
//! // 原始 JSON 透传
//! let r6 = Request::json(r#"{"audio_path":"./speech.wav"}"#);
//! ```

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde_json::Value;

use crate::audio::WavAudio;
use crate::error::Error;

/// 请求里的音频输入:本地文件路径,或内嵌采样数据。
#[derive(Debug, Clone)]
pub enum AudioInput {
    /// 从本地 WAV 文件读取(等价于 JSON 顶层 `audio_path`)。
    Path(String),
    /// 内嵌音频数据(等价于 JSON 顶层 `audio` 对象)。
    Buffer(WavAudio),
}

impl From<&str> for AudioInput {
    fn from(s: &str) -> Self {
        AudioInput::Path(s.to_owned())
    }
}

impl From<String> for AudioInput {
    fn from(s: String) -> Self {
        AudioInput::Path(s)
    }
}

impl From<&String> for AudioInput {
    fn from(s: &String) -> Self {
        AudioInput::Path(s.clone())
    }
}

impl From<WavAudio> for AudioInput {
    fn from(a: WavAudio) -> Self {
        AudioInput::Buffer(a)
    }
}

impl From<&Path> for AudioInput {
    fn from(p: &Path) -> Self {
        AudioInput::Path(p.to_string_lossy().into_owned())
    }
}

impl From<PathBuf> for AudioInput {
    fn from(p: PathBuf) -> Self {
        AudioInput::Path(p.to_string_lossy().into_owned())
    }
}

/// 音频类任务(VAD / ASR / 说话人分离 / 源分离)的请求参数。
#[derive(Debug, Clone, Default)]
pub struct AudioRequest {
    /// 音频输入(文件路径或内嵌数据)。
    pub audio: Option<AudioInput>,
    /// 附加选项键值(如 VAD 的 `vad_threshold` / `threshold`、流式 ASR 的
    /// `audio_chunk_seconds`)。非字符串值由 shim 字符串化后交给上游。
    pub options: BTreeMap<String, Value>,
}

impl AudioRequest {
    /// 以音频输入构造请求。
    pub fn new(audio: impl Into<AudioInput>) -> Self {
        Self {
            audio: Some(audio.into()),
            options: BTreeMap::new(),
        }
    }

    /// 设置一个选项键值(等价于 JSON `options` 里的一个字段)。
    pub fn option<V: Into<Value>>(mut self, key: impl Into<String>, value: V) -> Self {
        self.options.insert(key.into(), value.into());
        self
    }

    /// 批量设置选项。
    pub fn options<K, V>(mut self, opts: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<Value>,
    {
        self.options
            .extend(opts.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }
}

/// 语音合成(TTS)的请求参数。
#[derive(Debug, Clone)]
pub struct TtsRequest {
    /// 待合成文本。
    pub text: String,
    /// 文本语言(可选)。
    pub language: Option<String>,
    /// 说话人参考音频(声音克隆,如 Qwen3 TTS base 变体)。
    pub reference_audio: Option<AudioInput>,
    /// 参考音频的文本转写(经 `options.reference_text` 交给上游)。
    pub reference_text: Option<String>,
    /// 附加选项键值(如流式 TTS 的 `retry_badcase`)。
    pub options: BTreeMap<String, Value>,
}

impl TtsRequest {
    /// 以待合成文本构造请求。
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            language: None,
            reference_audio: None,
            reference_text: None,
            options: BTreeMap::new(),
        }
    }

    /// 设置文本语言。
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// 设置说话人参考音频(声音克隆)。
    pub fn reference(mut self, audio: impl Into<AudioInput>) -> Self {
        self.reference_audio = Some(audio.into());
        self
    }

    /// 设置参考音频的文本转写。
    pub fn reference_text(mut self, text: impl Into<String>) -> Self {
        self.reference_text = Some(text.into());
        self
    }

    /// 设置一个选项键值(等价于 JSON `options` 里的一个字段)。
    pub fn option<V: Into<Value>>(mut self, key: impl Into<String>, value: V) -> Self {
        self.options.insert(key.into(), value.into());
        self
    }

    /// 批量设置选项。
    pub fn options<K, V>(mut self, opts: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<Value>,
    {
        self.options
            .extend(opts.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }
}

/// 一次任务请求。
///
/// 对应 capi.cpp `parse_task_request` 读取的顶层 JSON 字段(`text` /
/// `language` / `audio` / `audio_path` / `options`)。按任务种类区分变体,
/// 每个变体携带自己的参数;序列化时统一展开为上述 JSON 形状。
#[derive(Debug, Clone)]
pub enum Request {
    /// 语音活动检测:需音频输入,可配 `vad_threshold` / `threshold` 等。
    Vad(AudioRequest),
    /// 语音识别:需音频输入,流式时用 `audio_chunk_seconds` 控制窗口。
    Asr(AudioRequest),
    /// 说话人分离:需音频输入。
    Diar(AudioRequest),
    /// 音乐源分离(Demucs 等):需音频输入。
    SourceSeparation(AudioRequest),
    /// 语音合成:需文本,可带说话人参考音频(声音克隆)。
    Tts(TtsRequest),
    /// 原始 JSON 字符串透传(不经任何序列化改动)。
    Json(String),
}

impl Request {
    /// VAD 请求:以音频输入构造。
    pub fn vad(audio: impl Into<AudioInput>) -> Self {
        Request::Vad(AudioRequest::new(audio))
    }

    /// ASR 请求:以音频输入构造。
    pub fn asr(audio: impl Into<AudioInput>) -> Self {
        Request::Asr(AudioRequest::new(audio))
    }

    /// 说话人分离请求:以音频输入构造。
    pub fn diar(audio: impl Into<AudioInput>) -> Self {
        Request::Diar(AudioRequest::new(audio))
    }

    /// 音乐源分离请求:以音频输入构造。
    pub fn source_separation(audio: impl Into<AudioInput>) -> Self {
        Request::SourceSeparation(AudioRequest::new(audio))
    }

    /// TTS 请求:以待合成文本构造。
    pub fn tts(text: impl Into<String>) -> Self {
        Request::Tts(TtsRequest::new(text))
    }

    /// 原始 JSON 字符串透传(不经序列化改动,直接交给 C 边界)。
    pub fn json(s: impl Into<String>) -> Self {
        Request::Json(s.into())
    }

    /// 设置一个选项键值(等价于 JSON `options` 里的一个字段)。
    ///
    /// 对 [`Request::Json`] 无效(原始 JSON 不经序列化改动)。
    pub fn option<V: Into<Value>>(self, key: impl Into<String>, value: V) -> Self {
        let key = key.into();
        let value = value.into();
        match self {
            Request::Vad(r) => Request::Vad(r.option(key, value)),
            Request::Asr(r) => Request::Asr(r.option(key, value)),
            Request::Diar(r) => Request::Diar(r.option(key, value)),
            Request::SourceSeparation(r) => Request::SourceSeparation(r.option(key, value)),
            Request::Tts(r) => Request::Tts(r.option(key, value)),
            Request::Json(_) => self,
        }
    }

    /// 批量设置选项。对 [`Request::Json`] 无效。
    pub fn options<K, V>(self, opts: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<Value>,
    {
        let opts: Vec<(String, Value)> = opts
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        match self {
            Request::Vad(r) => Request::Vad(r.options(opts)),
            Request::Asr(r) => Request::Asr(r.options(opts)),
            Request::Diar(r) => Request::Diar(r.options(opts)),
            Request::SourceSeparation(r) => Request::SourceSeparation(r.options(opts)),
            Request::Tts(r) => Request::Tts(r.options(opts)),
            Request::Json(_) => self,
        }
    }

    /// 设置说话人参考音频(仅对 [`Request::Tts`] 有意义,其余变体忽略)。
    pub fn reference(self, audio: impl Into<AudioInput>) -> Self {
        match self {
            Request::Tts(r) => Request::Tts(r.reference(audio)),
            other => other,
        }
    }

    /// 设置参考音频的文本转写(仅对 [`Request::Tts`] 有意义,其余变体忽略)。
    pub fn reference_text(self, text: impl Into<String>) -> Self {
        match self {
            Request::Tts(r) => Request::Tts(r.reference_text(text)),
            other => other,
        }
    }

    /// 设置文本语言(仅对 [`Request::Tts`] 有意义,其余变体忽略)。
    pub fn language(self, language: impl Into<String>) -> Self {
        match self {
            Request::Tts(r) => Request::Tts(r.language(language)),
            other => other,
        }
    }

    /// 序列化为 JSON 字符串(传给底层 C ABI)。[`Request::Json`] 原样返回。
    ///
    /// # Errors
    ///
    /// 当内部对象无法序列化为合法 JSON 时返回 [`Error::Json`]。
    pub fn to_json(&self) -> Result<String, Error> {
        let mut obj = serde_json::Map::new();
        match self {
            Request::Json(s) => return Ok(s.clone()),
            Request::Vad(r) | Request::Asr(r) | Request::Diar(r) | Request::SourceSeparation(r) => {
                if let Some(audio) = &r.audio {
                    write_audio(&mut obj, audio);
                }
                if !r.options.is_empty() {
                    obj.insert(
                        "options".into(),
                        Value::Object(r.options.clone().into_iter().collect()),
                    );
                }
            }
            Request::Tts(r) => {
                obj.insert("text".into(), Value::String(r.text.clone()));
                if let Some(lang) = &r.language {
                    obj.insert("language".into(), Value::String(lang.clone()));
                }
                if let Some(audio) = &r.reference_audio {
                    write_audio(&mut obj, audio);
                }
                let mut options = r.options.clone();
                if let Some(rt) = &r.reference_text {
                    options.insert("reference_text".into(), Value::String(rt.clone()));
                }
                if !options.is_empty() {
                    obj.insert(
                        "options".into(),
                        Value::Object(options.into_iter().collect()),
                    );
                }
            }
        }
        Ok(serde_json::to_string(&Value::Object(obj))?)
    }
}

/// 把音频输入写入请求根对象(`audio_path` 或 `audio` 对象)。
fn write_audio(obj: &mut serde_json::Map<String, Value>, input: &AudioInput) {
    match input {
        AudioInput::Path(p) => {
            obj.insert("audio_path".into(), Value::String(p.clone()));
        }
        AudioInput::Buffer(buf) => {
            obj.insert(
                "audio".into(),
                serde_json::json!({
                    "sample_rate": buf.sample_rate,
                    "channels": buf.channels,
                    "samples": buf.samples,
                }),
            );
        }
    }
}

/// 可转换为一次任务请求的参数。
///
/// 已为以下类型实现:
/// - [`Request`] / `&Request`:类型化请求;
/// - `&str` / `String`:任意 JSON 字符串(透传给 C 边界);
/// - `()`:空请求(等价于 `{}`)。
pub trait IntoRequest {
    /// 转换为请求对象。
    ///
    /// # Errors
    ///
    /// 永远成功(各实现均为 infallible),保留 `Result` 以便后续扩展。
    fn into_request(self) -> Result<Request, Error>;
}

impl IntoRequest for Request {
    fn into_request(self) -> Result<Request, Error> {
        Ok(self)
    }
}

impl IntoRequest for &Request {
    fn into_request(self) -> Result<Request, Error> {
        Ok(self.clone())
    }
}

impl IntoRequest for () {
    fn into_request(self) -> Result<Request, Error> {
        Ok(Request::Json("{}".into()))
    }
}

impl IntoRequest for &str {
    fn into_request(self) -> Result<Request, Error> {
        Ok(Request::Json(self.to_string()))
    }
}

impl IntoRequest for String {
    fn into_request(self) -> Result<Request, Error> {
        Ok(Request::Json(self))
    }
}

#[cfg(test)]
mod tests {
    // 测试断言中的 unwrap/expect 是惯用法:失败即测试失败,展开错误链无意义。
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    use super::*;

    fn json(s: &str) -> serde_json::Value {
        serde_json::from_str(s).expect("合法 JSON")
    }

    #[test]
    fn vad_offline() {
        let req = Request::vad("./a.wav").option("vad_threshold", 0.5);
        assert_eq!(
            json(&req.to_json().unwrap()),
            json(r#"{"audio_path":"./a.wav","options":{"vad_threshold":0.5}}"#)
        );
    }

    #[test]
    fn asr_streaming_window() {
        let req = Request::asr("./a.wav").option("audio_chunk_seconds", 3.0);
        assert_eq!(
            json(&req.to_json().unwrap()),
            json(r#"{"audio_path":"./a.wav","options":{"audio_chunk_seconds":3.0}}"#)
        );
    }

    #[test]
    fn tts_text() {
        let req = Request::tts("Hello!");
        assert_eq!(json(&req.to_json().unwrap()), json(r#"{"text":"Hello!"}"#));
    }

    #[test]
    fn tts_voice_clone() {
        let req = Request::tts("Hi")
            .reference("./ref.wav")
            .reference_text("参考文本")
            .language("zh");
        assert_eq!(
            json(&req.to_json().unwrap()),
            json(
                r#"{"text":"Hi","language":"zh","audio_path":"./ref.wav","options":{"reference_text":"参考文本"}}"#
            )
        );
    }

    #[test]
    fn windows_path_no_manual_escaping() {
        // 反斜杠与引号由序列化自动转义。
        let req = Request::asr("C:\\dir\\spe\"ch.wav");
        assert_eq!(
            json(&req.to_json().unwrap()),
            json(r#"{"audio_path":"C:\\dir\\spe\"ch.wav"}"#)
        );
    }

    #[test]
    fn embedded_audio_buffer() {
        let buf = WavAudio {
            sample_rate: 16000,
            channels: 1,
            samples: vec![0.0, 0.5, -0.5],
        };
        let req = Request::vad(AudioInput::Buffer(buf));
        assert_eq!(
            json(&req.to_json().unwrap()),
            json(r#"{"audio":{"sample_rate":16000,"channels":1,"samples":[0.0,0.5,-0.5]}}"#)
        );
    }

    #[test]
    fn raw_json_pass_through() {
        let s = r#"{"text":"hi","options":{"a":1}}"#;
        assert_eq!(Request::json(s).to_json().unwrap(), s);
        assert_eq!(
            <&str as IntoRequest>::into_request(s)
                .unwrap()
                .to_json()
                .unwrap(),
            s
        );
    }

    #[test]
    fn empty_request() {
        assert_eq!(
            IntoRequest::into_request(()).unwrap().to_json().unwrap(),
            "{}"
        );
    }
}