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
24pub(crate) mod asiafm;
25mod radioinfo;
26
27#[derive(Debug)]
28pub enum Event {
29 Playing,
30 Loaded,
31 Position(Option<u64>),
32 Duration(Option<u64>),
33 Seekable(bool),
34 Reply(u64, bool),
35 Title(String),
36 End(String),
37 Failed(DomainError),
38 Paused(bool),
39 Volume(u8),
40 Muted(bool),
41}
42
43pub struct Player {
44 child: Child,
45 stream: UnixStream,
46 socket: PathBuf,
47 buffer: Vec<u8>,
48 request: u64,
49 audio_device: Option<String>,
50 asiafm_metadata_patch: bool,
51}
52
53#[derive(Debug, serde::Serialize)]
54pub struct AudioDevice {
55 pub name: String,
56 pub description: String,
57}
58
59fn parse_audio_devices(output: &str) -> Vec<AudioDevice> {
60 output
61 .lines()
62 .filter_map(|line| {
63 let line = line.trim().strip_prefix('\'')?;
64 let (name, description) = line.rsplit_once("' (")?;
65 Some(AudioDevice {
66 name: name.into(),
67 description: description.strip_suffix(')')?.into(),
68 })
69 })
70 .collect()
71}
72
73pub fn audio_devices(config: &Config, stop: &Arc<AtomicBool>) -> Result<Vec<AudioDevice>> {
74 let output = crate::process::output(
75 Command::new(&config.settings.mpv).args(["--no-config", "--audio-device=help"]),
76 Duration::from_secs(3),
77 stop,
78 )?;
79 let devices = parse_audio_devices(&String::from_utf8_lossy(&output));
80 if devices.is_empty() {
81 bail!(DomainError::new(ErrorCode::AudioDevicesUnavailable));
82 }
83 Ok(devices)
84}
85
86fn supports_normalization(config: &Config, stop: &Arc<AtomicBool>) -> Result<bool> {
87 type Probe = Arc<Mutex<Option<bool>>>;
88 static PROBES: OnceLock<Mutex<HashMap<String, Probe>>> = OnceLock::new();
89 let probe = PROBES
90 .get_or_init(Mutex::default)
91 .lock()
92 .unwrap()
93 .entry(config.settings.mpv.clone())
94 .or_default()
95 .clone();
96 let mut cached = probe.lock().unwrap();
99 if let Some(supported) = *cached {
100 return Ok(supported);
101 }
102 let filters = crate::process::output(
103 Command::new(&config.settings.mpv).args(["--no-config", "--af=help"]),
104 Duration::from_secs(3),
105 stop,
106 )?;
107 let supported = String::from_utf8_lossy(&filters)
108 .lines()
109 .any(|line| line.split_whitespace().next() == Some("dynaudnorm"));
110 *cached = Some(supported);
111 Ok(supported)
112}
113
114fn metadata_title(metadata: &Value) -> String {
115 let Some(title) = metadata["icy-title"].as_str() else {
116 return display_title(metadata["title"].as_str().unwrap_or(""));
117 };
118 icy_title(&repair_mpv_gbk_runs(title))
119}
120
121fn display_title(title: &str) -> String {
122 let parsed = radioinfo::title(title);
123 crate::clean_text(parsed.as_deref().unwrap_or(title))
124}
125
126fn repair_mpv_gbk_runs(title: &str) -> String {
127 let mut repaired = String::with_capacity(title.len());
128 let mut start = 0;
129 for (end, character) in title
130 .char_indices()
131 .chain(std::iter::once((title.len(), ' ')))
132 {
133 if character.is_ascii() || is_cjk(character) || !character.is_alphabetic() {
134 let run = &title[start..end];
135 if run.chars().any(|c| c > '\u{ff}') && run.chars().any(|c| c <= '\u{ff}') {
142 let mut bytes = Vec::new();
143 for c in run.chars() {
144 if c <= '\u{ff}' {
145 bytes.push(c as u8);
146 } else {
147 bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
148 }
149 }
150 let latin1: String = bytes.iter().map(|&byte| char::from(byte)).collect();
151 if let Cow::Owned(decoded) = repair_latin1_run(&latin1, false)
152 && decoded.chars().all(is_cjk)
153 {
154 repaired.push_str(&decoded);
155 } else {
156 repaired.push_str(run);
157 }
158 } else {
159 repaired.push_str(run);
160 }
161 if end < title.len() {
162 repaired.push(character);
163 start = end + character.len_utf8();
164 }
165 }
166 }
167 repaired
168}
169
170fn parse_ipc_message(line: &[u8]) -> serde_json::Result<Value> {
171 if let Ok(valid) = std::str::from_utf8(line) {
172 return serde_json::from_str(valid);
173 }
174 let decoded = decode_metadata_bytes(line);
180 serde_json::from_str(&decoded)
181}
182
183fn push_metadata_bytes(bytes: &[u8], text: &mut String) {
184 let mut offset = 0;
185 for chunk in bytes.utf8_chunks() {
186 text.push_str(chunk.valid());
187 offset += chunk.valid().len() + chunk.invalid().len();
188 if matches!(chunk.invalid(), [0xe0..=0xf4])
192 && chunk.valid().chars().next_back().is_some_and(is_cjk)
193 && bytes.get(offset).is_none_or(u8::is_ascii)
194 {
195 text.push('\u{fffd}');
196 } else {
197 text.extend(chunk.invalid().iter().map(|&byte| char::from(byte)));
198 }
199 }
200}
201
202pub(crate) fn icy_title(title: &str) -> String {
203 let mut repaired = String::with_capacity(title.len());
210 let utf8_han = title.chars().any(is_cjk);
211 let mut start = 0;
212 for (index, character) in title.char_indices() {
213 if !matches!(character, '\u{80}'..='\u{ff}') {
214 repaired.push_str(&repair_latin1_run(&title[start..index], utf8_han));
215 repaired.push(character);
216 start = index + character.len_utf8();
217 }
218 }
219 repaired.push_str(&repair_latin1_run(&title[start..], utf8_han));
220 display_title(&repaired)
221}
222
223pub(crate) fn icy_title_bytes(bytes: &[u8]) -> String {
224 icy_title(&decode_metadata_bytes(bytes))
225}
226
227fn decode_metadata_bytes(bytes: &[u8]) -> String {
228 let mut title = String::with_capacity(bytes.len());
231 let mut start = 0;
232 for (index, &byte) in bytes.iter().enumerate() {
233 if byte.is_ascii() {
234 decode_icy_run(&bytes[start..index], &mut title);
235 title.push(char::from(byte));
236 start = index + 1;
237 }
238 }
239 decode_icy_run(&bytes[start..], &mut title);
240 title
241}
242
243fn decode_icy_run(bytes: &[u8], title: &mut String) {
244 if let Ok(valid) = std::str::from_utf8(bytes) {
245 title.push_str(valid);
246 return;
247 }
248 let has_utf8_han = bytes
251 .utf8_chunks()
252 .any(|chunk| chunk.valid().chars().any(is_cjk));
253 if !has_utf8_han {
254 let latin1: String = bytes.iter().map(|&byte| char::from(byte)).collect();
255 if let Cow::Owned(repaired) = repair_latin1_run(&latin1, false) {
256 title.push_str(&repaired);
257 return;
258 }
259 }
260 push_metadata_bytes(bytes, title);
261}
262
263fn repair_latin1_run(run: &str, utf8_han: bool) -> Cow<'_, str> {
264 if run.is_empty() {
265 return Cow::Borrowed(run);
266 }
267 let bytes: Vec<u8> = run.chars().map(|c| c as u8).collect();
268 let error = match std::str::from_utf8(&bytes) {
269 Ok(repaired) => return Cow::Owned(repaired.to_owned()),
270 Err(error) => error,
271 };
272 let incomplete_prefix = error
273 .error_len()
274 .is_none()
275 .then(|| std::str::from_utf8(&bytes[..error.valid_up_to()]).unwrap());
276 if let Some(prefix) = incomplete_prefix
280 && prefix.chars().any(is_cjk)
281 {
282 return Cow::Owned(format!("{prefix}\u{fffd}"));
283 }
284
285 if bytes.len() >= 4
291 && run
292 .chars()
293 .any(|c| !c.is_alphabetic() && !c.is_control() && !c.is_whitespace())
294 && let Some(decoded) =
295 encoding_rs::GB18030.decode_without_bom_handling_and_without_replacement(&bytes)
296 && decoded.chars().all(is_cjk)
297 && decoded.chars().count() * 2 == bytes.len()
298 {
299 return Cow::Owned(decoded.into_owned());
300 }
301
302 if let Some(prefix) = incomplete_prefix
306 && utf8_han
307 && bytes.len() - prefix.len() >= 2
308 {
309 return Cow::Owned(format!("{prefix}\u{fffd}"));
310 }
311 Cow::Borrowed(run)
312}
313
314fn is_cjk(character: char) -> bool {
315 matches!(character, '\u{3400}'..='\u{9fff}' | '\u{f900}'..='\u{faff}')
316}
317
318const SOCKET_PATH_LIMIT: usize = 100;
329
330fn ipc_socket_path(runtime_dir: &Path) -> PathBuf {
331 let id = uuid::Uuid::new_v4().simple().to_string();
332 let primary = runtime_dir.join(format!("mpv-{}.sock", &id[..12]));
333 if primary.as_os_str().len() <= SOCKET_PATH_LIMIT {
334 return primary;
335 }
336 std::env::temp_dir().join(format!("mpv-{id}.sock"))
337}
338
339fn playback_command(config: &Config, socket: &Path) -> Command {
340 let mut command = Command::new(&config.settings.mpv);
341 command
342 .args([
343 "--no-config",
344 "--load-scripts=no",
345 "--no-video",
346 "--no-audio-display",
347 "--terminal=no",
348 "--input-default-bindings=no",
349 "--idle=yes",
350 "--keep-open=no",
351 "--cache=yes",
352 "--cache-secs=3",
353 "--demuxer-max-bytes=2097152",
354 "--demuxer-max-back-bytes=524288",
357 "--demuxer-donate-buffer=no",
358 "--audio-buffer=0.2",
359 ])
360 .arg(format!("--user-agent={USER_AGENT}"))
361 .arg(format!("--volume={}", config.settings.volume))
362 .arg(format!(
363 "--network-timeout={}",
364 config.settings.playback_timeout_secs
365 ))
366 .arg(format!("--input-ipc-server={}", socket.display()))
367 .stdin(Stdio::null())
368 .stdout(Stdio::null())
369 .stderr(Stdio::null());
370 if config.settings.normalize_loudness {
371 command.arg("--af=dynaudnorm=f=150:g=5");
372 }
373 if let Some(device) = config
374 .settings
375 .audio_device
376 .as_deref()
377 .filter(|s| !s.trim().is_empty())
378 {
379 command.arg(format!("--audio-device={device}"));
380 }
381 command
382}
383
384impl Player {
385 pub fn start(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
386 Self::start_station(config, url, "", stop)
387 }
388
389 pub(crate) fn start_station(
390 config: &Config,
391 url: &str,
392 stationuuid: &str,
393 stop: &Arc<AtomicBool>,
394 ) -> Result<Self> {
395 validate_url(url)?;
396 Self::start_input(
397 config,
398 url,
399 stop,
400 asiafm::enabled(&config.settings, stationuuid, url),
401 false,
402 )
403 }
404
405 pub fn start_local(
406 config: &Config,
407 path: &std::path::Path,
408 stop: &Arc<AtomicBool>,
409 ) -> Result<Self> {
410 let path = fs::canonicalize(path)?;
411 let url = reqwest::Url::from_file_path(path)
412 .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?;
413 Self::start_input(config, url.as_str(), stop, false, false)
414 }
415
416 pub fn start_episode(config: &Config, input: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
417 let input = if input.starts_with('/') {
418 reqwest::Url::from_file_path(fs::canonicalize(input)?)
419 .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?
420 .to_string()
421 } else {
422 validate_url(input)?;
423 input.to_owned()
424 };
425 Self::start_input(config, &input, stop, false, true)
426 }
427
428 fn start_input(
429 config: &Config,
430 url: &str,
431 stop: &Arc<AtomicBool>,
432 asiafm_metadata_patch: bool,
433 paused: bool,
434 ) -> Result<Self> {
435 let socket = ipc_socket_path(&config.runtime_dir);
436 if socket.as_os_str().len() > SOCKET_PATH_LIMIT {
437 bail!(DomainError::new(ErrorCode::RuntimePathTooLong).with("path", socket.display()));
440 }
441 if config.settings.normalize_loudness && !supports_normalization(config, stop)? {
442 bail!(DomainError::new(ErrorCode::NormalizationUnavailable));
443 }
444 let mut command = playback_command(config, &socket);
445 if paused {
446 command.arg("--pause=yes");
447 }
448 let mut child = crate::process::spawn_owned(command)
449 .context(DomainError::new(ErrorCode::MissingDependency).with("program", "mpv"))?;
450 let deadline = Instant::now() + Duration::from_secs(10);
451 let stream = loop {
452 if let Ok(stream) = UnixStream::connect(&socket) {
453 break stream;
454 }
455 if child.try_wait()?.is_some()
456 || Instant::now() >= deadline
457 || stop.load(Ordering::Relaxed)
458 {
459 let _ = child.kill();
460 let _ = child.wait();
461 let _ = fs::remove_file(&socket);
462 bail!(DomainError::new(ErrorCode::PlayerStartup));
463 }
464 thread::sleep(Duration::from_millis(20));
465 };
466 stream.set_read_timeout(Some(Duration::from_millis(1)))?;
467 stream.set_write_timeout(Some(Duration::from_secs(1)))?;
468 let mut player = Self {
469 child,
470 stream,
471 socket,
472 buffer: vec![],
473 request: 0,
474 audio_device: config.settings.audio_device.clone(),
475 asiafm_metadata_patch,
476 };
477 for (id, property) in [
478 (1, "metadata"),
479 (2, "pause"),
480 (3, "volume"),
481 (4, "mute"),
482 (5, "time-pos"),
483 (6, "duration"),
484 (7, "seekable"),
485 ] {
486 player.command(json!(["observe_property", id, property]))?;
487 }
488 player.command(json!(["loadfile", url, "replace"]))?;
489 Ok(player)
490 }
491
492 pub fn command(&mut self, command: Value) -> Result<()> {
493 let mut bytes = serde_json::to_vec(&json!({"command":command}))?;
494 bytes.push(b'\n');
495 self.stream.write_all(&bytes)?;
496 Ok(())
497 }
498
499 pub fn request(&mut self, command: Value) -> Result<u64> {
500 self.request += 1;
501 let mut bytes = serde_json::to_vec(&json!({"command":command,"request_id":self.request}))?;
502 bytes.push(b'\n');
503 self.stream.write_all(&bytes)?;
504 Ok(self.request)
505 }
506 pub fn toggle_pause(&mut self) -> Result<()> {
507 self.command(json!(["cycle", "pause"]))
508 }
509 pub fn toggle_mute(&mut self) -> Result<()> {
510 self.command(json!(["cycle", "mute"]))
511 }
512 pub fn volume(&mut self, delta: i32) -> Result<()> {
513 self.command(json!(["add", "volume", delta]))
514 }
515
516 pub fn poll(&mut self) -> Result<Vec<Event>> {
517 let mut out = vec![];
518 let mut buf = [0u8; 8192];
519 let exited = self.child.try_wait()?.is_some();
522 let mut disconnected = None;
523 loop {
524 match self.stream.read(&mut buf) {
525 Ok(0) => {
526 disconnected = Some(ErrorCode::PlayerClosed);
527 break;
528 }
529 Ok(n) => self.buffer.extend_from_slice(&buf[..n]),
530 Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {
531 disconnected = Some(ErrorCode::PlayerClosed);
532 break;
533 }
534 Err(e)
535 if matches!(
536 e.kind(),
537 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
538 ) =>
539 {
540 disconnected = exited.then_some(ErrorCode::PlayerExited);
541 break;
542 }
543 Err(e) => return Err(e.into()),
544 }
545 if self.buffer.len() > 1024 * 1024 {
546 bail!(DomainError::new(ErrorCode::PlayerMessageTooLarge));
547 }
548 if self.buffer.len() >= 8192 {
549 break;
550 }
551 }
552 while let Some(end) = self.buffer.iter().position(|b| *b == b'\n') {
553 let line: Vec<_> = self.buffer.drain(..=end).collect();
554 let Ok(value) = parse_ipc_message(&line) else {
555 continue;
556 };
557 if let Some(id) = value["request_id"].as_u64() {
558 out.push(Event::Reply(id, value["error"].as_str() == Some("success")));
559 }
560 match value["event"].as_str().unwrap_or("") {
561 "file-loaded" => out.push(Event::Loaded),
562 "playback-restart" => out.push(Event::Playing),
563 "end-file" => {
564 if value["file_error"]
565 .as_str()
566 .is_some_and(|error| error.contains("audio output"))
567 && let Some(device) = self
568 .audio_device
569 .as_deref()
570 .filter(|s| !s.trim().is_empty())
571 {
572 out.push(Event::Failed(
573 DomainError::new(ErrorCode::AudioDeviceFailed).with("device", device),
574 ));
575 continue;
576 }
577 out.push(Event::End(
578 value["reason"].as_str().unwrap_or("unknown").into(),
579 ));
580 }
581 "property-change" => match value["name"].as_str().unwrap_or("") {
582 "metadata" => {
583 let title = metadata_title(&value["data"]);
584 let title = if self.asiafm_metadata_patch
585 && value["data"]["icy-title"].is_string()
586 {
587 asiafm::title(&title)
588 } else {
589 title
590 };
591 out.push(Event::Title(title));
592 }
593 "time-pos" => out.push(Event::Position(
594 value["data"]
595 .as_f64()
596 .filter(|v| v.is_finite() && *v >= 0.)
597 .map(|v| (v * 1000.) as u64),
598 )),
599 "duration" => out.push(Event::Duration(
600 value["data"]
601 .as_f64()
602 .filter(|v| v.is_finite() && *v > 0.)
603 .map(|v| (v * 1000.) as u64),
604 )),
605 "seekable" => {
606 out.push(Event::Seekable(value["data"].as_bool().unwrap_or(false)))
607 }
608 "pause" => out.push(Event::Paused(value["data"].as_bool().unwrap_or(false))),
609 "mute" => out.push(Event::Muted(value["data"].as_bool().unwrap_or(false))),
610 "volume" => out.push(Event::Volume(
611 value["data"].as_f64().unwrap_or(80.).clamp(0., 100.) as u8,
612 )),
613 _ => {}
614 },
615 _ => {}
616 }
617 }
618 if out.is_empty()
621 && let Some(code) = disconnected
622 {
623 bail!(DomainError::new(code));
624 }
625 Ok(out)
626 }
627}
628
629impl Drop for Player {
630 fn drop(&mut self) {
631 let _ = self.command(json!(["quit"]));
632 let deadline = Instant::now() + Duration::from_millis(800);
633 while Instant::now() < deadline {
634 if self.child.try_wait().ok().flatten().is_some() {
635 break;
636 }
637 thread::sleep(Duration::from_millis(20));
638 }
639 let _ = self.child.kill();
640 let _ = self.child.wait();
641 let _ = fs::remove_file(&self.socket);
642 }
643}
644
645#[cfg(test)]
646mod socket_path_tests {
647 use super::{SOCKET_PATH_LIMIT, ipc_socket_path};
648 use std::path::Path;
649
650 #[test]
651 fn prefers_runtime_dir_with_a_short_name() {
652 let dir = Path::new("/tmp/radio-test-run");
653 let path = ipc_socket_path(dir);
654 assert!(path.starts_with(dir));
655 assert!(path.as_os_str().len() <= SOCKET_PATH_LIMIT);
656 let name = path.file_name().unwrap().to_str().unwrap();
657 assert!(name.starts_with("mpv-") && name.ends_with(".sock"));
658 }
659
660 #[test]
661 fn falls_back_to_temp_dir_for_deep_runtime_dirs() {
662 let deep = std::env::temp_dir().join("a".repeat(160));
663 let path = ipc_socket_path(&deep);
664 assert!(path.starts_with(std::env::temp_dir()));
667 assert!(!path.starts_with(&deep));
668 }
669}
670
671#[cfg(test)]
672mod tests {
673 use super::{
674 icy_title_bytes, metadata_title, parse_audio_devices, parse_ipc_message, playback_command,
675 };
676 use serde_json::json;
677
678 #[test]
679 fn an_exited_player_delivers_its_final_event_after_a_full_read_buffer() {
680 use std::{io::Write, os::unix::net::UnixStream, process::Command};
681 let (stream, mut peer) = UnixStream::pair().unwrap();
682 let mut child = Command::new("true").spawn().unwrap();
683 child.wait().unwrap();
684 let mut player = super::Player {
685 child,
686 stream,
687 socket: Default::default(),
688 buffer: vec![],
689 request: 0,
690 audio_device: Some("test/fail".into()),
691 asiafm_metadata_patch: false,
692 };
693 peer.write_all(&[b' '; 8191]).unwrap();
695 peer.write_all(b"\n").unwrap();
696 assert!(player.poll().unwrap().is_empty());
697 writeln!(
698 peer,
699 "{}",
700 json!({"event":"end-file","file_error":"audio output initialization failed"})
701 )
702 .unwrap();
703 drop(peer);
704 let events = player.poll().unwrap();
705 assert!(
706 matches!(events.as_slice(), [super::Event::Failed(error)] if error.code == crate::error::ErrorCode::AudioDeviceFailed)
707 );
708 }
709
710 #[test]
711 fn device_names_preserve_backend_syntax_and_optional_arguments() {
712 let parsed = parse_audio_devices(
713 "List of detected audio devices:\n 'auto' (Autoselect device)\n 'alsa/plughw:CARD=USB,DEV=0' (Listener's USB (stereo))\nignored\n",
714 );
715 assert_eq!(parsed.len(), 2);
716 assert_eq!(parsed[1].name, "alsa/plughw:CARD=USB,DEV=0");
717 assert_eq!(parsed[1].description, "Listener's USB (stereo)");
718 let dir = tempfile::tempdir().unwrap();
719 let mut config = crate::test_support::config(dir.path());
720 let socket = std::path::Path::new("/tmp/radio.sock");
721 let original: Vec<_> = playback_command(&config, socket)
722 .get_args()
723 .map(|a| a.to_owned())
724 .collect();
725 config.settings.audio_device = Some(String::new());
726 assert_eq!(
727 playback_command(&config, socket)
728 .get_args()
729 .collect::<Vec<_>>(),
730 original
731 );
732 config.settings.audio_device = Some(parsed[1].name.clone());
733 let command = playback_command(&config, socket);
734 let args: Vec<_> = command.get_args().collect();
735 assert_eq!(&args[..original.len()], original);
736 assert_eq!(
737 args.last().unwrap(),
738 &"--audio-device=alsa/plughw:CARD=USB,DEV=0"
739 );
740 }
741
742 #[test]
743 fn normalization_changes_only_the_opt_in_filter_argument() {
744 let dir = tempfile::tempdir().unwrap();
745 let mut config = crate::test_support::config(dir.path());
746 let socket = std::path::Path::new("/tmp/radio-test.sock");
747 let command = playback_command(&config, socket);
748 let original: Vec<_> = command
749 .get_args()
750 .map(|a| a.to_string_lossy().into_owned())
751 .collect();
752 assert_eq!(
753 original,
754 vec![
755 "--no-config",
756 "--load-scripts=no",
757 "--no-video",
758 "--no-audio-display",
759 "--terminal=no",
760 "--input-default-bindings=no",
761 "--idle=yes",
762 "--keep-open=no",
763 "--cache=yes",
764 "--cache-secs=3",
765 "--demuxer-max-bytes=2097152",
766 "--demuxer-max-back-bytes=524288",
767 "--demuxer-donate-buffer=no",
768 "--audio-buffer=0.2",
769 &format!("--user-agent={}", crate::USER_AGENT),
770 "--volume=80",
771 "--network-timeout=12",
772 "--input-ipc-server=/tmp/radio-test.sock",
773 ]
774 );
775 config.settings.normalize_loudness = true;
776 let command = playback_command(&config, socket);
777 let enabled: Vec<_> = command
778 .get_args()
779 .map(|a| a.to_string_lossy().into_owned())
780 .collect();
781 assert_eq!(&enabled[..original.len()], original);
782 assert_eq!(&enabled[original.len()..], ["--af=dynaudnorm=f=150:g=5"]);
783 }
784
785 #[test]
786 fn icy_titles_repair_latin1_mojibake_before_sanitizing() {
787 let title = "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - é\u{9b}ªè\u{8a}±\x1b\n";
790 assert_eq!(
791 metadata_title(&json!({"icy-title": title})),
792 "邝美云 - 雪花"
793 );
794 }
795
796 #[test]
797 fn ipc_metadata_keeps_unicode_and_recovers_invalid_gbk_bytes() {
798 let mut line =
799 br#"{"event":"property-change","name":"metadata","data":{"icy-title":""#.to_vec();
800 line.extend_from_slice(b"\xcd\xf5\xb7\xc6 - ");
801 line.extend_from_slice("中文电台".as_bytes());
802 line.extend_from_slice(br#"","title":"File tag"}}"#);
803 let message = parse_ipc_message(&line).unwrap();
804 assert_eq!(message["event"], "property-change");
805 assert_eq!(metadata_title(&message["data"]), "王菲 - 中文电台");
806 assert_eq!(message["data"]["title"], "File tag");
807 assert!(parse_ipc_message(b"{\"data\":\"\xff\"").is_err());
808 }
809
810 #[test]
811 fn ipc_metadata_repairs_gbk_runs_with_valid_utf8_subsequences() {
812 for (raw, expected) in [
813 (b"\xd5\xc5\xb9\xfa\xc8\xd9".as_slice(), "张国荣"),
814 (b"\xba\xd3\xcd\xbc".as_slice(), "河图"),
815 ] {
816 let mut line = br#"{"icy-title":""#.to_vec();
817 line.extend_from_slice(raw);
818 line.extend_from_slice(r#" - Björk(中文)","title":"Café"}"#.as_bytes());
819 let message = parse_ipc_message(&line).unwrap();
820 assert_eq!(
821 metadata_title(&message),
822 format!("{expected} - Björk(中文)")
823 );
824 assert_eq!(message["title"], "Café");
825 }
826 let message = parse_ipc_message(b"{\"icy-title\":\"Caf\xc3\xa9\xff\"}").unwrap();
828 assert_eq!(metadata_title(&message), "Caféÿ");
829
830 for (title, expected) in [("ÕŹúÈÙ", "张国荣"), ("ºÓͼ", "河图")] {
832 assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
833 }
834 }
835
836 #[test]
837 fn icy_titles_repair_gbk_segments_in_mixed_mojibake() {
838 let title = "\u{cd}\u{f5}\u{b7}\u{c6} - (AsiaFM亚洲粤语\u{e5}\u{8f}?)";
842 assert_eq!(
843 metadata_title(&json!({"icy-title": title})),
844 "王菲 - (AsiaFM亚洲粤语�?)"
845 );
846 let lone_pair = "\u{b7}\u{c6} - (AsiaFM亚洲粤语)";
851 assert_eq!(
852 metadata_title(&json!({"icy-title": lone_pair})),
853 "\u{b7}\u{c6} - (AsiaFM亚洲粤语)"
854 );
855 let another_lone_pair = "\u{cd}\u{f5} - (AsiaFM亚洲粤语)";
856 assert_eq!(
857 metadata_title(&json!({"icy-title": another_lone_pair})),
858 "\u{cd}\u{f5} - (AsiaFM亚洲粤语)"
859 );
860 assert_eq!(
862 metadata_title(&json!({"icy-title": "Íõ·Æ\n - Café(中文电台)"})),
863 "王菲 - Café(中文电台)"
864 );
865 }
866
867 #[test]
868 fn icy_titles_repair_latin1_wrapped_gbk() {
869 let title = "ºÓͼ - ×Ï´¨Â¼";
871 assert_eq!(
872 metadata_title(&json!({"icy-title": title})),
873 "河图 - 紫川录"
874 );
875 let title = "Ã©æ± - 中文电台";
877 assert_eq!(
878 metadata_title(&json!({"icy-title": title})),
879 "茅姹 - 中文电台"
880 );
881 assert_eq!(icy_title_bytes(title.as_bytes()), "茅姹 - 中文电台");
882 }
883
884 #[test]
885 fn icy_titles_prefer_utf8_han_prefixes_over_gbk_without_external_han_context() {
886 let title = "ç\u{8e}\u{8b}ä";
890 assert_eq!(metadata_title(&json!({"icy-title": title})), "王�");
891 assert_eq!(icy_title_bytes(title.as_bytes()), "王�");
892 }
893
894 #[test]
895 fn icy_titles_keep_text_without_a_lossless_latin1_repair() {
896 for title in [
897 "Radio Swiss Jazz",
898 "张柏芝 - 乱了感觉",
899 "Café à côté",
900 "Björk - Jóga",
901 "Motörhead - Ace of Spades",
902 "Sigur Rós - Hoppípolla",
903 "ΩΩ - ŹŹ - Ελλάδα - Łódź",
904 "Chloéë",
905 "Chloéë - 中文电台",
906 "Café - 中文电台",
907 "Björk - Jóga(中文)",
908 "Café? - 中文电台",
909 "中文é?",
910 "Lääke - 中文电台",
911 "Lääke - Jää(中文电台)",
912 "éééé - 中文电台",
913 "éé - àà(中文电台)",
914 "Íõ· - 中文电台",
915 "ÖÐÎÄ", "’",
917 ] {
918 assert_eq!(metadata_title(&json!({"icy-title": title})), title);
919 assert_eq!(icy_title_bytes(title.as_bytes()), title);
920 }
921 assert_eq!(metadata_title(&json!({"icy-title": "中文\x1b\n"})), "中文");
922 }
923
924 #[test]
925 fn icy_titles_repair_utf8_runs_before_removing_c1_bytes() {
926 for (title, expected) in [
927 ("Beyoncé - Café", "Beyoncé - Café"),
928 ("Café — Live", "Café — Live"),
929 (
930 "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - 中文电台\x1b\n",
931 "邝美云 - 中文电台",
932 ),
933 ] {
934 assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
935 }
936 }
937
938 #[test]
939 fn icy_title_bytes_preserve_utf8_islands_and_latin1_fallbacks() {
940 let mut raw = b"\xcd\xf5\xb7\xc6 - ".to_vec();
941 raw.extend_from_slice("中文电台".as_bytes());
942 assert_eq!(icy_title_bytes(&raw), "王菲 - 中文电台");
943 let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
944 adjacent.extend_from_slice("中文".as_bytes());
945 assert_eq!(icy_title_bytes(&adjacent), "王菲中文");
946 assert_eq!(icy_title_bytes(b"Beyonc\xe9"), "Beyoncé");
947 assert_eq!(
948 icy_title_bytes(b"\xba\xd3\xcd\xbc - \xd7\xcf\xb4\xa8\xc2\xbc"),
949 "河图 - 紫川录"
950 );
951 assert_eq!(icy_title_bytes(b"Track\x1b\n\xff"), "Trackÿ");
952 }
953
954 #[test]
955 fn damaged_utf8_uses_replacement_characters_without_losing_gbk_or_accents() {
956 let mut raw = "李克".as_bytes().to_vec();
957 raw.extend_from_slice(b"\xe5\x8b?- ");
958 raw.extend_from_slice("飞".as_bytes());
959 raw.extend_from_slice(b"\xe8? (AsiaFM");
960 raw.extend_from_slice("亚洲粤语".as_bytes());
961 raw.extend_from_slice(b"\xe5\x8f?)");
962 let expected = "李克�?- 飞�? (AsiaFM亚洲粤语�?)";
963 assert_eq!(icy_title_bytes(&raw), expected);
964 let mut line = br#"{"icy-title":""#.to_vec();
965 line.extend_from_slice(&raw);
966 line.extend_from_slice(r#"","title":"Björk - Jóga"}"#.as_bytes());
967 let message = parse_ipc_message(&line).unwrap();
968 assert_eq!(metadata_title(&message), expected);
969 assert_eq!(message["title"], "Björk - Jóga");
970
971 let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
972 adjacent.extend_from_slice("中文".as_bytes());
973 adjacent.extend_from_slice(b"\xe8?");
974 assert_eq!(icy_title_bytes(&adjacent), "王菲中文�?");
975 let mut two_byte_lead = "中".as_bytes().to_vec();
977 two_byte_lead.extend_from_slice(b"\xc3?");
978 assert_eq!(icy_title_bytes(&two_byte_lead), "中Ã?");
979 assert_eq!(
980 metadata_title(&json!({"icy-title": "Björk - Jóga(中文)å\u{8f}?"})),
981 "Björk - Jóga(中文)�?"
982 );
983 }
984
985 #[test]
986 fn metadata_titles_preserve_file_tags_and_explicit_empty_icy_titles() {
987 assert_eq!(metadata_title(&json!({"title": "©\x1b\n"})), "©");
990 assert_eq!(
991 metadata_title(&json!({"icy-title": "", "title": "File title"})),
992 ""
993 );
994 assert_eq!(
995 metadata_title(&json!({"icy-title": 1, "title": "File title"})),
996 "File title"
997 );
998 assert_eq!(metadata_title(&json!(null)), "");
999 }
1000
1001 #[test]
1002 fn radioinfo_titles_extract_the_captured_hls_song_before_truncation() {
1003 let title = include_str!("../tests/fixtures/radioinfo-cidade.xml").trim();
1006 assert!(title.chars().count() > 1024);
1007 for key in ["title", "icy-title"] {
1008 assert_eq!(
1009 metadata_title(&json!({key: title})),
1010 "Taylor Swift - The Fate of Ophelia"
1011 );
1012 }
1013 assert_eq!(
1014 icy_title_bytes(title.as_bytes()),
1015 "Taylor Swift - The Fate of Ophelia"
1016 );
1017 }
1018
1019 #[test]
1020 fn radioinfo_titles_decode_entities_and_cdata_without_using_program_fields() {
1021 let title = "\u{feff} <RadioInfo><AnimadorInfo>\
1022 <DB_DALET_ARTIST_NAME>Host</DB_DALET_ARTIST_NAME><TITLE>Show</TITLE>\
1023 </AnimadorInfo><Table><DB_DALET_ARTIST_NAME>Björk & Friends</DB_DALET_ARTIST_NAME>\
1024 <DB_DALET_TITLE_NAME><![CDATA[ Jóga <Live>\n ]]>♥</DB_DALET_TITLE_NAME>\
1025 <DB_SONG_NAME>Other song</DB_SONG_NAME><DB_LEAD_ARTIST_NAME>Other artist</DB_LEAD_ARTIST_NAME>\
1026 </Table></RadioInfo>";
1027 assert_eq!(
1028 metadata_title(&json!({"title": title})),
1029 "Björk & Friends - Jóga <Live> ♥"
1030 );
1031 }
1032
1033 #[test]
1034 fn radioinfo_titles_keep_partial_tracks_and_station_announcements() {
1035 for (fields, expected) in [
1036 (
1037 "<DB_DALET_TITLE_NAME>CIDADE FM-So se quiseres</DB_DALET_TITLE_NAME><DB_SONG_ID>0</DB_SONG_ID>",
1038 "CIDADE FM-So se quiseres",
1039 ),
1040 (
1041 "<DB_DALET_ARTIST_NAME> </DB_DALET_ARTIST_NAME><DB_DALET_TITLE_NAME/><DB_LEAD_ARTIST_NAME>Artist</DB_LEAD_ARTIST_NAME><DB_SONG_NAME>Song</DB_SONG_NAME>",
1042 "Artist - Song",
1043 ),
1044 (
1045 "<DB_DALET_ARTIST_NAME>Artist</DB_DALET_ARTIST_NAME>",
1046 "Artist",
1047 ),
1048 ("<DB_SONG_NAME>Song</DB_SONG_NAME>", "Song"),
1049 ("<DB_RADIO_NAME>Cidade</DB_RADIO_NAME>", ""),
1050 ] {
1051 let title = format!(
1052 "<RadioInfo><Table>{fields}</Table><AnimadorInfo><TITLE>Show</TITLE></AnimadorInfo></RadioInfo>"
1053 );
1054 assert_eq!(metadata_title(&json!({"title": title})), expected);
1055 }
1056 assert_eq!(
1057 metadata_title(
1058 &json!({"icy-title": "", "title": include_str!("../tests/fixtures/radioinfo-cidade.xml")})
1059 ),
1060 ""
1061 );
1062 }
1063
1064 #[test]
1065 fn radioinfo_titles_select_the_first_nonempty_table_without_mixing_records() {
1066 let artist = "<DB_DALET_ARTIST_NAME>Artist A</DB_DALET_ARTIST_NAME>";
1067 let song = "<DB_SONG_NAME>Song B</DB_SONG_NAME>";
1068 let complete = "<DB_DALET_ARTIST_NAME>Artist B</DB_DALET_ARTIST_NAME><DB_SONG_NAME>Song B</DB_SONG_NAME>";
1069 for (tables, expected) in [
1070 (
1071 format!("<Table>{artist}</Table><Table>{complete}</Table>"),
1072 "Artist A",
1073 ),
1074 (
1075 format!("<Table>{song}</Table><Table>{artist}</Table>"),
1076 "Song B",
1077 ),
1078 (
1079 format!("<Table/><Table>{complete}</Table>"),
1080 "Artist B - Song B",
1081 ),
1082 (
1083 format!(
1084 "<Table><DB_RADIO_NAME>Cidade</DB_RADIO_NAME></Table><Table>{complete}</Table>"
1085 ),
1086 "Artist B - Song B",
1087 ),
1088 (
1089 format!("<Table>{complete}</Table><Table>{artist}</Table>"),
1090 "Artist B - Song B",
1091 ),
1092 (
1093 format!("<Table><Table>{artist}</Table>{song}</Table>"),
1094 "Song B",
1095 ),
1096 (
1097 format!("<Other><Table>{artist}</Table></Other><Table>{complete}</Table>"),
1098 "Artist B - Song B",
1099 ),
1100 ] {
1101 let title = format!("<RadioInfo>{tables}</RadioInfo>");
1102 for key in ["title", "icy-title"] {
1103 assert_eq!(metadata_title(&json!({key: title})), expected, "{title}");
1104 }
1105 }
1106 }
1107
1108 #[test]
1109 fn radioinfo_titles_check_the_document_after_selecting_a_table() {
1110 for tail in [
1111 "<Table><DB_SONG_NAME>Unclosed",
1112 "<Other></Broken>",
1113 "<Other>&unknown;</Other>",
1114 "<Other>",
1115 ] {
1116 let title = format!(
1117 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{tail}</RadioInfo>"
1118 );
1119 assert_eq!(metadata_title(&json!({"title": title})), title);
1120 }
1121 }
1122
1123 #[test]
1124 fn radioinfo_titles_reject_invalid_attributes_anywhere_in_the_document() {
1125 for attrs in [
1126 "broken",
1127 "key=unquoted",
1128 "key='one' key='two'",
1129 "key='&unknown;'",
1130 "key='&unterminated'",
1131 "key='<oops'",
1132 "key=\"<oops\"",
1133 ] {
1134 for title in [
1135 format!(
1136 "<RadioInfo {attrs}><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1137 ),
1138 format!(
1139 "<RadioInfo><Table {attrs}><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1140 ),
1141 format!(
1142 "<RadioInfo><Table><DB_SONG_NAME {attrs}>Song</DB_SONG_NAME></Table></RadioInfo>"
1143 ),
1144 format!(
1145 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Other {attrs}/></RadioInfo>"
1146 ),
1147 ] {
1148 for key in ["title", "icy-title"] {
1149 assert_eq!(metadata_title(&json!({key: title})), title);
1150 }
1151 }
1152 }
1153 let title = "<RadioInfo key='&' other=\"<value\"><Table key='one'><DB_SONG_NAME key='♥'>Song</DB_SONG_NAME></Table><Other key='<two'/></RadioInfo>";
1154 assert_eq!(metadata_title(&json!({"title": title})), "Song");
1155 }
1156
1157 #[test]
1158 fn radioinfo_titles_preserve_unknown_or_malformed_metadata_as_text() {
1159 for title in [
1160 "Artist - <Live>",
1161 "<song><title>Song</title></song>",
1162 "<Other><RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo></Other>",
1163 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>",
1164 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Other></RadioInfo>",
1165 "<RadioInfo><Table><DB_SONG_NAME>&unknown;</DB_SONG_NAME></Table></RadioInfo>",
1166 "<!DOCTYPE RadioInfo [<!ENTITY song 'Song'>]><RadioInfo><Table><DB_SONG_NAME>&song;</DB_SONG_NAME></Table></RadioInfo>",
1167 "<RadioInfo/><RadioInfo/>",
1168 "<RadioInfo/>trailing text",
1169 ] {
1170 assert_eq!(metadata_title(&json!({"title": title})), title);
1171 }
1172 }
1173
1174 #[test]
1175 fn radioinfo_titles_bound_parsing_and_sanitize_extracted_text() {
1176 let title = format!(
1177 "<RadioInfo><Table><DB_SONG_NAME>{}</DB_SONG_NAME></Table></RadioInfo>",
1178 "中".repeat(1100)
1179 );
1180 assert_eq!(metadata_title(&json!({"title": title})), "中".repeat(1024));
1181 for title in [
1182 format!(
1183 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Extra>{}</Extra></RadioInfo>",
1184 "x".repeat(64 * 1024)
1185 ),
1186 format!(
1187 "<RadioInfo>{}<Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{}</RadioInfo>",
1188 "<nested>".repeat(32),
1189 "</nested>".repeat(32)
1190 ),
1191 ] {
1192 assert_eq!(
1193 metadata_title(&json!({"title": title})),
1194 crate::clean_text(&title)
1195 );
1196 }
1197 let title = "<RadioInfo><Table><DB_SONG_NAME><![CDATA[Song\x1b[31m]]></DB_SONG_NAME></Table></RadioInfo>";
1198 assert_eq!(metadata_title(&json!({"title": title})), "Song[31m");
1199 }
1200
1201 #[test]
1202 fn icy_titles_are_limited_after_repair() {
1203 let title = "ä¸\u{ad}".repeat(1100);
1204 assert_eq!(
1205 metadata_title(&json!({"icy-title": title})),
1206 "中".repeat(1024)
1207 );
1208 }
1209}