1use crate::error::{DomainError, ErrorCode};
2use crate::{
3 USER_AGENT,
4 config::{Config, validate_url},
5};
6use anyhow::{Context, Result, bail};
7use serde_json::{Value, json};
8use std::{
9 borrow::Cow,
10 collections::HashMap,
11 fs,
12 io::{Read, Write},
13 os::unix::net::UnixStream,
14 path::{Path, PathBuf},
15 process::{Child, Command, Stdio},
16 sync::{
17 Arc, Mutex, OnceLock,
18 atomic::{AtomicBool, Ordering},
19 },
20 thread,
21 time::{Duration, Instant},
22};
23
24#[derive(Debug)]
25pub enum Event {
26 Playing,
27 Title(String),
28 End(String),
29 Failed(DomainError),
30 Paused(bool),
31 Volume(u8),
32 Muted(bool),
33}
34
35pub struct Player {
36 child: Child,
37 stream: UnixStream,
38 socket: PathBuf,
39 buffer: Vec<u8>,
40 audio_device: Option<String>,
41}
42
43#[derive(Debug, serde::Serialize)]
44pub struct AudioDevice {
45 pub name: String,
46 pub description: String,
47}
48
49fn parse_audio_devices(output: &str) -> Vec<AudioDevice> {
50 output
51 .lines()
52 .filter_map(|line| {
53 let line = line.trim().strip_prefix('\'')?;
54 let (name, description) = line.rsplit_once("' (")?;
55 Some(AudioDevice {
56 name: name.into(),
57 description: description.strip_suffix(')')?.into(),
58 })
59 })
60 .collect()
61}
62
63pub fn audio_devices(config: &Config, stop: &Arc<AtomicBool>) -> Result<Vec<AudioDevice>> {
64 let output = crate::process::output(
65 Command::new(&config.settings.mpv).args(["--no-config", "--audio-device=help"]),
66 Duration::from_secs(3),
67 stop,
68 )?;
69 let devices = parse_audio_devices(&String::from_utf8_lossy(&output));
70 if devices.is_empty() {
71 bail!(DomainError::new(ErrorCode::AudioDevicesUnavailable));
72 }
73 Ok(devices)
74}
75
76fn supports_normalization(config: &Config, stop: &Arc<AtomicBool>) -> Result<bool> {
77 type Probe = Arc<Mutex<Option<bool>>>;
78 static PROBES: OnceLock<Mutex<HashMap<String, Probe>>> = OnceLock::new();
79 let probe = PROBES
80 .get_or_init(Mutex::default)
81 .lock()
82 .unwrap()
83 .entry(config.settings.mpv.clone())
84 .or_default()
85 .clone();
86 let mut cached = probe.lock().unwrap();
89 if let Some(supported) = *cached {
90 return Ok(supported);
91 }
92 let filters = crate::process::output(
93 Command::new(&config.settings.mpv).args(["--no-config", "--af=help"]),
94 Duration::from_secs(3),
95 stop,
96 )?;
97 let supported = String::from_utf8_lossy(&filters)
98 .lines()
99 .any(|line| line.split_whitespace().next() == Some("dynaudnorm"));
100 *cached = Some(supported);
101 Ok(supported)
102}
103
104fn metadata_title(metadata: &Value) -> String {
105 let Some(title) = metadata["icy-title"].as_str() else {
106 return crate::clean_text(metadata["title"].as_str().unwrap_or(""));
107 };
108 icy_title(title)
109}
110
111pub(crate) fn icy_title(title: &str) -> String {
112 let mut repaired = String::with_capacity(title.len());
116 let mut start = 0;
117 for (index, character) in title.char_indices() {
118 if !matches!(character, '\u{80}'..='\u{ff}') {
119 repaired.push_str(&repair_latin1_run(&title[start..index]));
120 repaired.push(character);
121 start = index + character.len_utf8();
122 }
123 }
124 repaired.push_str(&repair_latin1_run(&title[start..]));
125 crate::clean_text(&repaired)
126}
127
128pub(crate) fn icy_title_bytes(bytes: &[u8]) -> String {
129 let mut title = String::with_capacity(bytes.len());
132 let mut start = 0;
133 for (index, &byte) in bytes.iter().enumerate() {
134 if byte.is_ascii() {
135 decode_icy_run(&bytes[start..index], &mut title);
136 title.push(char::from(byte));
137 start = index + 1;
138 }
139 }
140 decode_icy_run(&bytes[start..], &mut title);
141 icy_title(&title)
142}
143
144fn decode_icy_run(bytes: &[u8], title: &mut String) {
145 if let Ok(valid) = std::str::from_utf8(bytes) {
146 title.push_str(valid);
147 return;
148 }
149 let has_utf8_han = bytes
152 .utf8_chunks()
153 .any(|chunk| chunk.valid().chars().any(is_cjk));
154 if !has_utf8_han {
155 let latin1: String = bytes.iter().map(|&byte| char::from(byte)).collect();
156 if let Cow::Owned(repaired) = repair_latin1_run(&latin1) {
157 title.push_str(&repaired);
158 return;
159 }
160 }
161 for chunk in bytes.utf8_chunks() {
162 title.push_str(chunk.valid());
163 title.extend(chunk.invalid().iter().map(|&byte| char::from(byte)));
164 }
165}
166
167fn repair_latin1_run(run: &str) -> Cow<'_, str> {
168 if run.is_empty() {
169 return Cow::Borrowed(run);
170 }
171 let bytes: Vec<u8> = run.chars().map(|c| c as u8).collect();
172 if let Ok(repaired) = std::str::from_utf8(&bytes) {
173 return Cow::Owned(repaired.to_owned());
174 }
175
176 if bytes.len() < 4
182 || !run
183 .chars()
184 .any(|c| !c.is_alphabetic() && !c.is_control() && !c.is_whitespace())
185 {
186 return Cow::Borrowed(run);
187 }
188 if let Some(decoded) =
189 encoding_rs::GB18030.decode_without_bom_handling_and_without_replacement(&bytes)
190 && decoded.chars().all(is_cjk)
191 && decoded.chars().count() * 2 == bytes.len()
192 {
193 Cow::Owned(decoded.into_owned())
194 } else {
195 Cow::Borrowed(run)
196 }
197}
198
199fn is_cjk(character: char) -> bool {
200 matches!(character, '\u{3400}'..='\u{9fff}' | '\u{f900}'..='\u{faff}')
201}
202
203const SOCKET_PATH_LIMIT: usize = 100;
214
215fn ipc_socket_path(runtime_dir: &Path) -> PathBuf {
216 let id = uuid::Uuid::new_v4().simple().to_string();
217 let primary = runtime_dir.join(format!("mpv-{}.sock", &id[..12]));
218 if primary.as_os_str().len() <= SOCKET_PATH_LIMIT {
219 return primary;
220 }
221 std::env::temp_dir().join(format!("mpv-{id}.sock"))
222}
223
224fn playback_command(config: &Config, socket: &Path) -> Command {
225 let mut command = Command::new(&config.settings.mpv);
226 command
227 .args([
228 "--no-config",
229 "--load-scripts=no",
230 "--no-video",
231 "--no-audio-display",
232 "--terminal=no",
233 "--input-default-bindings=no",
234 "--idle=yes",
235 "--keep-open=no",
236 "--cache=yes",
237 "--cache-secs=3",
238 "--demuxer-max-bytes=2097152",
239 "--demuxer-max-back-bytes=524288",
242 "--demuxer-donate-buffer=no",
243 "--audio-buffer=0.2",
244 ])
245 .arg(format!("--user-agent={USER_AGENT}"))
246 .arg(format!("--volume={}", config.settings.volume))
247 .arg(format!(
248 "--network-timeout={}",
249 config.settings.playback_timeout_secs
250 ))
251 .arg(format!("--input-ipc-server={}", socket.display()))
252 .stdin(Stdio::null())
253 .stdout(Stdio::null())
254 .stderr(Stdio::null());
255 if config.settings.normalize_loudness {
256 command.arg("--af=dynaudnorm=f=150:g=5");
257 }
258 if let Some(device) = config
259 .settings
260 .audio_device
261 .as_deref()
262 .filter(|s| !s.trim().is_empty())
263 {
264 command.arg(format!("--audio-device={device}"));
265 }
266 command
267}
268
269impl Player {
270 pub fn start(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
271 validate_url(url)?;
272 Self::start_input(config, url, stop)
273 }
274
275 pub fn start_local(
276 config: &Config,
277 path: &std::path::Path,
278 stop: &Arc<AtomicBool>,
279 ) -> Result<Self> {
280 let path = fs::canonicalize(path)?;
281 let url = reqwest::Url::from_file_path(path)
282 .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?;
283 Self::start_input(config, url.as_str(), stop)
284 }
285
286 fn start_input(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
287 let socket = ipc_socket_path(&config.runtime_dir);
288 if socket.as_os_str().len() > SOCKET_PATH_LIMIT {
289 bail!(DomainError::new(ErrorCode::RuntimePathTooLong).with("path", socket.display()));
292 }
293 if config.settings.normalize_loudness && !supports_normalization(config, stop)? {
294 bail!(DomainError::new(ErrorCode::NormalizationUnavailable));
295 }
296 let command = playback_command(config, &socket);
297 let mut child = crate::process::spawn_owned(command)
298 .context(DomainError::new(ErrorCode::MissingDependency).with("program", "mpv"))?;
299 let deadline = Instant::now() + Duration::from_secs(3);
300 let stream = loop {
301 if let Ok(stream) = UnixStream::connect(&socket) {
302 break stream;
303 }
304 if child.try_wait()?.is_some()
305 || Instant::now() >= deadline
306 || stop.load(Ordering::Relaxed)
307 {
308 let _ = child.kill();
309 let _ = child.wait();
310 let _ = fs::remove_file(&socket);
311 bail!(DomainError::new(ErrorCode::PlayerStartup));
312 }
313 thread::sleep(Duration::from_millis(20));
314 };
315 stream.set_read_timeout(Some(Duration::from_millis(1)))?;
316 stream.set_write_timeout(Some(Duration::from_secs(1)))?;
317 let mut player = Self {
318 child,
319 stream,
320 socket,
321 buffer: vec![],
322 audio_device: config.settings.audio_device.clone(),
323 };
324 for (id, property) in [(1, "metadata"), (2, "pause"), (3, "volume"), (4, "mute")] {
325 player.command(json!(["observe_property", id, property]))?;
326 }
327 player.command(json!(["loadfile", url, "replace"]))?;
328 Ok(player)
329 }
330
331 pub fn command(&mut self, command: Value) -> Result<()> {
332 let mut bytes = serde_json::to_vec(&json!({"command":command}))?;
333 bytes.push(b'\n');
334 self.stream.write_all(&bytes)?;
335 Ok(())
336 }
337
338 pub fn toggle_pause(&mut self) -> Result<()> {
339 self.command(json!(["cycle", "pause"]))
340 }
341 pub fn toggle_mute(&mut self) -> Result<()> {
342 self.command(json!(["cycle", "mute"]))
343 }
344 pub fn volume(&mut self, delta: i32) -> Result<()> {
345 self.command(json!(["add", "volume", delta]))
346 }
347
348 pub fn poll(&mut self) -> Result<Vec<Event>> {
349 let mut out = vec![];
350 let mut buf = [0u8; 8192];
351 let mut closed = false;
352 loop {
353 match self.stream.read(&mut buf) {
354 Ok(0) => {
355 closed = true;
356 break;
357 }
358 Ok(n) => self.buffer.extend_from_slice(&buf[..n]),
359 Err(e)
360 if matches!(
361 e.kind(),
362 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
363 ) =>
364 {
365 break;
366 }
367 Err(e) => return Err(e.into()),
368 }
369 if self.buffer.len() > 1024 * 1024 {
370 bail!(DomainError::new(ErrorCode::PlayerMessageTooLarge));
371 }
372 if self.buffer.len() >= 8192 {
373 break;
374 }
375 }
376 while let Some(end) = self.buffer.iter().position(|b| *b == b'\n') {
377 let line: Vec<_> = self.buffer.drain(..=end).collect();
378 let Ok(value) = serde_json::from_slice::<Value>(&line) else {
379 continue;
380 };
381 match value["event"].as_str().unwrap_or("") {
382 "playback-restart" => out.push(Event::Playing),
383 "end-file" => {
384 if value["file_error"]
385 .as_str()
386 .is_some_and(|error| error.contains("audio output"))
387 && let Some(device) = self
388 .audio_device
389 .as_deref()
390 .filter(|s| !s.trim().is_empty())
391 {
392 out.push(Event::Failed(
393 DomainError::new(ErrorCode::AudioDeviceFailed).with("device", device),
394 ));
395 continue;
396 }
397 out.push(Event::End(
398 value["reason"].as_str().unwrap_or("unknown").into(),
399 ));
400 }
401 "property-change" => match value["name"].as_str().unwrap_or("") {
402 "metadata" => {
403 out.push(Event::Title(metadata_title(&value["data"])));
404 }
405 "pause" => out.push(Event::Paused(value["data"].as_bool().unwrap_or(false))),
406 "mute" => out.push(Event::Muted(value["data"].as_bool().unwrap_or(false))),
407 "volume" => out.push(Event::Volume(
408 value["data"].as_f64().unwrap_or(80.).clamp(0., 100.) as u8,
409 )),
410 _ => {}
411 },
412 _ => {}
413 }
414 }
415 if out.is_empty() && closed {
418 bail!(DomainError::new(ErrorCode::PlayerClosed));
419 }
420 if out.is_empty() && self.child.try_wait()?.is_some() {
421 bail!(DomainError::new(ErrorCode::PlayerExited));
422 }
423 Ok(out)
424 }
425}
426
427impl Drop for Player {
428 fn drop(&mut self) {
429 let _ = self.command(json!(["quit"]));
430 let deadline = Instant::now() + Duration::from_millis(800);
431 while Instant::now() < deadline {
432 if self.child.try_wait().ok().flatten().is_some() {
433 break;
434 }
435 thread::sleep(Duration::from_millis(20));
436 }
437 let _ = self.child.kill();
438 let _ = self.child.wait();
439 let _ = fs::remove_file(&self.socket);
440 }
441}
442
443#[cfg(test)]
444mod socket_path_tests {
445 use super::{SOCKET_PATH_LIMIT, ipc_socket_path};
446 use std::path::Path;
447
448 #[test]
449 fn prefers_runtime_dir_with_a_short_name() {
450 let dir = Path::new("/tmp/radio-test-run");
451 let path = ipc_socket_path(dir);
452 assert!(path.starts_with(dir));
453 assert!(path.as_os_str().len() <= SOCKET_PATH_LIMIT);
454 let name = path.file_name().unwrap().to_str().unwrap();
455 assert!(name.starts_with("mpv-") && name.ends_with(".sock"));
456 }
457
458 #[test]
459 fn falls_back_to_temp_dir_for_deep_runtime_dirs() {
460 let deep = std::env::temp_dir().join("a".repeat(160));
461 let path = ipc_socket_path(&deep);
462 assert!(path.starts_with(std::env::temp_dir()));
465 assert!(!path.starts_with(&deep));
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::{icy_title_bytes, metadata_title, parse_audio_devices, playback_command};
472 use serde_json::json;
473
474 #[test]
475 fn device_names_preserve_backend_syntax_and_optional_arguments() {
476 let parsed = parse_audio_devices(
477 "List of detected audio devices:\n 'auto' (Autoselect device)\n 'alsa/plughw:CARD=USB,DEV=0' (Listener's USB (stereo))\nignored\n",
478 );
479 assert_eq!(parsed.len(), 2);
480 assert_eq!(parsed[1].name, "alsa/plughw:CARD=USB,DEV=0");
481 assert_eq!(parsed[1].description, "Listener's USB (stereo)");
482 let dir = tempfile::tempdir().unwrap();
483 let mut config = crate::config::Config::load(None, Some(dir.path()), None).unwrap();
484 let socket = std::path::Path::new("/tmp/radio.sock");
485 let original: Vec<_> = playback_command(&config, socket)
486 .get_args()
487 .map(|a| a.to_owned())
488 .collect();
489 config.settings.audio_device = Some(String::new());
490 assert_eq!(
491 playback_command(&config, socket)
492 .get_args()
493 .collect::<Vec<_>>(),
494 original
495 );
496 config.settings.audio_device = Some(parsed[1].name.clone());
497 let command = playback_command(&config, socket);
498 let args: Vec<_> = command.get_args().collect();
499 assert_eq!(&args[..original.len()], original);
500 assert_eq!(
501 args.last().unwrap(),
502 &"--audio-device=alsa/plughw:CARD=USB,DEV=0"
503 );
504 }
505
506 #[test]
507 fn normalization_changes_only_the_opt_in_filter_argument() {
508 let dir = tempfile::tempdir().unwrap();
509 let mut config = crate::config::Config::load(None, Some(dir.path()), None).unwrap();
510 let socket = std::path::Path::new("/tmp/radio-test.sock");
511 let command = playback_command(&config, socket);
512 let original: Vec<_> = command
513 .get_args()
514 .map(|a| a.to_string_lossy().into_owned())
515 .collect();
516 assert_eq!(
517 original,
518 vec![
519 "--no-config",
520 "--load-scripts=no",
521 "--no-video",
522 "--no-audio-display",
523 "--terminal=no",
524 "--input-default-bindings=no",
525 "--idle=yes",
526 "--keep-open=no",
527 "--cache=yes",
528 "--cache-secs=3",
529 "--demuxer-max-bytes=2097152",
530 "--demuxer-max-back-bytes=524288",
531 "--demuxer-donate-buffer=no",
532 "--audio-buffer=0.2",
533 &format!("--user-agent={}", crate::USER_AGENT),
534 "--volume=80",
535 "--network-timeout=12",
536 "--input-ipc-server=/tmp/radio-test.sock",
537 ]
538 );
539 config.settings.normalize_loudness = true;
540 let command = playback_command(&config, socket);
541 let enabled: Vec<_> = command
542 .get_args()
543 .map(|a| a.to_string_lossy().into_owned())
544 .collect();
545 assert_eq!(&enabled[..original.len()], original);
546 assert_eq!(&enabled[original.len()..], ["--af=dynaudnorm=f=150:g=5"]);
547 }
548
549 #[test]
550 fn icy_titles_repair_latin1_mojibake_before_sanitizing() {
551 let title = "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - é\u{9b}ªè\u{8a}±\x1b\n";
554 assert_eq!(
555 metadata_title(&json!({"icy-title": title})),
556 "邝美云 - 雪花"
557 );
558 }
559
560 #[test]
561 fn icy_titles_repair_gbk_segments_in_mixed_mojibake() {
562 let title = "\u{cd}\u{f5}\u{b7}\u{c6} - (AsiaFM亚洲粤语\u{e5}\u{8f}?)";
566 assert_eq!(
567 metadata_title(&json!({"icy-title": title})),
568 "王菲 - (AsiaFM亚洲粤语å?)"
569 );
570 let lone_pair = "\u{b7}\u{c6} - (AsiaFM亚洲粤语)";
575 assert_eq!(
576 metadata_title(&json!({"icy-title": lone_pair})),
577 "\u{b7}\u{c6} - (AsiaFM亚洲粤语)"
578 );
579 let another_lone_pair = "\u{cd}\u{f5} - (AsiaFM亚洲粤语)";
580 assert_eq!(
581 metadata_title(&json!({"icy-title": another_lone_pair})),
582 "\u{cd}\u{f5} - (AsiaFM亚洲粤语)"
583 );
584 assert_eq!(
586 metadata_title(&json!({"icy-title": "Íõ·Æ\n - Café(中文电台)"})),
587 "王菲 - Café(中文电台)"
588 );
589 }
590
591 #[test]
592 fn icy_titles_repair_latin1_wrapped_gbk() {
593 let title = "ºÓͼ - ×Ï´¨Â¼";
595 assert_eq!(
596 metadata_title(&json!({"icy-title": title})),
597 "河图 - 紫川录"
598 );
599 }
600
601 #[test]
602 fn icy_titles_keep_text_without_a_lossless_latin1_repair() {
603 for title in [
604 "Radio Swiss Jazz",
605 "张柏芝 - 乱了感觉",
606 "Café à côté",
607 "Björk - Jóga",
608 "Motörhead - Ace of Spades",
609 "Sigur Rós - Hoppípolla",
610 "Chloéë",
611 "Chloéë - 中文电台",
612 "Lääke - 中文电台",
613 "Lääke - Jää(中文电台)",
614 "éééé - 中文电台",
615 "éé - àà(中文电台)",
616 "Íõ· - 中文电台",
617 "ÖÐÎÄ", "’",
619 ] {
620 assert_eq!(metadata_title(&json!({"icy-title": title})), title);
621 assert_eq!(icy_title_bytes(title.as_bytes()), title);
622 }
623 assert_eq!(metadata_title(&json!({"icy-title": "中文\x1b\n"})), "中文");
624 }
625
626 #[test]
627 fn icy_titles_repair_utf8_runs_before_removing_c1_bytes() {
628 for (title, expected) in [
629 ("Beyoncé - Café", "Beyoncé - Café"),
630 ("Café — Live", "Café — Live"),
631 (
632 "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - 中文电台\x1b\n",
633 "邝美云 - 中文电台",
634 ),
635 ] {
636 assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
637 }
638 }
639
640 #[test]
641 fn icy_title_bytes_preserve_utf8_islands_and_latin1_fallbacks() {
642 let mut raw = b"\xcd\xf5\xb7\xc6 - ".to_vec();
643 raw.extend_from_slice("中文电台".as_bytes());
644 assert_eq!(icy_title_bytes(&raw), "王菲 - 中文电台");
645 let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
646 adjacent.extend_from_slice("中文".as_bytes());
647 assert_eq!(icy_title_bytes(&adjacent), "王菲中文");
648 assert_eq!(icy_title_bytes(b"Beyonc\xe9"), "Beyoncé");
649 assert_eq!(
650 icy_title_bytes(b"\xba\xd3\xcd\xbc - \xd7\xcf\xb4\xa8\xc2\xbc"),
651 "河图 - 紫川录"
652 );
653 assert_eq!(icy_title_bytes(b"Track\x1b\n\xff"), "Trackÿ");
654 }
655
656 #[test]
657 fn metadata_titles_preserve_file_tags_and_explicit_empty_icy_titles() {
658 assert_eq!(metadata_title(&json!({"title": "©\x1b\n"})), "©");
660 assert_eq!(
661 metadata_title(&json!({"icy-title": "", "title": "File title"})),
662 ""
663 );
664 assert_eq!(
665 metadata_title(&json!({"icy-title": 1, "title": "File title"})),
666 "File title"
667 );
668 assert_eq!(metadata_title(&json!(null)), "");
669 }
670
671 #[test]
672 fn icy_titles_are_limited_after_repair() {
673 let title = "ä¸\u{ad}".repeat(1100);
674 assert_eq!(
675 metadata_title(&json!({"icy-title": title})),
676 "中".repeat(1024)
677 );
678 }
679}