Skip to main content

acde_wire/
asr.rs

1use std::path::PathBuf;
2
3use serde_json::{Map, Value, json};
4
5pub const VERSION: u64 = 2;
6pub const SAMPLE_RATE: u32 = 16_000;
7pub const MAX_FRAME: usize = 1 << 20;
8pub const MAX_HOTWORDS: usize = 200;
9pub const MAX_HOTWORD_CHARS: usize = 32;
10pub const MAX_NAME_CHARS: usize = 128;
11
12const CONTROL: u8 = 0x01;
13const AUDIO: u8 = 0x02;
14const HEADER: usize = 4;
15
16pub fn socket_path() -> Option<PathBuf> {
17    let runtime = std::env::var_os("XDG_RUNTIME_DIR").filter(|dir| !dir.is_empty())?;
18    Some(PathBuf::from(runtime).join("acdes").join("asr.socket"))
19}
20
21#[derive(Debug, Clone, PartialEq)]
22pub enum Frame {
23    Control(Value),
24    Audio(Vec<i16>),
25}
26
27impl Frame {
28    pub fn encode(&self) -> Vec<u8> {
29        let (kind, payload) = match self {
30            Frame::Control(value) => (CONTROL, value.to_string().into_bytes()),
31            Frame::Audio(samples) => (AUDIO, samples.iter().flat_map(|s| s.to_le_bytes()).collect()),
32        };
33        let length = u32::try_from(payload.len() + 1).unwrap_or(u32::MAX);
34        let mut out = Vec::with_capacity(HEADER + 1 + payload.len());
35        out.extend_from_slice(&length.to_le_bytes());
36        out.push(kind);
37        out.extend_from_slice(&payload);
38        out
39    }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum FrameError {
44    TooLong(usize),
45    Empty,
46    Kind(u8),
47    Json(String),
48    OddAudio(usize),
49}
50
51impl std::fmt::Display for FrameError {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            FrameError::TooLong(length) => write!(f, "a frame of {length} bytes is longer than {MAX_FRAME}"),
55            FrameError::Empty => write!(f, "a frame without its kind byte"),
56            FrameError::Kind(kind) => write!(f, "unknown frame kind {kind:#04x}"),
57            FrameError::Json(why) => write!(f, "a control frame that is no JSON object: {why}"),
58            FrameError::OddAudio(length) => write!(f, "{length} bytes of audio are no whole 16-bit samples"),
59        }
60    }
61}
62
63#[derive(Default)]
64pub struct Frames {
65    buffer: Vec<u8>,
66}
67
68impl Frames {
69    pub fn push(&mut self, bytes: &[u8]) {
70        self.buffer.extend_from_slice(bytes);
71    }
72
73    pub fn next_frame(&mut self) -> Option<Result<Frame, FrameError>> {
74        let header: [u8; HEADER] = self.buffer.get(..HEADER)?.try_into().ok()?;
75        let length = u32::from_le_bytes(header) as usize;
76        if length > MAX_FRAME {
77            return Some(Err(FrameError::TooLong(length)));
78        }
79        if self.buffer.len() < HEADER + length {
80            return None;
81        }
82        let body: Vec<u8> = self.buffer.drain(..HEADER + length).skip(HEADER).collect();
83        Some(decode(&body))
84    }
85}
86
87fn decode(body: &[u8]) -> Result<Frame, FrameError> {
88    let (&kind, payload) = body.split_first().ok_or(FrameError::Empty)?;
89    match kind {
90        CONTROL => match serde_json::from_slice::<Value>(payload) {
91            Ok(value) if value.is_object() => Ok(Frame::Control(value)),
92            Ok(_) => Err(FrameError::Json("not an object".into())),
93            Err(e) => Err(FrameError::Json(e.to_string())),
94        },
95        AUDIO if payload.len() % 2 == 0 => Ok(Frame::Audio(payload.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]])).collect())),
96        AUDIO => Err(FrameError::OddAudio(payload.len())),
97        kind => Err(FrameError::Kind(kind)),
98    }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Client {
103    InputMethod,
104    Voice,
105}
106
107impl Client {
108    pub fn as_str(self) -> &'static str {
109        match self {
110            Client::InputMethod => "input-method",
111            Client::Voice => "voice",
112        }
113    }
114
115    pub fn parse(name: &str) -> Option<Self> {
116        [Client::InputMethod, Client::Voice].into_iter().find(|client| client.as_str() == name)
117    }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Start {
122    pub client: Client,
123    pub hotwords: Vec<String>,
124    pub recognize: bool,
125    pub name: Option<String>,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum Request {
130    Hello { version: u64 },
131    Start(Start),
132    Finish,
133    Cancel,
134}
135
136impl Request {
137    pub fn to_json(&self) -> Value {
138        match self {
139            Request::Hello { version } => json!({ "type": "hello", "version": version }),
140            Request::Start(start) => {
141                let mut value = json!({ "type": "start", "client": start.client.as_str(), "hotwords": start.hotwords, "recognize": start.recognize });
142                if let Some(name) = &start.name {
143                    value["name"] = json!(name);
144                }
145                value
146            }
147            Request::Finish => json!({ "type": "finish" }),
148            Request::Cancel => json!({ "type": "cancel" }),
149        }
150    }
151
152    pub fn from_json(value: &Value) -> Result<Self, String> {
153        let object = value.as_object().ok_or("a request is a JSON object")?;
154        match kind_of(object)? {
155            "hello" => Ok(Request::Hello { version: object.get("version").and_then(Value::as_u64).ok_or("hello needs a numeric version")? }),
156            "start" => start(object).map(Request::Start),
157            "finish" => Ok(Request::Finish),
158            "cancel" => Ok(Request::Cancel),
159            other => Err(format!("unknown request {other:?}")),
160        }
161    }
162}
163
164fn start(object: &Map<String, Value>) -> Result<Start, String> {
165    let client = object.get("client").and_then(Value::as_str).unwrap_or_default();
166    let client = Client::parse(client).ok_or_else(|| format!("start needs client input-method or voice, not {client:?}"))?;
167    let recognize = match object.get("recognize") {
168        None | Some(Value::Null) => true,
169        Some(value) => value.as_bool().ok_or("recognize is true or false")?,
170    };
171    Ok(Start { client, hotwords: hotwords(object.get("hotwords"))?, recognize, name: name(object.get("name"))? })
172}
173
174fn name(value: Option<&Value>) -> Result<Option<String>, String> {
175    let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(None) };
176    let name = value.as_str().ok_or("name is a string")?;
177    let fits = !name.is_empty() && name.chars().count() <= MAX_NAME_CHARS && !name.chars().any(char::is_control);
178    fits.then(|| Some(name.to_string())).ok_or_else(|| format!("name {name:?} is empty, too long or has control characters"))
179}
180
181fn hotwords(value: Option<&Value>) -> Result<Vec<String>, String> {
182    let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
183    let list = value.as_array().ok_or("hotwords is a list of strings")?;
184    if list.len() > MAX_HOTWORDS {
185        return Err(format!("{} hotwords, at most {MAX_HOTWORDS}", list.len()));
186    }
187    list.iter()
188        .map(|word| {
189            let word = word.as_str().ok_or("hotwords is a list of strings")?.trim();
190            match word.chars().count() {
191                0 => Err("an empty hotword".to_string()),
192                n if n > MAX_HOTWORD_CHARS => Err(format!("hotword {word:?} is longer than {MAX_HOTWORD_CHARS} characters")),
193                _ => Ok(word.to_string()),
194            }
195        })
196        .collect()
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub enum Reason {
201    ModelMissing,
202    ModelBroken,
203    RuntimeFailed,
204    BadRequest,
205    ServiceMissing,
206    MicrophoneFailed,
207}
208
209impl Reason {
210    const ALL: [(Reason, &'static str); 6] = [
211        (Reason::ModelMissing, "model-missing"),
212        (Reason::ModelBroken, "model-broken"),
213        (Reason::RuntimeFailed, "runtime-failed"),
214        (Reason::BadRequest, "bad-request"),
215        (Reason::ServiceMissing, "service-missing"),
216        (Reason::MicrophoneFailed, "microphone-failed"),
217    ];
218
219    pub fn as_str(self) -> &'static str {
220        Self::ALL.iter().find(|(reason, _)| *reason == self).map_or("runtime-failed", |(_, name)| name)
221    }
222
223    pub fn parse(name: &str) -> Option<Self> {
224        Self::ALL.iter().find(|(_, n)| *n == name).map(|(reason, _)| *reason)
225    }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct Model {
230    pub id: String,
231    pub languages: Vec<String>,
232    pub hotwords: bool,
233}
234
235#[derive(Debug, Clone, PartialEq)]
236pub enum Reply {
237    Ready(Model),
238    Unavailable { reason: Reason, detail: String },
239    Recording,
240    Level { value: f64 },
241    Partial { text: String },
242    Final { text: String },
243    Error { reason: Reason, detail: String },
244    Done,
245}
246
247impl Reply {
248    pub fn to_json(&self) -> Value {
249        match self {
250            Reply::Ready(m) => json!({ "type": "ready", "model": m.id, "languages": m.languages, "sampleRate": SAMPLE_RATE, "hotwords": m.hotwords }),
251            Reply::Unavailable { reason, detail } => json!({ "type": "unavailable", "reason": reason.as_str(), "detail": detail }),
252            Reply::Recording => json!({ "type": "recording" }),
253            Reply::Level { value } => json!({ "type": "level", "value": value.clamp(0.0, 1.0) }),
254            Reply::Partial { text } => json!({ "type": "partial", "text": text }),
255            Reply::Final { text } => json!({ "type": "final", "text": text }),
256            Reply::Error { reason, detail } => json!({ "type": "error", "reason": reason.as_str(), "detail": detail }),
257            Reply::Done => json!({ "type": "done" }),
258        }
259    }
260
261    pub fn from_json(value: &Value) -> Result<Self, String> {
262        let object = value.as_object().ok_or("a reply is a JSON object")?;
263        let text = || object.get("text").and_then(Value::as_str).map(str::to_string).ok_or("no text");
264        let reason = || {
265            let name = object.get("reason").and_then(Value::as_str).unwrap_or_default();
266            let reason = Reason::parse(name).ok_or_else(|| format!("unknown reason {name:?}"))?;
267            Ok::<_, String>((reason, object.get("detail").and_then(Value::as_str).unwrap_or_default().to_string()))
268        };
269        match kind_of(object)? {
270            "ready" => Ok(Reply::Ready(Model {
271                id: object.get("model").and_then(Value::as_str).ok_or("ready needs the model")?.to_string(),
272                languages: object.get("languages").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(),
273                hotwords: object.get("hotwords").and_then(Value::as_bool).unwrap_or(false),
274            })),
275            "unavailable" => reason().map(|(reason, detail)| Reply::Unavailable { reason, detail }),
276            "recording" => Ok(Reply::Recording),
277            "level" => object
278                .get("value")
279                .and_then(Value::as_f64)
280                .map(|value| Reply::Level { value: value.clamp(0.0, 1.0) })
281                .ok_or_else(|| "level needs a value".into()),
282            "partial" => Ok(Reply::Partial { text: text()? }),
283            "final" => Ok(Reply::Final { text: text()? }),
284            "error" => reason().map(|(reason, detail)| Reply::Error { reason, detail }),
285            "done" => Ok(Reply::Done),
286            other => Err(format!("unknown reply {other:?}")),
287        }
288    }
289}
290
291fn kind_of(object: &Map<String, Value>) -> Result<&str, String> {
292    object.get("type").and_then(Value::as_str).ok_or_else(|| "no type".to_string())
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    fn read_all(bytes: &[u8]) -> Vec<Result<Frame, FrameError>> {
300        let mut frames = Frames::default();
301        let mut out = Vec::new();
302        for byte in bytes {
303            frames.push(std::slice::from_ref(byte));
304            out.extend(frames.next_frame());
305        }
306        out
307    }
308
309    #[test]
310    fn frames_survive_being_split_anywhere() {
311        let sent = [Frame::Control(Request::Start(start(Client::Voice, vec!["Dopame".into()])).to_json()), Frame::Audio(vec![0, -1, i16::MAX, i16::MIN])];
312        let bytes: Vec<u8> = sent.iter().flat_map(Frame::encode).collect();
313        let got: Vec<Frame> = read_all(&bytes).into_iter().map(Result::unwrap).collect();
314        assert_eq!(got, sent);
315    }
316
317    #[test]
318    fn bad_frames_are_named() {
319        let too_long = ((MAX_FRAME + 1) as u32).to_le_bytes();
320        assert_eq!(read_all(&too_long), [Err(FrameError::TooLong(MAX_FRAME + 1))]);
321        assert_eq!(read_all(&[2, 0, 0, 0, AUDIO, 1]), [Err(FrameError::OddAudio(1))]);
322        assert_eq!(read_all(&[1, 0, 0, 0, 9]), [Err(FrameError::Kind(9))]);
323        assert!(matches!(read_all(&[3, 0, 0, 0, CONTROL, b'[', b']']).as_slice(), [Err(FrameError::Json(_))]));
324    }
325
326    #[test]
327    fn requests_and_replies_round_trip() {
328        let named = Start { recognize: false, name: Some("dopame.assistant".into()), ..start(Client::Voice, Vec::new()) };
329        let requests = [
330            Request::Hello { version: VERSION },
331            Request::Start(start(Client::InputMethod, vec!["张三".into(), "acdes".into()])),
332            Request::Start(named),
333            Request::Finish,
334            Request::Cancel,
335        ];
336        for request in requests {
337            assert_eq!(Request::from_json(&request.to_json()), Ok(request));
338        }
339        let model = Model { id: "zipformer-zh-en".into(), languages: vec!["zh".into(), "en".into()], hotwords: true };
340        let replies = [
341            Reply::Ready(model),
342            Reply::Unavailable { reason: Reason::ModelMissing, detail: "/usr/share/acdes/asr/models".into() },
343            Reply::Recording,
344            Reply::Level { value: 0.25 },
345            Reply::Partial { text: "你好".into() },
346            Reply::Final { text: "你好 world".into() },
347            Reply::Error { reason: Reason::RuntimeFailed, detail: "x".into() },
348            Reply::Error { reason: Reason::MicrophoneFailed, detail: "the default source went away".into() },
349            Reply::Done,
350        ];
351        for reply in replies {
352            assert_eq!(Reply::from_json(&reply.to_json()), Ok(reply));
353        }
354    }
355
356    fn start(client: Client, hotwords: Vec<String>) -> Start {
357        Start { client, hotwords, recognize: true, name: None }
358    }
359
360    #[test]
361    fn hotwords_are_bounded() {
362        let with = |words: Vec<String>| Request::from_json(&json!({ "type": "start", "client": "voice", "hotwords": words }));
363        assert_eq!(with(Vec::new()), Ok(Request::Start(start(Client::Voice, Vec::new()))));
364        assert_eq!(Request::from_json(&json!({ "type": "start", "client": "voice" })), Ok(Request::Start(start(Client::Voice, Vec::new()))));
365        assert!(with(vec!["x".into(); MAX_HOTWORDS + 1]).is_err());
366        assert!(with(vec!["长".repeat(MAX_HOTWORD_CHARS + 1)]).is_err());
367        assert!(with(vec!["  ".into()]).is_err());
368    }
369
370    #[test]
371    fn a_start_names_its_client_and_may_ask_for_audio_alone() {
372        assert!(Request::from_json(&json!({ "type": "start" })).is_err(), "the client is required");
373        assert!(Request::from_json(&json!({ "type": "start", "client": "browser" })).is_err());
374        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "recognize": "no" })).is_err());
375        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "name": "a\nb" })).is_err());
376        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "name": "x".repeat(MAX_NAME_CHARS + 1) })).is_err());
377        let audio = Request::from_json(&json!({ "type": "start", "client": "voice", "recognize": false, "name": "dopame.assistant" }));
378        assert_eq!(audio, Ok(Request::Start(Start { recognize: false, name: Some("dopame.assistant".into()), ..start(Client::Voice, Vec::new()) })));
379        assert_eq!(Reply::from_json(&json!({ "type": "level", "value": 3.0 })), Ok(Reply::Level { value: 1.0 }), "a level stays within 0 to 1");
380    }
381
382    #[test]
383    fn the_socket_lives_in_the_runtime_directory() {
384        let path = socket_path();
385        if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR").filter(|d| !d.is_empty()) {
386            assert_eq!(path, Some(PathBuf::from(runtime).join("acdes/asr.socket")));
387        }
388    }
389}