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
330#[cfg(test)]
331pub(crate) fn radioinfo_title_for_test(text: &str) -> Option<String> {
332 radioinfo::title(text)
333}
334
335#[cfg(test)]
336pub(crate) fn ipc_socket_path_for_test(runtime_dir: &Path) -> PathBuf {
337 ipc_socket_path(runtime_dir)
338}
339
340#[cfg(test)]
341pub(crate) fn parse_ipc_message_for_test(line: &[u8]) -> serde_json::Result<Value> {
342 parse_ipc_message(line)
343}
344
345fn ipc_socket_path(runtime_dir: &Path) -> PathBuf {
346 let id = uuid::Uuid::new_v4().simple().to_string();
347 let primary = runtime_dir.join(format!("mpv-{}.sock", &id[..12]));
348 if primary.as_os_str().len() <= SOCKET_PATH_LIMIT {
349 return primary;
350 }
351 std::env::temp_dir().join(format!("mpv-{id}.sock"))
352}
353
354fn playback_command(config: &Config, socket: &Path) -> Command {
355 let mut command = Command::new(&config.settings.mpv);
356 command
357 .args([
358 "--no-config",
359 "--load-scripts=no",
360 "--no-video",
361 "--no-audio-display",
362 "--terminal=no",
363 "--input-default-bindings=no",
364 "--idle=yes",
365 "--keep-open=no",
366 "--cache=yes",
367 "--cache-secs=3",
368 "--demuxer-max-bytes=2097152",
369 "--demuxer-max-back-bytes=524288",
372 "--demuxer-donate-buffer=no",
373 "--audio-buffer=0.2",
374 ])
375 .arg(format!("--user-agent={USER_AGENT}"))
376 .arg(format!("--volume={}", config.settings.volume))
377 .arg(format!(
378 "--network-timeout={}",
379 config.settings.playback_timeout_secs
380 ))
381 .arg(format!("--input-ipc-server={}", socket.display()))
382 .stdin(Stdio::null())
383 .stdout(Stdio::null())
384 .stderr(Stdio::null());
385 if config.settings.normalize_loudness {
386 command.arg("--af=dynaudnorm=f=150:g=5");
387 }
388 if let Some(device) = config
389 .settings
390 .audio_device
391 .as_deref()
392 .filter(|s| !s.trim().is_empty())
393 {
394 command.arg(format!("--audio-device={device}"));
395 }
396 command
397}
398
399impl Player {
400 pub fn start(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
401 Self::start_station(config, url, "", stop)
402 }
403
404 pub(crate) fn start_station(
405 config: &Config,
406 url: &str,
407 stationuuid: &str,
408 stop: &Arc<AtomicBool>,
409 ) -> Result<Self> {
410 validate_url(url)?;
411 Self::start_input(
412 config,
413 url,
414 stop,
415 asiafm::enabled(&config.settings, stationuuid, url),
416 false,
417 )
418 }
419
420 pub fn start_local(
421 config: &Config,
422 path: &std::path::Path,
423 stop: &Arc<AtomicBool>,
424 ) -> Result<Self> {
425 let path = fs::canonicalize(path)?;
426 let url = reqwest::Url::from_file_path(path)
427 .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?;
428 Self::start_input(config, url.as_str(), stop, false, false)
429 }
430
431 pub fn start_episode(config: &Config, input: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
432 let input = if input.starts_with('/') {
433 reqwest::Url::from_file_path(fs::canonicalize(input)?)
434 .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?
435 .to_string()
436 } else {
437 validate_url(input)?;
438 input.to_owned()
439 };
440 Self::start_input(config, &input, stop, false, true)
441 }
442
443 fn start_input(
444 config: &Config,
445 url: &str,
446 stop: &Arc<AtomicBool>,
447 asiafm_metadata_patch: bool,
448 paused: bool,
449 ) -> Result<Self> {
450 let socket = ipc_socket_path(&config.runtime_dir);
451 if socket.as_os_str().len() > SOCKET_PATH_LIMIT {
452 bail!(DomainError::new(ErrorCode::RuntimePathTooLong).with("path", socket.display()));
455 }
456 if config.settings.normalize_loudness && !supports_normalization(config, stop)? {
457 bail!(DomainError::new(ErrorCode::NormalizationUnavailable));
458 }
459 let mut command = playback_command(config, &socket);
460 if paused {
461 command.arg("--pause=yes");
462 }
463 let mut child = crate::process::spawn_owned(command)
464 .context(DomainError::new(ErrorCode::MissingDependency).with("program", "mpv"))?;
465 let deadline = Instant::now() + Duration::from_secs(10);
466 let stream = loop {
467 if let Ok(stream) = UnixStream::connect(&socket) {
468 break stream;
469 }
470 if child.try_wait()?.is_some()
471 || Instant::now() >= deadline
472 || stop.load(Ordering::Relaxed)
473 {
474 let _ = child.kill();
475 let _ = child.wait();
476 let _ = fs::remove_file(&socket);
477 bail!(DomainError::new(ErrorCode::PlayerStartup));
478 }
479 thread::sleep(Duration::from_millis(20));
480 };
481 stream.set_read_timeout(Some(Duration::from_millis(1)))?;
482 stream.set_write_timeout(Some(Duration::from_secs(1)))?;
483 let mut player = Self {
484 child,
485 stream,
486 socket,
487 buffer: vec![],
488 request: 0,
489 audio_device: config.settings.audio_device.clone(),
490 asiafm_metadata_patch,
491 };
492 for (id, property) in [
493 (1, "metadata"),
494 (2, "pause"),
495 (3, "volume"),
496 (4, "mute"),
497 (5, "time-pos"),
498 (6, "duration"),
499 (7, "seekable"),
500 ] {
501 player.command(json!(["observe_property", id, property]))?;
502 }
503 player.command(json!(["loadfile", url, "replace"]))?;
504 Ok(player)
505 }
506
507 pub fn command(&mut self, command: Value) -> Result<()> {
508 let mut bytes = serde_json::to_vec(&json!({"command":command}))?;
509 bytes.push(b'\n');
510 self.stream.write_all(&bytes)?;
511 Ok(())
512 }
513
514 pub fn request(&mut self, command: Value) -> Result<u64> {
515 self.request += 1;
516 let mut bytes = serde_json::to_vec(&json!({"command":command,"request_id":self.request}))?;
517 bytes.push(b'\n');
518 self.stream.write_all(&bytes)?;
519 Ok(self.request)
520 }
521 pub fn toggle_pause(&mut self) -> Result<()> {
522 self.command(json!(["cycle", "pause"]))
523 }
524 pub fn toggle_mute(&mut self) -> Result<()> {
525 self.command(json!(["cycle", "mute"]))
526 }
527 pub fn volume(&mut self, delta: i32) -> Result<()> {
528 self.command(json!(["add", "volume", delta]))
529 }
530
531 pub fn poll(&mut self) -> Result<Vec<Event>> {
532 let mut out = vec![];
533 let mut buf = [0u8; 8192];
534 let exited = self.child.try_wait()?.is_some();
537 let mut disconnected = None;
538 loop {
539 match self.stream.read(&mut buf) {
540 Ok(0) => {
541 disconnected = Some(ErrorCode::PlayerClosed);
542 break;
543 }
544 Ok(n) => self.buffer.extend_from_slice(&buf[..n]),
545 Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {
546 disconnected = Some(ErrorCode::PlayerClosed);
547 break;
548 }
549 Err(e)
550 if matches!(
551 e.kind(),
552 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
553 ) =>
554 {
555 disconnected = exited.then_some(ErrorCode::PlayerExited);
556 break;
557 }
558 Err(e) => return Err(e.into()),
559 }
560 if self.buffer.len() > 1024 * 1024 {
561 bail!(DomainError::new(ErrorCode::PlayerMessageTooLarge));
562 }
563 if self.buffer.len() >= 8192 {
564 break;
565 }
566 }
567 while let Some(end) = self.buffer.iter().position(|b| *b == b'\n') {
568 let line: Vec<_> = self.buffer.drain(..=end).collect();
569 let Ok(value) = parse_ipc_message(&line) else {
570 continue;
571 };
572 if let Some(id) = value["request_id"].as_u64() {
573 out.push(Event::Reply(id, value["error"].as_str() == Some("success")));
574 }
575 match value["event"].as_str().unwrap_or("") {
576 "file-loaded" => out.push(Event::Loaded),
577 "playback-restart" => out.push(Event::Playing),
578 "end-file" => {
579 if value["file_error"]
580 .as_str()
581 .is_some_and(|error| error.contains("audio output"))
582 && let Some(device) = self
583 .audio_device
584 .as_deref()
585 .filter(|s| !s.trim().is_empty())
586 {
587 out.push(Event::Failed(
588 DomainError::new(ErrorCode::AudioDeviceFailed).with("device", device),
589 ));
590 continue;
591 }
592 out.push(Event::End(
593 value["reason"].as_str().unwrap_or("unknown").into(),
594 ));
595 }
596 "property-change" => match value["name"].as_str().unwrap_or("") {
597 "metadata" => {
598 let title = metadata_title(&value["data"]);
599 let title = if self.asiafm_metadata_patch
600 && value["data"]["icy-title"].is_string()
601 {
602 asiafm::title(&title)
603 } else {
604 title
605 };
606 out.push(Event::Title(title));
607 }
608 "time-pos" => out.push(Event::Position(
609 value["data"]
610 .as_f64()
611 .filter(|v| v.is_finite() && *v >= 0.)
612 .map(|v| (v * 1000.) as u64),
613 )),
614 "duration" => out.push(Event::Duration(
615 value["data"]
616 .as_f64()
617 .filter(|v| v.is_finite() && *v > 0.)
618 .map(|v| (v * 1000.) as u64),
619 )),
620 "seekable" => {
621 out.push(Event::Seekable(value["data"].as_bool().unwrap_or(false)))
622 }
623 "pause" => out.push(Event::Paused(value["data"].as_bool().unwrap_or(false))),
624 "mute" => out.push(Event::Muted(value["data"].as_bool().unwrap_or(false))),
625 "volume" => out.push(Event::Volume(
626 value["data"].as_f64().unwrap_or(80.).clamp(0., 100.) as u8,
627 )),
628 _ => {}
629 },
630 _ => {}
631 }
632 }
633 if out.is_empty()
636 && let Some(code) = disconnected
637 {
638 bail!(DomainError::new(code));
639 }
640 Ok(out)
641 }
642}
643
644impl Drop for Player {
645 fn drop(&mut self) {
646 let _ = self.command(json!(["quit"]));
647 let deadline = Instant::now() + Duration::from_millis(800);
648 while Instant::now() < deadline {
649 if self.child.try_wait().ok().flatten().is_some() {
650 break;
651 }
652 thread::sleep(Duration::from_millis(20));
653 }
654 let _ = self.child.kill();
655 let _ = self.child.wait();
656 let _ = fs::remove_file(&self.socket);
657 }
658}
659
660#[cfg(test)]
661mod socket_path_tests {
662 use super::{SOCKET_PATH_LIMIT, ipc_socket_path};
663 use std::path::Path;
664
665 #[test]
666 fn prefers_runtime_dir_with_a_short_name() {
667 let dir = Path::new("/tmp/radio-test-run");
668 let path = ipc_socket_path(dir);
669 assert!(path.starts_with(dir));
670 assert!(path.as_os_str().len() <= SOCKET_PATH_LIMIT);
671 let name = path.file_name().unwrap().to_str().unwrap();
672 assert!(name.starts_with("mpv-") && name.ends_with(".sock"));
673 }
674
675 #[test]
676 fn falls_back_to_temp_dir_for_deep_runtime_dirs() {
677 let deep = std::env::temp_dir().join("a".repeat(160));
678 let path = ipc_socket_path(&deep);
679 assert!(path.starts_with(std::env::temp_dir()));
682 assert!(!path.starts_with(&deep));
683 }
684}
685
686#[cfg(test)]
687mod tests {
688 use super::{
689 icy_title_bytes, metadata_title, parse_audio_devices, parse_ipc_message, playback_command,
690 };
691 use serde_json::json;
692
693 #[test]
694 fn an_exited_player_delivers_its_final_event_after_a_full_read_buffer() {
695 use std::{io::Write, os::unix::net::UnixStream, process::Command};
696 let (stream, mut peer) = UnixStream::pair().unwrap();
697 let mut child = Command::new("true").spawn().unwrap();
698 child.wait().unwrap();
699 let mut player = super::Player {
700 child,
701 stream,
702 socket: Default::default(),
703 buffer: vec![],
704 request: 0,
705 audio_device: Some("test/fail".into()),
706 asiafm_metadata_patch: false,
707 };
708 peer.write_all(&[b' '; 8191]).unwrap();
710 peer.write_all(b"\n").unwrap();
711 assert!(player.poll().unwrap().is_empty());
712 writeln!(
713 peer,
714 "{}",
715 json!({"event":"end-file","file_error":"audio output initialization failed"})
716 )
717 .unwrap();
718 drop(peer);
719 let events = player.poll().unwrap();
720 assert!(
721 matches!(events.as_slice(), [super::Event::Failed(error)] if error.code == crate::error::ErrorCode::AudioDeviceFailed)
722 );
723 }
724
725 #[test]
726 fn device_names_preserve_backend_syntax_and_optional_arguments() {
727 let parsed = parse_audio_devices(
728 "List of detected audio devices:\n 'auto' (Autoselect device)\n 'alsa/plughw:CARD=USB,DEV=0' (Listener's USB (stereo))\nignored\n",
729 );
730 assert_eq!(parsed.len(), 2);
731 assert_eq!(parsed[1].name, "alsa/plughw:CARD=USB,DEV=0");
732 assert_eq!(parsed[1].description, "Listener's USB (stereo)");
733 let dir = tempfile::tempdir().unwrap();
734 let mut config = crate::test_support::config(dir.path());
735 let socket = std::path::Path::new("/tmp/radio.sock");
736 let original: Vec<_> = playback_command(&config, socket)
737 .get_args()
738 .map(|a| a.to_owned())
739 .collect();
740 config.settings.audio_device = Some(String::new());
741 assert_eq!(
742 playback_command(&config, socket)
743 .get_args()
744 .collect::<Vec<_>>(),
745 original
746 );
747 config.settings.audio_device = Some(parsed[1].name.clone());
748 let command = playback_command(&config, socket);
749 let args: Vec<_> = command.get_args().collect();
750 assert_eq!(&args[..original.len()], original);
751 assert_eq!(
752 args.last().unwrap(),
753 &"--audio-device=alsa/plughw:CARD=USB,DEV=0"
754 );
755 }
756
757 #[test]
758 fn normalization_changes_only_the_opt_in_filter_argument() {
759 let dir = tempfile::tempdir().unwrap();
760 let mut config = crate::test_support::config(dir.path());
761 let socket = std::path::Path::new("/tmp/radio-test.sock");
762 let command = playback_command(&config, socket);
763 let original: Vec<_> = command
764 .get_args()
765 .map(|a| a.to_string_lossy().into_owned())
766 .collect();
767 assert_eq!(
768 original,
769 vec![
770 "--no-config",
771 "--load-scripts=no",
772 "--no-video",
773 "--no-audio-display",
774 "--terminal=no",
775 "--input-default-bindings=no",
776 "--idle=yes",
777 "--keep-open=no",
778 "--cache=yes",
779 "--cache-secs=3",
780 "--demuxer-max-bytes=2097152",
781 "--demuxer-max-back-bytes=524288",
782 "--demuxer-donate-buffer=no",
783 "--audio-buffer=0.2",
784 &format!("--user-agent={}", crate::USER_AGENT),
785 "--volume=80",
786 "--network-timeout=12",
787 "--input-ipc-server=/tmp/radio-test.sock",
788 ]
789 );
790 config.settings.normalize_loudness = true;
791 let command = playback_command(&config, socket);
792 let enabled: Vec<_> = command
793 .get_args()
794 .map(|a| a.to_string_lossy().into_owned())
795 .collect();
796 assert_eq!(&enabled[..original.len()], original);
797 assert_eq!(&enabled[original.len()..], ["--af=dynaudnorm=f=150:g=5"]);
798 }
799
800 #[test]
801 fn icy_titles_repair_latin1_mojibake_before_sanitizing() {
802 let title = "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - é\u{9b}ªè\u{8a}±\x1b\n";
805 assert_eq!(
806 metadata_title(&json!({"icy-title": title})),
807 "邝美云 - 雪花"
808 );
809 }
810
811 #[test]
812 fn ipc_metadata_keeps_unicode_and_recovers_invalid_gbk_bytes() {
813 let mut line =
814 br#"{"event":"property-change","name":"metadata","data":{"icy-title":""#.to_vec();
815 line.extend_from_slice(b"\xcd\xf5\xb7\xc6 - ");
816 line.extend_from_slice("中文电台".as_bytes());
817 line.extend_from_slice(br#"","title":"File tag"}}"#);
818 let message = parse_ipc_message(&line).unwrap();
819 assert_eq!(message["event"], "property-change");
820 assert_eq!(metadata_title(&message["data"]), "王菲 - 中文电台");
821 assert_eq!(message["data"]["title"], "File tag");
822 assert!(parse_ipc_message(b"{\"data\":\"\xff\"").is_err());
823 }
824
825 #[test]
826 fn ipc_metadata_repairs_gbk_runs_with_valid_utf8_subsequences() {
827 for (raw, expected) in [
828 (b"\xd5\xc5\xb9\xfa\xc8\xd9".as_slice(), "张国荣"),
829 (b"\xba\xd3\xcd\xbc".as_slice(), "河图"),
830 ] {
831 let mut line = br#"{"icy-title":""#.to_vec();
832 line.extend_from_slice(raw);
833 line.extend_from_slice(r#" - Björk(中文)","title":"Café"}"#.as_bytes());
834 let message = parse_ipc_message(&line).unwrap();
835 assert_eq!(
836 metadata_title(&message),
837 format!("{expected} - Björk(中文)")
838 );
839 assert_eq!(message["title"], "Café");
840 }
841 let message = parse_ipc_message(b"{\"icy-title\":\"Caf\xc3\xa9\xff\"}").unwrap();
843 assert_eq!(metadata_title(&message), "Caféÿ");
844
845 for (title, expected) in [("ÕŹúÈÙ", "张国荣"), ("ºÓͼ", "河图")] {
847 assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
848 }
849 }
850
851 #[test]
852 fn icy_titles_repair_gbk_segments_in_mixed_mojibake() {
853 let title = "\u{cd}\u{f5}\u{b7}\u{c6} - (AsiaFM亚洲粤语\u{e5}\u{8f}?)";
857 assert_eq!(
858 metadata_title(&json!({"icy-title": title})),
859 "王菲 - (AsiaFM亚洲粤语�?)"
860 );
861 let lone_pair = "\u{b7}\u{c6} - (AsiaFM亚洲粤语)";
866 assert_eq!(
867 metadata_title(&json!({"icy-title": lone_pair})),
868 "\u{b7}\u{c6} - (AsiaFM亚洲粤语)"
869 );
870 let another_lone_pair = "\u{cd}\u{f5} - (AsiaFM亚洲粤语)";
871 assert_eq!(
872 metadata_title(&json!({"icy-title": another_lone_pair})),
873 "\u{cd}\u{f5} - (AsiaFM亚洲粤语)"
874 );
875 assert_eq!(
877 metadata_title(&json!({"icy-title": "Íõ·Æ\n - Café(中文电台)"})),
878 "王菲 - Café(中文电台)"
879 );
880 }
881
882 #[test]
883 fn icy_titles_repair_latin1_wrapped_gbk() {
884 let title = "ºÓͼ - ×Ï´¨Â¼";
886 assert_eq!(
887 metadata_title(&json!({"icy-title": title})),
888 "河图 - 紫川录"
889 );
890 let title = "Ã©æ± - 中文电台";
892 assert_eq!(
893 metadata_title(&json!({"icy-title": title})),
894 "茅姹 - 中文电台"
895 );
896 assert_eq!(icy_title_bytes(title.as_bytes()), "茅姹 - 中文电台");
897 }
898
899 #[test]
900 fn icy_titles_prefer_utf8_han_prefixes_over_gbk_without_external_han_context() {
901 let title = "ç\u{8e}\u{8b}ä";
905 assert_eq!(metadata_title(&json!({"icy-title": title})), "王�");
906 assert_eq!(icy_title_bytes(title.as_bytes()), "王�");
907 }
908
909 #[test]
910 fn icy_titles_keep_text_without_a_lossless_latin1_repair() {
911 for title in [
912 "Radio Swiss Jazz",
913 "张柏芝 - 乱了感觉",
914 "Café à côté",
915 "Björk - Jóga",
916 "Motörhead - Ace of Spades",
917 "Sigur Rós - Hoppípolla",
918 "ΩΩ - ŹŹ - Ελλάδα - Łódź",
919 "Chloéë",
920 "Chloéë - 中文电台",
921 "Café - 中文电台",
922 "Björk - Jóga(中文)",
923 "Café? - 中文电台",
924 "中文é?",
925 "Lääke - 中文电台",
926 "Lääke - Jää(中文电台)",
927 "éééé - 中文电台",
928 "éé - àà(中文电台)",
929 "Íõ· - 中文电台",
930 "ÖÐÎÄ", "’",
932 ] {
933 assert_eq!(metadata_title(&json!({"icy-title": title})), title);
934 assert_eq!(icy_title_bytes(title.as_bytes()), title);
935 }
936 assert_eq!(metadata_title(&json!({"icy-title": "中文\x1b\n"})), "中文");
937 }
938
939 #[test]
940 fn icy_titles_repair_utf8_runs_before_removing_c1_bytes() {
941 for (title, expected) in [
942 ("Beyoncé - Café", "Beyoncé - Café"),
943 ("Café — Live", "Café — Live"),
944 (
945 "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - 中文电台\x1b\n",
946 "邝美云 - 中文电台",
947 ),
948 ] {
949 assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
950 }
951 }
952
953 #[test]
954 fn icy_title_bytes_preserve_utf8_islands_and_latin1_fallbacks() {
955 let mut raw = b"\xcd\xf5\xb7\xc6 - ".to_vec();
956 raw.extend_from_slice("中文电台".as_bytes());
957 assert_eq!(icy_title_bytes(&raw), "王菲 - 中文电台");
958 let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
959 adjacent.extend_from_slice("中文".as_bytes());
960 assert_eq!(icy_title_bytes(&adjacent), "王菲中文");
961 assert_eq!(icy_title_bytes(b"Beyonc\xe9"), "Beyoncé");
962 assert_eq!(
963 icy_title_bytes(b"\xba\xd3\xcd\xbc - \xd7\xcf\xb4\xa8\xc2\xbc"),
964 "河图 - 紫川录"
965 );
966 assert_eq!(icy_title_bytes(b"Track\x1b\n\xff"), "Trackÿ");
967 }
968
969 #[test]
970 fn damaged_utf8_uses_replacement_characters_without_losing_gbk_or_accents() {
971 let mut raw = "李克".as_bytes().to_vec();
972 raw.extend_from_slice(b"\xe5\x8b?- ");
973 raw.extend_from_slice("飞".as_bytes());
974 raw.extend_from_slice(b"\xe8? (AsiaFM");
975 raw.extend_from_slice("亚洲粤语".as_bytes());
976 raw.extend_from_slice(b"\xe5\x8f?)");
977 let expected = "李克�?- 飞�? (AsiaFM亚洲粤语�?)";
978 assert_eq!(icy_title_bytes(&raw), expected);
979 let mut line = br#"{"icy-title":""#.to_vec();
980 line.extend_from_slice(&raw);
981 line.extend_from_slice(r#"","title":"Björk - Jóga"}"#.as_bytes());
982 let message = parse_ipc_message(&line).unwrap();
983 assert_eq!(metadata_title(&message), expected);
984 assert_eq!(message["title"], "Björk - Jóga");
985
986 let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
987 adjacent.extend_from_slice("中文".as_bytes());
988 adjacent.extend_from_slice(b"\xe8?");
989 assert_eq!(icy_title_bytes(&adjacent), "王菲中文�?");
990 let mut two_byte_lead = "中".as_bytes().to_vec();
992 two_byte_lead.extend_from_slice(b"\xc3?");
993 assert_eq!(icy_title_bytes(&two_byte_lead), "中Ã?");
994 assert_eq!(
995 metadata_title(&json!({"icy-title": "Björk - Jóga(中文)å\u{8f}?"})),
996 "Björk - Jóga(中文)�?"
997 );
998 }
999
1000 #[test]
1001 fn metadata_titles_preserve_file_tags_and_explicit_empty_icy_titles() {
1002 assert_eq!(metadata_title(&json!({"title": "©\x1b\n"})), "©");
1005 assert_eq!(
1006 metadata_title(&json!({"icy-title": "", "title": "File title"})),
1007 ""
1008 );
1009 assert_eq!(
1010 metadata_title(&json!({"icy-title": 1, "title": "File title"})),
1011 "File title"
1012 );
1013 assert_eq!(metadata_title(&json!(null)), "");
1014 }
1015
1016 #[test]
1017 fn radioinfo_titles_extract_the_captured_hls_song_before_truncation() {
1018 let title = include_str!("../tests/fixtures/radioinfo-cidade.xml").trim();
1021 assert!(title.chars().count() > 1024);
1022 for key in ["title", "icy-title"] {
1023 assert_eq!(
1024 metadata_title(&json!({key: title})),
1025 "Taylor Swift - The Fate of Ophelia"
1026 );
1027 }
1028 assert_eq!(
1029 icy_title_bytes(title.as_bytes()),
1030 "Taylor Swift - The Fate of Ophelia"
1031 );
1032 }
1033
1034 #[test]
1035 fn radioinfo_titles_decode_entities_and_cdata_without_using_program_fields() {
1036 let title = "\u{feff} <RadioInfo><AnimadorInfo>\
1037 <DB_DALET_ARTIST_NAME>Host</DB_DALET_ARTIST_NAME><TITLE>Show</TITLE>\
1038 </AnimadorInfo><Table><DB_DALET_ARTIST_NAME>Björk & Friends</DB_DALET_ARTIST_NAME>\
1039 <DB_DALET_TITLE_NAME><![CDATA[ Jóga <Live>\n ]]>♥</DB_DALET_TITLE_NAME>\
1040 <DB_SONG_NAME>Other song</DB_SONG_NAME><DB_LEAD_ARTIST_NAME>Other artist</DB_LEAD_ARTIST_NAME>\
1041 </Table></RadioInfo>";
1042 assert_eq!(
1043 metadata_title(&json!({"title": title})),
1044 "Björk & Friends - Jóga <Live> ♥"
1045 );
1046 }
1047
1048 #[test]
1049 fn radioinfo_titles_keep_partial_tracks_and_station_announcements() {
1050 for (fields, expected) in [
1051 (
1052 "<DB_DALET_TITLE_NAME>CIDADE FM-So se quiseres</DB_DALET_TITLE_NAME><DB_SONG_ID>0</DB_SONG_ID>",
1053 "CIDADE FM-So se quiseres",
1054 ),
1055 (
1056 "<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>",
1057 "Artist - Song",
1058 ),
1059 (
1060 "<DB_DALET_ARTIST_NAME>Artist</DB_DALET_ARTIST_NAME>",
1061 "Artist",
1062 ),
1063 ("<DB_SONG_NAME>Song</DB_SONG_NAME>", "Song"),
1064 ("<DB_RADIO_NAME>Cidade</DB_RADIO_NAME>", ""),
1065 ] {
1066 let title = format!(
1067 "<RadioInfo><Table>{fields}</Table><AnimadorInfo><TITLE>Show</TITLE></AnimadorInfo></RadioInfo>"
1068 );
1069 assert_eq!(metadata_title(&json!({"title": title})), expected);
1070 }
1071 assert_eq!(
1072 metadata_title(
1073 &json!({"icy-title": "", "title": include_str!("../tests/fixtures/radioinfo-cidade.xml")})
1074 ),
1075 ""
1076 );
1077 }
1078
1079 #[test]
1080 fn radioinfo_titles_select_the_first_nonempty_table_without_mixing_records() {
1081 let artist = "<DB_DALET_ARTIST_NAME>Artist A</DB_DALET_ARTIST_NAME>";
1082 let song = "<DB_SONG_NAME>Song B</DB_SONG_NAME>";
1083 let complete = "<DB_DALET_ARTIST_NAME>Artist B</DB_DALET_ARTIST_NAME><DB_SONG_NAME>Song B</DB_SONG_NAME>";
1084 for (tables, expected) in [
1085 (
1086 format!("<Table>{artist}</Table><Table>{complete}</Table>"),
1087 "Artist A",
1088 ),
1089 (
1090 format!("<Table>{song}</Table><Table>{artist}</Table>"),
1091 "Song B",
1092 ),
1093 (
1094 format!("<Table/><Table>{complete}</Table>"),
1095 "Artist B - Song B",
1096 ),
1097 (
1098 format!(
1099 "<Table><DB_RADIO_NAME>Cidade</DB_RADIO_NAME></Table><Table>{complete}</Table>"
1100 ),
1101 "Artist B - Song B",
1102 ),
1103 (
1104 format!("<Table>{complete}</Table><Table>{artist}</Table>"),
1105 "Artist B - Song B",
1106 ),
1107 (
1108 format!("<Table><Table>{artist}</Table>{song}</Table>"),
1109 "Song B",
1110 ),
1111 (
1112 format!("<Other><Table>{artist}</Table></Other><Table>{complete}</Table>"),
1113 "Artist B - Song B",
1114 ),
1115 ] {
1116 let title = format!("<RadioInfo>{tables}</RadioInfo>");
1117 for key in ["title", "icy-title"] {
1118 assert_eq!(metadata_title(&json!({key: title})), expected, "{title}");
1119 }
1120 }
1121 }
1122
1123 #[test]
1124 fn radioinfo_titles_check_the_document_after_selecting_a_table() {
1125 for tail in [
1126 "<Table><DB_SONG_NAME>Unclosed",
1127 "<Other></Broken>",
1128 "<Other>&unknown;</Other>",
1129 "<Other>",
1130 ] {
1131 let title = format!(
1132 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{tail}</RadioInfo>"
1133 );
1134 assert_eq!(metadata_title(&json!({"title": title})), title);
1135 }
1136 }
1137
1138 #[test]
1139 fn radioinfo_titles_reject_invalid_attributes_anywhere_in_the_document() {
1140 for attrs in [
1141 "broken",
1142 "key=unquoted",
1143 "key='one' key='two'",
1144 "key='&unknown;'",
1145 "key='&unterminated'",
1146 "key='<oops'",
1147 "key=\"<oops\"",
1148 ] {
1149 for title in [
1150 format!(
1151 "<RadioInfo {attrs}><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1152 ),
1153 format!(
1154 "<RadioInfo><Table {attrs}><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1155 ),
1156 format!(
1157 "<RadioInfo><Table><DB_SONG_NAME {attrs}>Song</DB_SONG_NAME></Table></RadioInfo>"
1158 ),
1159 format!(
1160 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Other {attrs}/></RadioInfo>"
1161 ),
1162 ] {
1163 for key in ["title", "icy-title"] {
1164 assert_eq!(metadata_title(&json!({key: title})), title);
1165 }
1166 }
1167 }
1168 let title = "<RadioInfo key='&' other=\"<value\"><Table key='one'><DB_SONG_NAME key='♥'>Song</DB_SONG_NAME></Table><Other key='<two'/></RadioInfo>";
1169 assert_eq!(metadata_title(&json!({"title": title})), "Song");
1170 }
1171
1172 #[test]
1173 fn radioinfo_titles_preserve_unknown_or_malformed_metadata_as_text() {
1174 for title in [
1175 "Artist - <Live>",
1176 "<song><title>Song</title></song>",
1177 "<Other><RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo></Other>",
1178 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>",
1179 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Other></RadioInfo>",
1180 "<RadioInfo><Table><DB_SONG_NAME>&unknown;</DB_SONG_NAME></Table></RadioInfo>",
1181 "<!DOCTYPE RadioInfo [<!ENTITY song 'Song'>]><RadioInfo><Table><DB_SONG_NAME>&song;</DB_SONG_NAME></Table></RadioInfo>",
1182 "<RadioInfo/><RadioInfo/>",
1183 "<RadioInfo/>trailing text",
1184 ] {
1185 assert_eq!(metadata_title(&json!({"title": title})), title);
1186 }
1187 }
1188
1189 #[test]
1190 fn radioinfo_titles_bound_parsing_and_sanitize_extracted_text() {
1191 let title = format!(
1192 "<RadioInfo><Table><DB_SONG_NAME>{}</DB_SONG_NAME></Table></RadioInfo>",
1193 "中".repeat(1100)
1194 );
1195 assert_eq!(metadata_title(&json!({"title": title})), "中".repeat(1024));
1196 for title in [
1197 format!(
1198 "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Extra>{}</Extra></RadioInfo>",
1199 "x".repeat(64 * 1024)
1200 ),
1201 format!(
1202 "<RadioInfo>{}<Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{}</RadioInfo>",
1203 "<nested>".repeat(32),
1204 "</nested>".repeat(32)
1205 ),
1206 ] {
1207 assert_eq!(
1208 metadata_title(&json!({"title": title})),
1209 crate::clean_text(&title)
1210 );
1211 }
1212 let title = "<RadioInfo><Table><DB_SONG_NAME><![CDATA[Song\x1b[31m]]></DB_SONG_NAME></Table></RadioInfo>";
1213 assert_eq!(metadata_title(&json!({"title": title})), "Song[31m");
1214 }
1215
1216 #[test]
1217 fn icy_titles_are_limited_after_repair() {
1218 let title = "ä¸\u{ad}".repeat(1100);
1219 assert_eq!(
1220 metadata_title(&json!({"icy-title": title})),
1221 "中".repeat(1024)
1222 );
1223 }
1224}