返回 CodeWhale
voice.rs
根目录 / crates / engine / src / voice.rs
1 //! Voice capture and transcription core: recorder detection, WAV encoding,
2 //! ASR selection and dispatch, the send-suffix contract, and the headless
3 //! record→transcribe cycle.
4 //!
5 //! Shared by the TUI's `/voice` commands (`commands::voice`, which keeps the
6 //! slash commands and the composer-updating capture loop) and the runtime
7 //! API's `/v1/voice` routes (`runtime_api::voice`). No UI types live here.
8 //!
9 //! ## Recording
10 //!
11 //! Uses platform-specific command-line tools (sox, rec, arecord) to capture
12 //! 16kHz mono 16-bit PCM audio. Records until a silence gap is detected or
13 //! the maximum duration is reached (default 10 s).
14
15 use std::process::{Command, Stdio};
16 use std::sync::LazyLock;
17 use std::time::Duration;
18
19 use regex::Regex;
20
21 use codewhale_runtime::config::Config;
22
23 /// Transcription model requested from the provider's chat-completions API.
24 const ASR_MODEL: &str = "mimo-v2.5-asr";
25 const GROQ_ASR_MODEL: &str = "whisper-large-v3-turbo";
26 pub const UPLOAD_AUDIO_MAX_BYTES: usize = crate::deepseek_media::DEEPSEEK_ASR_MAX_BYTES;
27 /// Local whisper binary names to probe (whisper.cpp, faster-whisper, OpenAI whisper).
28 const LOCAL_WHISPER_BINS: &[&str] = &["whisper", "whisper.cpp", "whisper-cpp", "faster-whisper"];
29 /// Model used for the AI-assisted voice-control pipeline.
30 const VOICE_CONTROL_MODEL: &str = "mimo-v2.5";
31
32 // --- Recorder detection ----------------------------------------------------
33
34 /// Platform-specific recorder definitions.
35 #[derive(Debug, Clone)]
36 struct Recorder {
37 cmd: &'static str,
38 /// CLI arguments for piping raw 16kHz mono S16_LE PCM to stdout.
39 pipe_args: &'static [&'static str],
40 }
41
42 fn detect_recorder() -> Option<Recorder> {
43 let probe = || {
44 if std::env::var_os("CODEWHALE_DISABLE_VOICE").is_some() {
45 return None;
46 }
47 let candidates: &[Recorder] = if cfg!(target_os = "macos") {
48 &[
49 Recorder {
50 cmd: "sox",
51 pipe_args: &["-d", "-r", "16000", "-c", "1", "-b", "16", "-t", "raw", "-"],
52 },
53 Recorder {
54 cmd: "rec",
55 pipe_args: &["-r", "16000", "-c", "1", "-b", "16", "-t", "raw", "-"],
56 },
57 ]
58 } else if cfg!(target_os = "linux") {
59 &[
60 Recorder {
61 cmd: "arecord",
62 pipe_args: &["-f", "S16_LE", "-r", "16000", "-c", "1", "-t", "raw"],
63 },
64 Recorder {
65 cmd: "sox",
66 pipe_args: &["-d", "-r", "16000", "-c", "1", "-b", "16", "-t", "raw", "-"],
67 },
68 ]
69 } else if cfg!(target_os = "windows") {
70 &[Recorder {
71 cmd: "sox",
72 pipe_args: &["-d", "-r", "16000", "-c", "1", "-b", "16", "-t", "raw", "-"],
73 }]
74 } else {
75 &[]
76 };
77
78 candidates
79 .iter()
80 .find(|r| {
81 Command::new(r.cmd)
82 .arg("--version")
83 .stdin(Stdio::null())
84 .stdout(Stdio::null())
85 .stderr(Stdio::null())
86 .spawn()
87 .is_ok()
88 })
89 .cloned()
90 };
91 #[cfg(any(test, feature = "test-support"))]
92 {
93 crate::test_support::with_test_env_lock(probe)
94 }
95 #[cfg(not(any(test, feature = "test-support")))]
96 {
97 probe()
98 }
99 }
100
101 /// Check whether voice recording is available on this system.
102 pub fn is_available() -> bool {
103 detect_recorder().is_some()
104 }
105
106 // --- WAV encoding ----------------------------------------------------------
107
108 /// Encode raw 16kHz mono S16_LE PCM samples as a WAV buffer.
109 fn encode_wav(samples: &[i16]) -> Vec<u8> {
110 encode_wav_with_rate(samples, 16000)
111 }
112
113 fn encode_wav_with_rate(samples: &[i16], sample_rate: u32) -> Vec<u8> {
114 let data_size = (samples.len() * 2) as u32;
115 let mut buf = Vec::with_capacity(44 + data_size as usize);
116
117 // RIFF header
118 buf.extend_from_slice(b"RIFF");
119 buf.extend_from_slice(&(36 + data_size).to_le_bytes());
120 buf.extend_from_slice(b"WAVE");
121
122 // fmt chunk
123 buf.extend_from_slice(b"fmt ");
124 buf.extend_from_slice(&16u32.to_le_bytes()); // chunk size
125 buf.extend_from_slice(&1u16.to_le_bytes()); // PCM
126 buf.extend_from_slice(&1u16.to_le_bytes()); // mono
127 buf.extend_from_slice(&sample_rate.to_le_bytes());
128 buf.extend_from_slice(&(sample_rate.saturating_mul(2)).to_le_bytes());
129 buf.extend_from_slice(&2u16.to_le_bytes()); // block align
130 buf.extend_from_slice(&16u16.to_le_bytes()); // bits per sample
131
132 // data chunk
133 buf.extend_from_slice(b"data");
134 buf.extend_from_slice(&data_size.to_le_bytes());
135 for &sample in samples {
136 buf.extend_from_slice(&sample.to_le_bytes());
137 }
138
139 buf
140 }
141
142 // --- Recording -------------------------------------------------------------
143
144 /// Maximum recording duration in seconds before auto-stopping.
145 pub const MAX_RECORD_SECS: u64 = 10;
146 /// Minimum segment duration in seconds to consider as valid speech.
147 const MIN_SEGMENT_SECS: f64 = 0.3;
148
149 /// Record audio from the default microphone.
150 ///
151 /// Returns raw 16kHz mono S16_LE PCM samples. Returns `None` if no recorder
152 /// is available, the recording failed, or no speech was detected.
153 pub fn record_audio() -> Option<(Vec<i16>, Duration)> {
154 let recorder = detect_recorder()?;
155 let start = std::time::Instant::now();
156
157 let mut child = Command::new(recorder.cmd)
158 .args(recorder.pipe_args)
159 .stdin(Stdio::null())
160 .stdout(Stdio::piped())
161 .stderr(Stdio::null())
162 .spawn()
163 .ok()?;
164
165 let stdout = child.stdout.take()?;
166 let mut reader = std::io::BufReader::new(stdout);
167 let mut all_samples: Vec<i16> = Vec::with_capacity(16000 * MAX_RECORD_SECS as usize);
168
169 // Read until timeout or silence
170 let mut buf = [0u8; 320]; // 10ms of 16kHz S16_LE
171 let max_duration = Duration::from_secs(MAX_RECORD_SECS);
172 let mut silence_samples = 0u32;
173 let mut had_speech = false;
174 let speech_threshold: i16 = 500; // RMS-based speech detection threshold
175 let silence_duration_samples = 16000u32; // 1 second of silence to stop
176
177 loop {
178 use std::io::Read;
179 match reader.read_exact(&mut buf) {
180 Ok(()) => {
181 let chunk: Vec<i16> = buf
182 .as_chunks::<2>()
183 .0
184 .iter()
185 .copied()
186 .map(i16::from_le_bytes)
187 .collect();
188
189 // Simple RMS-based VAD
190 let rms = (chunk.iter().map(|&s| (s as f64) * (s as f64)).sum::<f64>()
191 / chunk.len() as f64)
192 .sqrt();
193 let is_speech = rms > speech_threshold as f64;
194
195 if is_speech {
196 had_speech = true;
197 silence_samples = 0;
198 } else if had_speech {
199 silence_samples += chunk.len() as u32;
200 }
201
202 if had_speech {
203 all_samples.extend_from_slice(&chunk);
204 }
205
206 if start.elapsed() > max_duration {
207 let _ = child.kill();
208 break;
209 }
210 if had_speech && silence_samples >= silence_duration_samples {
211 let _ = child.kill();
212 break;
213 }
214 }
215 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
216 Err(_) => {
217 let _ = child.kill();
218 break;
219 }
220 }
221 }
222
223 let _ = child.wait();
224 let elapsed = start.elapsed();
225
226 let min_samples = (MIN_SEGMENT_SECS * 16000.0) as usize;
227 if all_samples.len() < min_samples {
228 return None;
229 }
230
231 Some((all_samples, elapsed))
232 }
233
234 // --- Auto-send suffix ------------------------------------------------------
235
236 /// Trailing phrases that mean "submit this" — the human-readable form of
237 /// `SEND_SUFFIX_RE`; keep in sync with the regex when either changes.
238 pub const SEND_PHRASES: &[&str] = &["send it", "发送", "發送"];
239
240 /// Matches an explicit send instruction at the end of transcribed text:
241 /// "send it" (any spacing/case) or 发送/發送, with trailing punctuation.
242 static SEND_SUFFIX_RE: LazyLock<Regex> = LazyLock::new(|| {
243 Regex::new(r"(?i)(?:^|[\s,,.。!!??]+)(?:send\s*it|发送|發送)[\s.。!!??]*$").unwrap()
244 });
245
246 /// Split a transcript into the message remainder and whether it ended with an
247 /// explicit send instruction. `"ship the fix, send it"` → `("ship the fix", true)`.
248 pub fn split_send_suffix(text: &str) -> (&str, bool) {
249 match SEND_SUFFIX_RE.find(text) {
250 Some(found) => (text[..found.start()].trim(), true),
251 None => (text.trim(), false),
252 }
253 }
254
255 // --- Transcription ---------------------------------------------------------
256
257 fn base64_encode(data: &[u8]) -> String {
258 use base64::Engine;
259 base64::engine::general_purpose::STANDARD.encode(data)
260 }
261
262 fn chat_completions_url(base_url: &str) -> String {
263 format!("{}/chat/completions", base_url.trim_end_matches('/'))
264 }
265
266 async fn post_chat_completions(
267 api_key: &str,
268 base_url: &str,
269 mut body: serde_json::Value,
270 openrouter_vendor: Option<&str>,
271 ) -> Result<serde_json::Value, String> {
272 crate::client::apply_openrouter_vendor(&mut body, openrouter_vendor);
273 let _inference = crate::client::acquire_remote_control_inference_participant().await;
274 let client = codewhale_release::tls::reqwest_client();
275 let resp = client
276 .post(chat_completions_url(base_url))
277 .header("Content-Type", "application/json")
278 .header("Authorization", format!("Bearer {api_key}"))
279 .timeout(Duration::from_secs(30))
280 .json(&body)
281 .send()
282 .await
283 .map_err(|e| format!("request failed: {e}"))?;
284
285 if !resp.status().is_success() {
286 return Err(format!("API returned status {}", resp.status()));
287 }
288
289 resp.json()
290 .await
291 .map_err(|e| format!("failed to parse response: {e}"))
292 }
293
294 /// Send audio to the provider's API for plain transcription.
295 ///
296 /// Uses the chat completions endpoint with `input_audio` content blocks.
297 pub async fn transcribe(
298 api_key: &str,
299 base_url: &str,
300 audio_samples: &[i16],
301 openrouter_vendor: Option<&str>,
302 ) -> Result<String, String> {
303 transcribe_with_model(
304 api_key,
305 base_url,
306 audio_samples,
307 ASR_MODEL,
308 openrouter_vendor,
309 )
310 .await
311 }
312
313 async fn transcribe_with_model(
314 api_key: &str,
315 base_url: &str,
316 audio_samples: &[i16],
317 model: &str,
318 openrouter_vendor: Option<&str>,
319 ) -> Result<String, String> {
320 let wav = encode_wav(audio_samples);
321 let data_url = format!("data:audio/wav;base64,{}", base64_encode(&wav));
322
323 let body = serde_json::json!({
324 "model": model,
325 "messages": [
326 {
327 "role": "user",
328 "content": [
329 {
330 "type": "input_audio",
331 "input_audio": {
332 "data": data_url
333 }
334 }
335 ]
336 }
337 ],
338 "asr_options": {
339 "language": "auto"
340 }
341 });
342
343 let data = post_chat_completions(api_key, base_url, body, openrouter_vendor).await?;
344 data["choices"][0]["message"]["content"]
345 .as_str()
346 .map(|s| s.trim().to_string())
347 .ok_or_else(|| "no transcription in response".to_string())
348 }
349
350 /// Process audio through the voice-control pipeline: AI-assisted dictation
351 /// that sees the current composer text, mirroring MiMo Code's
352 /// `processVoiceControl`. Used when `/voice-control` is enabled.
353 pub async fn process_voice_control(
354 api_key: &str,
355 base_url: &str,
356 audio_samples: &[i16],
357 current_text: &str,
358 openrouter_vendor: Option<&str>,
359 ) -> Result<String, String> {
360 let wav = encode_wav(audio_samples);
361 let data_url = format!("data:audio/wav;base64,{}", base64_encode(&wav));
362
363 let user_context = serde_json::json!({
364 "current_text": current_text,
365 "cursor": "end",
366 });
367
368 let body = serde_json::json!({
369 "model": VOICE_CONTROL_MODEL,
370 "messages": [
371 {
372 "role": "system",
373 "content": "You are a voice input assistant. Transcribe the user's speech. Output JSON: {\"text\": \"transcribed text\"}."
374 },
375 {
376 "role": "user",
377 "content": [
378 { "type": "text", "text": user_context.to_string() },
379 { "type": "input_audio", "input_audio": { "data": data_url } }
380 ]
381 }
382 ],
383 "response_format": { "type": "json_object" }
384 });
385
386 let data = post_chat_completions(api_key, base_url, body, openrouter_vendor).await?;
387 let content = data["choices"][0]["message"]["content"]
388 .as_str()
389 .ok_or_else(|| "no response content".to_string())?;
390
391 let parsed: serde_json::Value = serde_json::from_str(content)
392 .map_err(|e| format!("failed to parse voice control JSON: {e}"))?;
393
394 parsed["text"]
395 .as_str()
396 .map(|s| s.to_string())
397 .ok_or_else(|| "no text field in voice control response".to_string())
398 }
399
400 /// Detect best free ASR for this host — local whisper > Groq free > provider fallback.
401 /// Works on macOS (brew install whisper-cpp), Windows (whisper.cpp binary),
402 /// Linux (apt), and HarmonyOS (falls back to cloud).
403 fn detect_free_asr() -> &'static str {
404 for bin in LOCAL_WHISPER_BINS {
405 if Command::new(bin)
406 .arg("--help")
407 .stdin(Stdio::null())
408 .stdout(Stdio::null())
409 .stderr(Stdio::null())
410 .spawn()
411 .is_ok()
412 {
413 return "local-whisper";
414 }
415 }
416 if std::env::var("GROQ_API_KEY").is_ok_and(|v| !v.trim().is_empty()) {
417 return "groq";
418 }
419 "provider"
420 }
421
422 /// Transcribe via local whisper.cpp (free, offline, cross-platform).
423 ///
424 /// The whole body is synchronous — temp-file I/O plus `Command::output()`,
425 /// which blocks for the entire subprocess run — so it runs on the blocking
426 /// pool rather than a Tokio worker (blocking-call convention, #6149).
427 pub async fn transcribe_local_whisper(audio_samples: &[i16]) -> Result<String, String> {
428 let wav = encode_wav(audio_samples);
429 tokio::task::spawn_blocking(move || transcribe_local_whisper_blocking(&wav))
430 .await
431 .map_err(|e| e.to_string())?
432 }
433
434 fn transcribe_local_whisper_blocking(wav: &[u8]) -> Result<String, String> {
435 // C01-10: a fresh, exclusively created file per call. The old
436 // `cw-voice-<pid>.wav` name was shared by every transcription in the
437 // process (an interim pass, the final pass, a runtime-API dictation) and
438 // predictable in a shared temp dir. Dropping `audio` removes it.
439 let audio = tempfile::Builder::new()
440 .prefix("cw-voice-")
441 .suffix(".wav")
442 .tempfile()
443 .map_err(|e| e.to_string())?;
444 let tmp = audio.path().to_path_buf();
445 std::fs::write(&tmp, wav).map_err(|e| e.to_string())?;
446 // Try each local binary until one succeeds; whisper.cpp outputs to stdout or file.
447 for bin in LOCAL_WHISPER_BINS {
448 let output = Command::new(bin)
449 .arg(tmp.to_string_lossy().as_ref())
450 .arg("--model")
451 .arg("tiny")
452 .arg("--language")
453 .arg("auto")
454 .arg("--output-txt")
455 .output();
456 if let Ok(out) = output
457 && out.status.success()
458 {
459 let txt = String::from_utf8_lossy(&out.stdout).trim().to_string();
460 if !txt.is_empty() {
461 return Ok(txt);
462 }
463 // Some builds write to .txt sidecar
464 let sidecar = tmp.with_extension("txt");
465 if let Ok(s) = std::fs::read_to_string(&sidecar) {
466 let _ = std::fs::remove_file(&sidecar);
467 if !s.trim().is_empty() {
468 return Ok(s.trim().to_string());
469 }
470 }
471 }
472 }
473 Err("local whisper not available".into())
474 }
475
476 /// Transcribe via Groq Whisper large-v3-turbo (free tier, ~$0.04/hr, fast).
477 /// Groq is NOT a full CodeWhale provider yet — this is a direct ASR call
478 /// using `GROQ_API_KEY` only (no provider setup needed). Uses the same
479 /// chat-completions `input_audio` path as Xiaomi so no `multipart` feature.
480 pub async fn transcribe_groq(audio_samples: &[i16]) -> Result<String, String> {
481 let api_key = std::env::var("GROQ_API_KEY").map_err(|_| "GROQ_API_KEY not set".to_string())?;
482 let base_url = "https://api.groq.com/openai/v1";
483 transcribe_with_model(&api_key, base_url, audio_samples, GROQ_ASR_MODEL, None).await
484 }
485
486 pub fn resolve_asr_choice(config: &Config) -> (String, String) {
487 let read = || {
488 let explicit = std::env::var("CODEWHALE_ASR_MODEL")
489 .ok()
490 .and_then(|value| explicit_asr_choice(&value));
491 let (kind, model) = explicit.unwrap_or_else(|| match detect_free_asr() {
492 "local-whisper" => ("local-whisper", "tiny"),
493 "groq" => ("groq", GROQ_ASR_MODEL),
494 _ if config.active_provider_identity().is_ok_and(|identity| {
495 matches!(
496 identity.provider,
497 codewhale_config::ProviderKind::Deepseek
498 | codewhale_config::ProviderKind::DeepseekAnthropic
499 )
500 }) =>
501 {
502 ("deepseek", crate::deepseek_media::DEEPSEEK_ASR_MODEL)
503 }
504 _ => ("provider", ASR_MODEL),
505 });
506 (kind.to_string(), model.to_string())
507 };
508 #[cfg(any(test, feature = "test-support"))]
509 {
510 crate::test_support::with_test_env_lock(read)
511 }
512 #[cfg(not(any(test, feature = "test-support")))]
513 {
514 read()
515 }
516 }
517
518 fn explicit_asr_choice(value: &str) -> Option<(&'static str, &'static str)> {
519 let m = value.trim().to_ascii_lowercase();
520 if m.contains("local") || m.contains("whisper.cpp") || m.contains("whisper-cpp") {
521 return Some(("local-whisper", "tiny"));
522 }
523 if m.contains("groq") || m.contains("whisper") {
524 return Some(("groq", GROQ_ASR_MODEL));
525 }
526 if m.contains("deepseek") {
527 return Some(("deepseek", crate::deepseek_media::DEEPSEEK_ASR_MODEL));
528 }
529 if m.contains("mimo") || m.contains("xiaomi") {
530 return Some(("provider", ASR_MODEL));
531 }
532 None
533 }
534
535 // --- Headless capture (HTTP/native-client path) ----------------------------
536
537 /// What a headless dictation should do with the finished transcript.
538 #[derive(Debug, Clone)]
539 pub enum DictateMode {
540 /// Transcribe and return the text for insertion into the composer.
541 Insert,
542 /// Transcribe, then apply the "send it" / 发送 suffix contract. The
543 /// outcome's `send` flag tells the client to submit; a bare send
544 /// instruction yields empty `text` so the client submits its own draft.
545 Send,
546 /// AI-assisted dictation that sees the client's composer text — the
547 /// `/voice-control` pipeline. Only provider ASR can see context; free
548 /// ASR kinds degrade to plain transcription with `assisted: false`.
549 Control(String),
550 }
551
552 /// Machine-readable failure for the headless path so HTTP clients can
553 /// localize by `reason` rather than parsing message text.
554 #[derive(Debug)]
555 pub enum DictateError {
556 NoRecorder,
557 NoSpeech,
558 NoProviderAuth,
559 InvalidInput(String),
560 Transcription(String),
561 }
562
563 impl DictateError {
564 pub fn reason(&self) -> &'static str {
565 match self {
566 Self::NoRecorder => "no_recorder",
567 Self::NoSpeech => "no_speech",
568 Self::NoProviderAuth => "no_provider_auth",
569 Self::InvalidInput(_) => "invalid_input",
570 Self::Transcription(_) => "transcription_failed",
571 }
572 }
573 }
574
575 impl std::fmt::Display for DictateError {
576 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577 match self {
578 Self::NoRecorder => write!(f, "no supported voice recorder on this host"),
579 Self::NoSpeech => write!(f, "no speech detected"),
580 Self::NoProviderAuth => {
581 write!(f, "provider ASR requires a configured API key")
582 }
583 Self::InvalidInput(e) | Self::Transcription(e) => write!(f, "{e}"),
584 }
585 }
586 }
587
588 /// Result of one headless record→transcribe cycle.
589 #[derive(Debug)]
590 pub struct DictationOutcome {
591 /// Final transcript (send suffix already stripped for `Send` mode).
592 pub text: String,
593 /// `Send` mode only: the transcript ended with an explicit send phrase.
594 pub send: bool,
595 /// `Control` mode only: the composer context reached the model. False
596 /// when a free ASR kind handled the audio and never saw the context.
597 pub assisted: bool,
598 /// Which ASR backend was selected for this capture.
599 pub asr_kind: String,
600 pub asr_model: String,
601 }
602
603 /// Detected recorder binary name, if any (`"sox"`, `"arecord"`, `"rec"`).
604 pub fn recorder_command() -> Option<&'static str> {
605 detect_recorder().map(|r| r.cmd)
606 }
607
608 /// Resolved ASR selection (`kind`, `model`) for capability reporting.
609 pub fn asr_choice(config: &Config) -> (String, String) {
610 resolve_asr_choice(config)
611 }
612
613 /// One record→transcribe cycle with no UI surface: the HTTP/native-client
614 /// equivalent of `commands::voice::capture_and_transcribe`. Recording runs on a blocking
615 /// thread; transcription follows the same ASR dispatch as the TUI —
616 /// explicit `CODEWHALE_ASR_MODEL` > local whisper > Groq > provider —
617 /// but resolves the provider key lazily so free ASR kinds work without
618 /// provider auth.
619 pub async fn dictate_once(
620 config: &Config,
621 mode: DictateMode,
622 ) -> Result<DictationOutcome, DictateError> {
623 if !is_available() {
624 return Err(DictateError::NoRecorder);
625 }
626 let (samples, _duration) = tokio::task::spawn_blocking(record_audio)
627 .await
628 .ok()
629 .flatten()
630 .ok_or(DictateError::NoSpeech)?;
631
632 let (asr_kind, asr_model) = resolve_asr_choice(config);
633 let assisted = asr_kind == "provider" && matches!(&mode, DictateMode::Control(_));
634 let composer = match &mode {
635 DictateMode::Control(composer) => Some(composer.as_str()),
636 _ => None,
637 };
638 let text = transcribe_selected(config, &asr_kind, &samples, composer).await?;
639
640 let clean = text.trim().to_string();
641 let (text, send) = match mode {
642 DictateMode::Send => {
643 let (remainder, wants_send) = split_send_suffix(&clean);
644 (remainder.to_string(), wants_send)
645 }
646 _ => (clean, false),
647 };
648 Ok(DictationOutcome {
649 text,
650 send,
651 assisted,
652 asr_kind,
653 asr_model,
654 })
655 }
656
657 /// One selected ASR route for both native/HTTP and TUI capture. A failure
658 /// stays on that route: it must not upload the recording to another provider.
659 pub async fn transcribe_selected(
660 config: &Config,
661 kind: &str,
662 samples: &[i16],
663 composer: Option<&str>,
664 ) -> Result<String, DictateError> {
665 let text = match kind {
666 "local-whisper" => transcribe_local_whisper(samples).await,
667 "groq" => transcribe_groq(samples).await,
668 "deepseek" => {
669 let (base_url, api_key) = crate::deepseek_media::resolve_deepseek_config_auth(config)
670 .ok_or(DictateError::NoProviderAuth)?;
671 let wav = encode_wav(samples);
672 crate::deepseek_media::transcribe_deepseek_bytes(
673 &base_url,
674 &api_key,
675 &wav,
676 "voice.wav",
677 "audio/wav",
678 None,
679 )
680 .await
681 .map(|response| response.text)
682 }
683 _ => {
684 let key = config
685 .active_route_api_key()
686 .map_err(|_| DictateError::NoProviderAuth)?;
687 let base = config.active_route_base_url();
688 let vendor = config
689 .openrouter_vendor()
690 .map_err(|error| DictateError::Transcription(error.to_string()))?;
691 match composer {
692 Some(composer) => {
693 process_voice_control(&key, &base, samples, composer, vendor.as_deref()).await
694 }
695 None => transcribe(&key, &base, samples, vendor.as_deref()).await,
696 }
697 }
698 };
699 text.map_err(DictateError::Transcription)
700 }
701
702 #[derive(Debug, Clone, PartialEq, Eq)]
703 pub struct VoiceTtsOutcome {
704 pub audio_bytes: Vec<u8>,
705 pub content_type: String,
706 pub format: String,
707 pub provider: String,
708 pub model: String,
709 pub voice: String,
710 }
711
712 pub const MIMO_TTS_VOICES: &[&str] = &["mimo_default", "Mia", "Chloe", "Milo", "Dean"];
713
714 #[derive(Debug, Clone, PartialEq, Eq)]
715 pub enum VoiceTtsError {
716 NoProviderAuth(String),
717 InvalidInput(String),
718 SynthesisFailed(String),
719 }
720
721 impl VoiceTtsError {
722 pub fn reason(&self) -> &'static str {
723 match self {
724 Self::NoProviderAuth(_) => "no_provider_auth",
725 Self::InvalidInput(_) => "invalid_input",
726 Self::SynthesisFailed(_) => "synthesis_failed",
727 }
728 }
729 }
730
731 impl std::fmt::Display for VoiceTtsError {
732 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
733 match self {
734 Self::NoProviderAuth(msg) | Self::InvalidInput(msg) | Self::SynthesisFailed(msg) => {
735 write!(f, "{msg}")
736 }
737 }
738 }
739 }
740
741 impl std::error::Error for VoiceTtsError {}
742
743 fn active_mimo_tts_ready(config: &Config) -> bool {
744 config
745 .active_provider_identity()
746 .is_ok_and(|identity| identity.provider == codewhale_config::ProviderKind::XiaomiMimo)
747 && config
748 .active_route_api_key_read_only()
749 .is_ok_and(|value| !value.trim().is_empty())
750 }
751
752 fn resample_pcm16_mono(samples: &[i16], src_rate: u32, dst_rate: u32) -> Vec<i16> {
753 if samples.is_empty() || src_rate == dst_rate {
754 return samples.to_vec();
755 }
756 let out_len = ((samples.len() as u64).saturating_mul(dst_rate as u64) / (src_rate as u64))
757 .max(1) as usize;
758 if out_len == 1 || samples.len() == 1 {
759 return vec![samples[0]; out_len];
760 }
761 let ratio = (samples.len() as f64) / (out_len as f64);
762 let max_idx = samples.len() - 1;
763 (0..out_len)
764 .map(|i| {
765 let pos = (i as f64) * ratio;
766 let idx = (pos.floor() as usize).min(max_idx);
767 let next = (idx + 1).min(max_idx);
768 let frac = pos - (idx as f64);
769 let a = samples[idx] as f64;
770 let b = samples[next] as f64;
771 (a + (b - a) * frac)
772 .round()
773 .clamp(i16::MIN as f64, i16::MAX as f64) as i16
774 })
775 .collect()
776 }
777
778 pub fn decode_wav_pcm16_mono(wav_bytes: &[u8]) -> Result<Vec<i16>, String> {
779 if wav_bytes.len() < 12 || &wav_bytes[0..4] != b"RIFF" || &wav_bytes[8..12] != b"WAVE" {
780 return Err("invalid WAV header: expected RIFF/WAVE".to_string());
781 }
782 let mut sample_rate: Option<u32> = None;
783 let mut data_chunk: Option<&[u8]> = None;
784 let mut offset = 12usize;
785 while offset + 8 <= wav_bytes.len() {
786 let chunk_id = &wav_bytes[offset..offset + 4];
787 let chunk_size = u32::from_le_bytes([
788 wav_bytes[offset + 4],
789 wav_bytes[offset + 5],
790 wav_bytes[offset + 6],
791 wav_bytes[offset + 7],
792 ]) as usize;
793 let data_start = offset + 8;
794 let Some(data_end) = data_start.checked_add(chunk_size) else {
795 return Err("invalid WAV chunk length".to_string());
796 };
797 if data_end > wav_bytes.len() {
798 return Err("truncated WAV chunk".to_string());
799 }
800 let chunk = &wav_bytes[data_start..data_end];
801 if chunk_id == b"fmt " {
802 if chunk.len() < 16 {
803 return Err("truncated WAV fmt chunk".to_string());
804 }
805 let audio_format = u16::from_le_bytes([chunk[0], chunk[1]]);
806 let channels = u16::from_le_bytes([chunk[2], chunk[3]]);
807 let parsed_rate = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
808 let bits_per_sample = u16::from_le_bytes([chunk[14], chunk[15]]);
809 if audio_format != 1 || channels != 1 || bits_per_sample != 16 {
810 return Err(format!(
811 "unsupported WAV encoding: expected PCM16 mono, got format={audio_format} channels={channels} bits={bits_per_sample}"
812 ));
813 }
814 if !(8_000..=192_000).contains(&parsed_rate) {
815 return Err(format!(
816 "unsupported WAV sample rate {parsed_rate} Hz (expected 8000..=192000 Hz)"
817 ));
818 }
819 sample_rate = Some(parsed_rate);
820 } else if chunk_id == b"data" {
821 data_chunk = Some(chunk);
822 }
823 offset = data_end.saturating_add(chunk_size & 1);
824 }
825 let Some(sample_rate) = sample_rate else {
826 return Err("missing WAV fmt chunk".to_string());
827 };
828 let Some(data) = data_chunk else {
829 return Err("missing WAV data chunk".to_string());
830 };
831 if data.len() % 2 != 0 {
832 return Err("WAV PCM16 data length must be even".to_string());
833 }
834 let raw_samples: Vec<i16> = data
835 .as_chunks::<2>()
836 .0
837 .iter()
838 .copied()
839 .map(i16::from_le_bytes)
840 .collect();
841 Ok(resample_pcm16_mono(&raw_samples, sample_rate, 16_000))
842 }
843
844 pub fn upload_available(config: &Config) -> bool {
845 let (asr_kind, _) = resolve_asr_choice(config);
846 match asr_kind.as_str() {
847 "local-whisper" => true,
848 "groq" => {
849 let has_groq_key =
850 || std::env::var("GROQ_API_KEY").is_ok_and(|value| !value.trim().is_empty());
851 #[cfg(any(test, feature = "test-support"))]
852 {
853 crate::test_support::with_test_env_lock(has_groq_key)
854 }
855 #[cfg(not(any(test, feature = "test-support")))]
856 {
857 has_groq_key()
858 }
859 }
860 "deepseek" => crate::deepseek_media::resolve_deepseek_config_auth(config).is_some(),
861 _ => config
862 .active_route_api_key_read_only()
863 .is_ok_and(|value| !value.trim().is_empty()),
864 }
865 }
866
867 pub fn tts_available(config: &Config) -> bool {
868 active_mimo_tts_ready(config)
869 || crate::deepseek_media::resolve_deepseek_config_auth(config).is_some()
870 }
871
872 pub fn tts_voices(config: &Config) -> &'static [&'static str] {
873 if active_mimo_tts_ready(config) {
874 MIMO_TTS_VOICES
875 } else if crate::deepseek_media::resolve_deepseek_config_auth(config).is_some() {
876 crate::deepseek_media::DEEPSEEK_TTS_VOICES
877 } else {
878 &[]
879 }
880 }
881
882 pub async fn transcribe_uploaded_audio(
883 config: &Config,
884 audio_bytes: &[u8],
885 mime_type: &str,
886 mode: DictateMode,
887 language: Option<&str>,
888 ) -> Result<DictationOutcome, DictateError> {
889 if audio_bytes.is_empty() {
890 return Err(DictateError::InvalidInput(
891 "audio payload cannot be empty".to_string(),
892 ));
893 }
894 if audio_bytes.len() > UPLOAD_AUDIO_MAX_BYTES {
895 return Err(DictateError::InvalidInput(format!(
896 "audio payload exceeds maximum of {UPLOAD_AUDIO_MAX_BYTES} bytes"
897 )));
898 }
899 let canonical_mime = crate::deepseek_media::normalize_deepseek_asr_mime(mime_type)
900 .map_err(DictateError::InvalidInput)?;
901 let (asr_kind, asr_model) = resolve_asr_choice(config);
902 let assisted = asr_kind == "provider" && matches!(&mode, DictateMode::Control(_));
903 let text = if asr_kind == "deepseek" {
904 let (base_url, api_key) = crate::deepseek_media::resolve_deepseek_config_auth(config)
905 .ok_or(DictateError::NoProviderAuth)?;
906 let file_name = if canonical_mime == "audio/ogg" {
907 "voice.ogg"
908 } else {
909 "voice.wav"
910 };
911 crate::deepseek_media::transcribe_deepseek_bytes(
912 &base_url,
913 &api_key,
914 audio_bytes,
915 file_name,
916 canonical_mime,
917 language,
918 )
919 .await
920 .map(|response| response.text)
921 .map_err(DictateError::Transcription)?
922 } else {
923 if canonical_mime != "audio/wav" {
924 return Err(DictateError::InvalidInput(format!(
925 "mime type '{canonical_mime}' requires DeepSeek ASR; send audio/wav for '{asr_kind}'"
926 )));
927 }
928 let samples = decode_wav_pcm16_mono(audio_bytes).map_err(DictateError::InvalidInput)?;
929 if samples.is_empty() {
930 return Err(DictateError::NoSpeech);
931 }
932 let composer = match &mode {
933 DictateMode::Control(composer) => Some(composer.as_str()),
934 _ => None,
935 };
936 transcribe_selected(config, &asr_kind, &samples, composer).await?
937 };
938
939 let clean = text.trim().to_string();
940 let (text, send) = match mode {
941 DictateMode::Send => {
942 let (remainder, wants_send) = split_send_suffix(&clean);
943 (remainder.to_string(), wants_send)
944 }
945 _ => (clean, false),
946 };
947 Ok(DictationOutcome {
948 text,
949 send,
950 assisted,
951 asr_kind,
952 asr_model,
953 })
954 }
955
956 pub async fn synthesize_voice_tts(
957 config: &Config,
958 text: &str,
959 voice: Option<&str>,
960 format: Option<&str>,
961 ) -> Result<VoiceTtsOutcome, VoiceTtsError> {
962 synthesize_voice_tts_with_options(config, text, voice, format, true).await
963 }
964
965 pub async fn synthesize_voice_tts_with_options(
966 config: &Config,
967 text: &str,
968 voice: Option<&str>,
969 format: Option<&str>,
970 filter_markdown: bool,
971 ) -> Result<VoiceTtsOutcome, VoiceTtsError> {
972 if text.trim().is_empty() {
973 return Err(VoiceTtsError::InvalidInput(
974 "speech text cannot be empty".to_string(),
975 ));
976 }
977 if text.chars().count() > crate::deepseek_media::DEEPSEEK_TTS_MAX_CHARS {
978 return Err(VoiceTtsError::InvalidInput(format!(
979 "speech text exceeds maximum of {} characters",
980 crate::deepseek_media::DEEPSEEK_TTS_MAX_CHARS
981 )));
982 }
983 if active_mimo_tts_ready(config) {
984 let req_format = format.unwrap_or("wav").trim();
985 let format_value = if req_format.is_empty() {
986 "wav".to_string()
987 } else {
988 crate::tools::speech::normalize_speech_format(req_format).ok_or_else(|| {
989 VoiceTtsError::InvalidInput(format!(
990 "unsupported speech format '{req_format}' (allowed: wav, mp3, pcm16)"
991 ))
992 })?
993 };
994 let requested_voice = voice
995 .map(str::trim)
996 .filter(|value| !value.is_empty())
997 .unwrap_or("mimo_default");
998 let client = crate::client::CodewhaleClient::new(config)
999 .map_err(|err| VoiceTtsError::SynthesisFailed(err.to_string()))?;
1000 let response = client
1001 .synthesize_speech(crate::client::SpeechSynthesisRequest {
1002 model: "mimo-v2.5-tts".to_string(),
1003 text: text.to_string(),
1004 instruction: None,
1005 audio_format: format_value,
1006 voice: Some(requested_voice.to_string()),
1007 })
1008 .await
1009 .map_err(|err| VoiceTtsError::SynthesisFailed(err.to_string()))?;
1010 let content_type = match response.audio_format.as_str() {
1011 "mp3" => "audio/mpeg",
1012 "pcm" | "pcm16" => "audio/pcm",
1013 _ => "audio/wav",
1014 };
1015 return Ok(VoiceTtsOutcome {
1016 audio_bytes: response.audio_bytes,
1017 content_type: content_type.to_string(),
1018 format: response.audio_format,
1019 provider: "xiaomi-mimo".to_string(),
1020 model: response.model,
1021 voice: response
1022 .voice
1023 .unwrap_or_else(|| requested_voice.to_string()),
1024 });
1025 }
1026
1027 if let Some((base_url, api_key)) = crate::deepseek_media::resolve_deepseek_config_auth(config) {
1028 crate::deepseek_media::validate_deepseek_tts_inputs(
1029 Some(crate::deepseek_media::DEEPSEEK_TTS_MODEL),
1030 text,
1031 None,
1032 voice,
1033 format.unwrap_or("wav"),
1034 )
1035 .map_err(VoiceTtsError::InvalidInput)?;
1036 let outcome = crate::deepseek_media::synthesize_deepseek_bytes_with_options(
1037 &base_url,
1038 &api_key,
1039 text,
1040 voice,
1041 format.unwrap_or("wav"),
1042 filter_markdown,
1043 )
1044 .await
1045 .map_err(VoiceTtsError::SynthesisFailed)?;
1046 return Ok(VoiceTtsOutcome {
1047 audio_bytes: outcome.audio_bytes,
1048 content_type: outcome.content_type,
1049 format: outcome.format,
1050 provider: "deepseek".to_string(),
1051 model: outcome.model,
1052 voice: outcome.voice,
1053 });
1054 }
1055
1056 Err(VoiceTtsError::NoProviderAuth(
1057 "voice TTS requires a configured DeepSeek or Xiaomi MiMo API key".to_string(),
1058 ))
1059 }
1060
1061 #[cfg(test)]
1062 mod tests {
1063 mod selected_asr;
1064
1065 use super::*;
1066
1067 #[tokio::test]
1068 async fn voice_requests_preserve_openrouter_vendor_pin() {
1069 use wiremock::matchers::{method, path};
1070 use wiremock::{Mock, MockServer, ResponseTemplate};
1071
1072 let server = MockServer::start().await;
1073 Mock::given(method("POST"))
1074 .and(path("/v1/chat/completions"))
1075 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1076 "choices": [{ "message": { "content": "{\"text\":\"hello\"}" } }]
1077 })))
1078 .expect(3)
1079 .mount(&server)
1080 .await;
1081 let base_url = format!("{}/v1", server.uri());
1082 transcribe(
1083 "fixture-key",
1084 &base_url,
1085 &[0; 16],
1086 Some("chutes/region-fixture"),
1087 )
1088 .await
1089 .unwrap();
1090 process_voice_control(
1091 "fixture-key",
1092 &base_url,
1093 &[0; 16],
1094 "existing text",
1095 Some("chutes/region-fixture"),
1096 )
1097 .await
1098 .unwrap();
1099 transcribe_with_model("fixture-key", &base_url, &[0; 16], GROQ_ASR_MODEL, None)
1100 .await
1101 .unwrap();
1102
1103 let requests = server.received_requests().await.unwrap();
1104 assert_eq!(requests.len(), 3);
1105 for request in &requests[..2] {
1106 let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
1107 assert_eq!(
1108 body["provider"],
1109 serde_json::json!({"order": ["chutes/region-fixture"], "allow_fallbacks": false})
1110 );
1111 }
1112 let independent: serde_json::Value = serde_json::from_slice(&requests[2].body).unwrap();
1113 assert!(independent.get("provider").is_none());
1114 }
1115
1116 #[test]
1117 fn explicit_local_whisper_is_not_routed_to_groq() {
1118 // C01-10: every local spelling contains "whisper"; none may reach the
1119 // hosted Groq backend (which needs a key and sends audio off-host).
1120 for local in ["local-whisper", "whisper.cpp", "whisper-cpp", " LOCAL "] {
1121 assert_eq!(
1122 explicit_asr_choice(local),
1123 Some(("local-whisper", "tiny")),
1124 "{local}"
1125 );
1126 }
1127 for hosted in ["groq", "whisper", "whisper-large-v3-turbo"] {
1128 assert_eq!(
1129 explicit_asr_choice(hosted),
1130 Some(("groq", GROQ_ASR_MODEL)),
1131 "{hosted}"
1132 );
1133 }
1134 assert_eq!(explicit_asr_choice("mimo"), Some(("provider", ASR_MODEL)));
1135 assert_eq!(explicit_asr_choice("something-else"), None);
1136 }
1137
1138 #[test]
1139 fn wav_encoding_produces_valid_header() {
1140 let samples = vec![0i16; 16000]; // 1 second of silence
1141 let wav = encode_wav(&samples);
1142 assert_eq!(&wav[0..4], b"RIFF");
1143 assert_eq!(&wav[8..12], b"WAVE");
1144 assert_eq!(&wav[12..16], b"fmt ");
1145 // data size = 16000 * 2 = 32000
1146 assert_eq!(&wav[4..8], &(36 + 32000u32).to_le_bytes());
1147 }
1148
1149 #[test]
1150 fn wav_encoding_empty_is_minimal() {
1151 let wav = encode_wav(&[]);
1152 assert_eq!(wav.len(), 44);
1153 assert_eq!(&wav[4..8], &36u32.to_le_bytes());
1154 }
1155
1156 #[test]
1157 fn send_suffix_detected_and_stripped() {
1158 assert_eq!(split_send_suffix("send it"), ("", true));
1159 assert_eq!(split_send_suffix("Send It!"), ("", true));
1160 assert_eq!(split_send_suffix("发送"), ("", true));
1161 assert_eq!(split_send_suffix("發送。"), ("", true));
1162 assert_eq!(
1163 split_send_suffix("ship the fix, send it"),
1164 ("ship the fix", true)
1165 );
1166 assert_eq!(
1167 split_send_suffix("修复这个问题,发送"),
1168 ("修复这个问题", true)
1169 );
1170 }
1171
1172 #[test]
1173 fn send_suffix_leaves_plain_text_alone() {
1174 assert_eq!(split_send_suffix("send it now"), ("send it now", false));
1175 assert_eq!(
1176 split_send_suffix("帮我发送一封邮件"),
1177 ("帮我发送一封邮件", false)
1178 );
1179 assert_eq!(split_send_suffix("发送邮件"), ("发送邮件", false));
1180 assert_eq!(
1181 split_send_suffix("resend it to the queue"),
1182 ("resend it to the queue", false)
1183 );
1184 }
1185
1186 #[test]
1187 fn recorder_detection_does_not_crash() {
1188 let _lock = crate::test_support::lock_test_env();
1189 let _ = is_available();
1190 }
1191
1192 #[test]
1193 fn explicit_deepseek_asr_choice_resolves_model() {
1194 assert_eq!(
1195 explicit_asr_choice("deepseek"),
1196 Some(("deepseek", crate::deepseek_media::DEEPSEEK_ASR_MODEL))
1197 );
1198 assert_eq!(
1199 explicit_asr_choice("DeepSeek-ASR"),
1200 Some(("deepseek", crate::deepseek_media::DEEPSEEK_ASR_MODEL))
1201 );
1202 }
1203
1204 #[test]
1205 fn wav_decoder_roundtrips_pcm16_mono_and_rejects_bad_headers() {
1206 let wav = encode_wav(&[10, -250, 1234, -4096]);
1207 let decoded = decode_wav_pcm16_mono(&wav).expect("valid wav");
1208 assert_eq!(decoded, vec![10, -250, 1234, -4096]);
1209 assert!(decode_wav_pcm16_mono(b"not-wav").is_err());
1210
1211 let zero_rate = encode_wav_with_rate(&[1, 2, 3], 0);
1212 assert!(decode_wav_pcm16_mono(&zero_rate).is_err());
1213
1214 let wav_48k = encode_wav_with_rate(&vec![1000i16; 480], 48_000);
1215 let resampled = decode_wav_pcm16_mono(&wav_48k).expect("48kHz wav decodes");
1216 assert_eq!(resampled.len(), 160);
1217 }
1218
1219 #[tokio::test]
1220 async fn deepseek_uploaded_audio_and_tts_work_with_deepseek_config() {
1221 use crate::test_support::{EnvVarGuard, lock_test_env};
1222 use wiremock::matchers::{method, path};
1223 use wiremock::{Mock, MockServer, ResponseTemplate};
1224
1225 let server = MockServer::start().await;
1226 Mock::given(method("POST"))
1227 .and(path("/v1/tools/asr"))
1228 .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
1229 "request_id": "req-upload",
1230 "text": "commit the slice send it",
1231 "duration_ms": 950
1232 })))
1233 .mount(&server)
1234 .await;
1235 Mock::given(method("POST"))
1236 .and(path("/v1/tools/tts"))
1237 .respond_with(ResponseTemplate::new(200).set_body_bytes(b"RIFF_TTS".to_vec()))
1238 .mount(&server)
1239 .await;
1240
1241 let _lock = lock_test_env();
1242 let _asr_env = EnvVarGuard::remove("CODEWHALE_ASR_MODEL");
1243 let _groq_env = EnvVarGuard::remove("GROQ_API_KEY");
1244 let _cli_source = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_SOURCE_ENV);
1245 let _legacy_cli_source =
1246 EnvVarGuard::remove(codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV);
1247 let _cli_key = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV);
1248 let _ds_key = EnvVarGuard::remove("DEEPSEEK_API_KEY");
1249 let _ds_base = EnvVarGuard::remove("DEEPSEEK_BASE_URL");
1250 let _cw_base = EnvVarGuard::remove("CODEWHALE_BASE_URL");
1251 let _path = EnvVarGuard::set("PATH", "/nonexistent-voice-path");
1252
1253 let config: Config = toml::from_str(&format!(
1254 "provider = \"deepseek\"\n\n[providers.deepseek]\napi_key = \"ds-voice-key\"\nbase_url = \"{}/v1\"\n",
1255 server.uri()
1256 ))
1257 .expect("deepseek config parses");
1258
1259 assert_eq!(
1260 resolve_asr_choice(&config),
1261 ("deepseek".to_string(), "deepseek-asr".to_string())
1262 );
1263 assert!(upload_available(&config));
1264 assert!(tts_available(&config));
1265
1266 let wav = encode_wav(&[0; 320]);
1267 let outcome =
1268 transcribe_uploaded_audio(&config, &wav, "audio/wav", DictateMode::Send, None)
1269 .await
1270 .expect("upload transcription");
1271 assert_eq!(outcome.text, "commit the slice");
1272 assert!(outcome.send);
1273 assert!(!outcome.assisted);
1274 assert_eq!(outcome.asr_kind, "deepseek");
1275 assert_eq!(outcome.asr_model, "deepseek-asr");
1276
1277 let tts = synthesize_voice_tts(&config, "All tests passed", Some("tide"), Some("wav"))
1278 .await
1279 .expect("voice tts");
1280 assert_eq!(tts.audio_bytes, b"RIFF_TTS");
1281 assert_eq!(tts.provider, "deepseek");
1282 assert_eq!(tts.voice, "tide");
1283 }
1284 }
1285
1285 lines RUST