Skip to main content

radio_cli/
player.rs

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    // Serialize only probes for this executable, including concurrent starts.
97    // Failed or cancelled subprocesses remain retryable on the next start.
98    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            // Some mpv builds turn invalid bytes into Latin-1 while retaining
136            // valid UTF-8 subsequences (C5 B9 -> Ź inside GBK 张国荣).
137            // Reconstruct that mixed run only when the normal conservative
138            // GBK heuristic accepts it. Like pure Latin-1 runs, mixed Unicode
139            // runs can be false positives (e.g. Ωéé -> 惟殚); this is not
140            // encoding detection.
141            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    // Repair whole non-ASCII runs before UTF-8 chunking: GBK bytes can contain
175    // valid UTF-8 subsequences, which would otherwise hide recoverable bytes.
176    // This fallback applies to every IPC field, including file tags such as
177    // title, not only icy-title. Complete UTF-8 runs remain unchanged.
178    // Do not sanitize JSON here; other fields must retain their Unicode.
179    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        // A lone three/four-byte UTF-8 lead after Han text and before ASCII
189        // suggests a truncated character. Detect this in the raw bytes, so actual
190        // Unicode accents such as "中文é?" remain intact.
191        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    // Repair Latin-1 byte runs before sanitizing: C1 characters can be
204    // UTF-8 continuation bytes. ASCII and existing Unicode delimit runs,
205    // so GBK guesses cannot consume ASCII letters or span separate words.
206    // Latin-1 and wrapped UTF-8 remain ambiguous: a genuine accent followed
207    // by malformed continuation bytes can be reinterpreted as Han text.
208    // A complete UTF-8 Han prefix is repaired even without Han elsewhere.
209    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    // Decode each non-ASCII run independently. Some GBK bytes happen to form
229    // short UTF-8 sequences, so try a complete run before the byte fallback.
230    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    // Existing UTF-8 Han text is stronger evidence than a GBK guess over
249    // the entire run. Preserve it even when adjacent bytes are malformed.
250    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    // Prefer a complete UTF-8 Han prefix over a GBK guess, as decode_icy_run
277    // does for valid Han islands. Mark only the incomplete trailing character;
278    // this evidence comes from the run itself, independently of utf8_han.
279    if let Some(prefix) = incomplete_prefix
280        && prefix.chars().any(is_cjk)
281    {
282        return Cow::Owned(format!("{prefix}\u{fffd}"));
283    }
284
285    // GBK and genuine Latin-1 text overlap. Require a contiguous run of at
286    // least two double-byte Han characters and some evidence beyond letters
287    // (e.g. the symbols in "Íõ·Æ" or "ºÓͼ"). Letter-only runs such as "ää"
288    // and "éééé" stay untouched. This remains a conservative heuristic, not
289    // encoding detection; ambiguous titles may need a source-specific policy.
290    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    // With Han elsewhere in the title, mark a UTF-8 lead and continuation
303    // that remain incomplete after a lossless GBK repair was ruled out.
304    // A lone byte is ambiguous with a genuine accent and stays unchanged.
305    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
318/// `sockaddr_un.sun_path` holds 104 bytes on macOS (108 on Linux) including
319/// the terminating NUL; stay at the lowest common denominator. The default
320/// per-user data directory (`~/Library/Application Support` on macOS) plus a
321/// full UUID socket name could exceed it, so the runtime-directory name keeps
322/// only 12 hex characters; when the runtime directory runs deeper, fall back
323/// to the system temp directory with the full UUID, which stays unguessable
324/// in shared temp dirs. Do not lengthen the runtime-directory name again: the
325/// default macOS path leaves room for little more than the truncation.
326/// Session uniqueness comes from the random suffix; the application allows a
327/// single media session per data directory anyway.
328const 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            // Keep recent packets until playback observes timed ICY metadata.
355            // Disabling the back buffer can lose one-shot title updates.
356            "--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            // The runtime directory and the system temp directory are both
438            // too deep; surface the path so the JSON report shows the culprit.
439            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 mut closed = false;
520        loop {
521            match self.stream.read(&mut buf) {
522                Ok(0) => {
523                    closed = true;
524                    break;
525                }
526                Ok(n) => self.buffer.extend_from_slice(&buf[..n]),
527                Err(e)
528                    if matches!(
529                        e.kind(),
530                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
531                    ) =>
532                {
533                    break;
534                }
535                Err(e) => return Err(e.into()),
536            }
537            if self.buffer.len() > 1024 * 1024 {
538                bail!(DomainError::new(ErrorCode::PlayerMessageTooLarge));
539            }
540            if self.buffer.len() >= 8192 {
541                break;
542            }
543        }
544        while let Some(end) = self.buffer.iter().position(|b| *b == b'\n') {
545            let line: Vec<_> = self.buffer.drain(..=end).collect();
546            let Ok(value) = parse_ipc_message(&line) else {
547                continue;
548            };
549            if let Some(id) = value["request_id"].as_u64() {
550                out.push(Event::Reply(id, value["error"].as_str() == Some("success")));
551            }
552            match value["event"].as_str().unwrap_or("") {
553                "file-loaded" => out.push(Event::Loaded),
554                "playback-restart" => out.push(Event::Playing),
555                "end-file" => {
556                    if value["file_error"]
557                        .as_str()
558                        .is_some_and(|error| error.contains("audio output"))
559                        && let Some(device) = self
560                            .audio_device
561                            .as_deref()
562                            .filter(|s| !s.trim().is_empty())
563                    {
564                        out.push(Event::Failed(
565                            DomainError::new(ErrorCode::AudioDeviceFailed).with("device", device),
566                        ));
567                        continue;
568                    }
569                    out.push(Event::End(
570                        value["reason"].as_str().unwrap_or("unknown").into(),
571                    ));
572                }
573                "property-change" => match value["name"].as_str().unwrap_or("") {
574                    "metadata" => {
575                        let title = metadata_title(&value["data"]);
576                        let title = if self.asiafm_metadata_patch
577                            && value["data"]["icy-title"].is_string()
578                        {
579                            asiafm::title(&title)
580                        } else {
581                            title
582                        };
583                        out.push(Event::Title(title));
584                    }
585                    "time-pos" => out.push(Event::Position(
586                        value["data"]
587                            .as_f64()
588                            .filter(|v| v.is_finite() && *v >= 0.)
589                            .map(|v| (v * 1000.) as u64),
590                    )),
591                    "duration" => out.push(Event::Duration(
592                        value["data"]
593                            .as_f64()
594                            .filter(|v| v.is_finite() && *v > 0.)
595                            .map(|v| (v * 1000.) as u64),
596                    )),
597                    "seekable" => {
598                        out.push(Event::Seekable(value["data"].as_bool().unwrap_or(false)))
599                    }
600                    "pause" => out.push(Event::Paused(value["data"].as_bool().unwrap_or(false))),
601                    "mute" => out.push(Event::Muted(value["data"].as_bool().unwrap_or(false))),
602                    "volume" => out.push(Event::Volume(
603                        value["data"].as_f64().unwrap_or(80.).clamp(0., 100.) as u8,
604                    )),
605                    _ => {}
606                },
607                _ => {}
608            }
609        }
610        // Deliver buffered end-file errors even when mpv closes IPC or exits
611        // immediately afterward; otherwise their structured reason is lost.
612        if out.is_empty() && closed {
613            bail!(DomainError::new(ErrorCode::PlayerClosed));
614        }
615        if out.is_empty() && self.child.try_wait()?.is_some() {
616            bail!(DomainError::new(ErrorCode::PlayerExited));
617        }
618        Ok(out)
619    }
620}
621
622impl Drop for Player {
623    fn drop(&mut self) {
624        let _ = self.command(json!(["quit"]));
625        let deadline = Instant::now() + Duration::from_millis(800);
626        while Instant::now() < deadline {
627            if self.child.try_wait().ok().flatten().is_some() {
628                break;
629            }
630            thread::sleep(Duration::from_millis(20));
631        }
632        let _ = self.child.kill();
633        let _ = self.child.wait();
634        let _ = fs::remove_file(&self.socket);
635    }
636}
637
638#[cfg(test)]
639mod socket_path_tests {
640    use super::{SOCKET_PATH_LIMIT, ipc_socket_path};
641    use std::path::Path;
642
643    #[test]
644    fn prefers_runtime_dir_with_a_short_name() {
645        let dir = Path::new("/tmp/radio-test-run");
646        let path = ipc_socket_path(dir);
647        assert!(path.starts_with(dir));
648        assert!(path.as_os_str().len() <= SOCKET_PATH_LIMIT);
649        let name = path.file_name().unwrap().to_str().unwrap();
650        assert!(name.starts_with("mpv-") && name.ends_with(".sock"));
651    }
652
653    #[test]
654    fn falls_back_to_temp_dir_for_deep_runtime_dirs() {
655        let deep = std::env::temp_dir().join("a".repeat(160));
656        let path = ipc_socket_path(&deep);
657        // The function only guarantees the primary path fits; a fallback path
658        // that is still too long is rejected by the caller's length check.
659        assert!(path.starts_with(std::env::temp_dir()));
660        assert!(!path.starts_with(&deep));
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::{
667        icy_title_bytes, metadata_title, parse_audio_devices, parse_ipc_message, playback_command,
668    };
669    use serde_json::json;
670
671    #[test]
672    fn device_names_preserve_backend_syntax_and_optional_arguments() {
673        let parsed = parse_audio_devices(
674            "List of detected audio devices:\n  'auto' (Autoselect device)\n  'alsa/plughw:CARD=USB,DEV=0' (Listener's USB (stereo))\nignored\n",
675        );
676        assert_eq!(parsed.len(), 2);
677        assert_eq!(parsed[1].name, "alsa/plughw:CARD=USB,DEV=0");
678        assert_eq!(parsed[1].description, "Listener's USB (stereo)");
679        let dir = tempfile::tempdir().unwrap();
680        let mut config = crate::test_support::config(dir.path());
681        let socket = std::path::Path::new("/tmp/radio.sock");
682        let original: Vec<_> = playback_command(&config, socket)
683            .get_args()
684            .map(|a| a.to_owned())
685            .collect();
686        config.settings.audio_device = Some(String::new());
687        assert_eq!(
688            playback_command(&config, socket)
689                .get_args()
690                .collect::<Vec<_>>(),
691            original
692        );
693        config.settings.audio_device = Some(parsed[1].name.clone());
694        let command = playback_command(&config, socket);
695        let args: Vec<_> = command.get_args().collect();
696        assert_eq!(&args[..original.len()], original);
697        assert_eq!(
698            args.last().unwrap(),
699            &"--audio-device=alsa/plughw:CARD=USB,DEV=0"
700        );
701    }
702
703    #[test]
704    fn normalization_changes_only_the_opt_in_filter_argument() {
705        let dir = tempfile::tempdir().unwrap();
706        let mut config = crate::test_support::config(dir.path());
707        let socket = std::path::Path::new("/tmp/radio-test.sock");
708        let command = playback_command(&config, socket);
709        let original: Vec<_> = command
710            .get_args()
711            .map(|a| a.to_string_lossy().into_owned())
712            .collect();
713        assert_eq!(
714            original,
715            vec![
716                "--no-config",
717                "--load-scripts=no",
718                "--no-video",
719                "--no-audio-display",
720                "--terminal=no",
721                "--input-default-bindings=no",
722                "--idle=yes",
723                "--keep-open=no",
724                "--cache=yes",
725                "--cache-secs=3",
726                "--demuxer-max-bytes=2097152",
727                "--demuxer-max-back-bytes=524288",
728                "--demuxer-donate-buffer=no",
729                "--audio-buffer=0.2",
730                &format!("--user-agent={}", crate::USER_AGENT),
731                "--volume=80",
732                "--network-timeout=12",
733                "--input-ipc-server=/tmp/radio-test.sock",
734            ]
735        );
736        config.settings.normalize_loudness = true;
737        let command = playback_command(&config, socket);
738        let enabled: Vec<_> = command
739            .get_args()
740            .map(|a| a.to_string_lossy().into_owned())
741            .collect();
742        assert_eq!(&enabled[..original.len()], original);
743        assert_eq!(&enabled[original.len()..], ["--af=dynaudnorm=f=150:g=5"]);
744    }
745
746    #[test]
747    fn icy_titles_repair_latin1_mojibake_before_sanitizing() {
748        // UTF-8 bytes for "邝美云 - 雪花" were decoded as Latin-1 and then
749        // encoded as UTF-8. The C1 characters must survive until repaired.
750        let title = "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - é\u{9b}ªè\u{8a}±\x1b\n";
751        assert_eq!(
752            metadata_title(&json!({"icy-title": title})),
753            "邝美云 - 雪花"
754        );
755    }
756
757    #[test]
758    fn ipc_metadata_keeps_unicode_and_recovers_invalid_gbk_bytes() {
759        let mut line =
760            br#"{"event":"property-change","name":"metadata","data":{"icy-title":""#.to_vec();
761        line.extend_from_slice(b"\xcd\xf5\xb7\xc6 - ");
762        line.extend_from_slice("中文电台".as_bytes());
763        line.extend_from_slice(br#"","title":"File tag"}}"#);
764        let message = parse_ipc_message(&line).unwrap();
765        assert_eq!(message["event"], "property-change");
766        assert_eq!(metadata_title(&message["data"]), "王菲 - 中文电台");
767        assert_eq!(message["data"]["title"], "File tag");
768        assert!(parse_ipc_message(b"{\"data\":\"\xff\"").is_err());
769    }
770
771    #[test]
772    fn ipc_metadata_repairs_gbk_runs_with_valid_utf8_subsequences() {
773        for (raw, expected) in [
774            (b"\xd5\xc5\xb9\xfa\xc8\xd9".as_slice(), "张国荣"),
775            (b"\xba\xd3\xcd\xbc".as_slice(), "河图"),
776        ] {
777            let mut line = br#"{"icy-title":""#.to_vec();
778            line.extend_from_slice(raw);
779            line.extend_from_slice(r#" - Björk(中文)","title":"Café"}"#.as_bytes());
780            let message = parse_ipc_message(&line).unwrap();
781            assert_eq!(
782                metadata_title(&message),
783                format!("{expected} - Björk(中文)")
784            );
785            assert_eq!(message["title"], "Café");
786        }
787        // A valid accent alongside unrelated invalid bytes stays Unicode.
788        let message = parse_ipc_message(b"{\"icy-title\":\"Caf\xc3\xa9\xff\"}").unwrap();
789        assert_eq!(metadata_title(&message), "Caféÿ");
790
791        // mpv versions which wrap only invalid bytes already send valid JSON.
792        for (title, expected) in [("ÕŹúÈÙ", "张国荣"), ("ºÓͼ", "河图")] {
793            assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
794        }
795    }
796
797    #[test]
798    fn icy_titles_repair_gbk_segments_in_mixed_mojibake() {
799        // AsiaFM sends GBK song text before UTF-8 station text. The final
800        // metadata byte is already a literal question mark and cannot be
801        // recovered from the stream, so only the recoverable part is repaired.
802        let title = "\u{cd}\u{f5}\u{b7}\u{c6} -  (AsiaFM亚洲粤语\u{e5}\u{8f}?)";
803        assert_eq!(
804            metadata_title(&json!({"icy-title": title})),
805            "王菲 -  (AsiaFM亚洲粤语�?)"
806        );
807        // A lone GBK pair decodes to a single character; guessing one
808        // character from two ambiguous bytes is not worth the risk, so such
809        // runs stay untouched. Rejecting a single-character guess is the safe
810        // side: the raw bytes are shown instead of a wrong character.
811        let lone_pair = "\u{b7}\u{c6} -  (AsiaFM亚洲粤语)";
812        assert_eq!(
813            metadata_title(&json!({"icy-title": lone_pair})),
814            "\u{b7}\u{c6} -  (AsiaFM亚洲粤语)"
815        );
816        let another_lone_pair = "\u{cd}\u{f5} -  (AsiaFM亚洲粤语)";
817        assert_eq!(
818            metadata_title(&json!({"icy-title": another_lone_pair})),
819            "\u{cd}\u{f5} -  (AsiaFM亚洲粤语)"
820        );
821        // Ordinary text and controls elsewhere must not veto a good segment.
822        assert_eq!(
823            metadata_title(&json!({"icy-title": "Íõ·Æ\n - Café(中文电台)"})),
824            "王菲 - Café(中文电台)"
825        );
826    }
827
828    #[test]
829    fn icy_titles_repair_latin1_wrapped_gbk() {
830        // A Zeno stream wraps GBK title bytes in Latin-1 and then UTF-8.
831        let title = "ºÓͼ - ×Ï´¨Â¼";
832        assert_eq!(
833            metadata_title(&json!({"icy-title": title})),
834            "河图 - 紫川录"
835        );
836        // GBK can overlap with a valid UTF-8 character and a truncated prefix.
837        let title = "Ã©æ± - 中文电台";
838        assert_eq!(
839            metadata_title(&json!({"icy-title": title})),
840            "茅姹 - 中文电台"
841        );
842        assert_eq!(icy_title_bytes(title.as_bytes()), "茅姹 - 中文电台");
843    }
844
845    #[test]
846    fn icy_titles_prefer_utf8_han_prefixes_over_gbk_without_external_han_context() {
847        // UTF-8 for 王 followed by an incomplete E4 lead, wrapped in Latin-1.
848        // The same bytes form two valid GBK Han characters (鐜嬩), so this
849        // fixes the priority of the UTF-8 prefix rather than the GBK guess.
850        let title = "ç\u{8e}\u{8b}ä";
851        assert_eq!(metadata_title(&json!({"icy-title": title})), "王�");
852        assert_eq!(icy_title_bytes(title.as_bytes()), "王�");
853    }
854
855    #[test]
856    fn icy_titles_keep_text_without_a_lossless_latin1_repair() {
857        for title in [
858            "Radio Swiss Jazz",
859            "张柏芝 - 乱了感觉",
860            "Café à côté",
861            "Björk - Jóga",
862            "Motörhead - Ace of Spades",
863            "Sigur Rós - Hoppípolla",
864            "ΩΩ - ŹŹ - Ελλάδα - Łódź",
865            "Chloéë",
866            "Chloéë - 中文电台",
867            "Café - 中文电台",
868            "Björk - Jóga(中文)",
869            "Café? - 中文电台",
870            "中文é?",
871            "Lääke - 中文电台",
872            "Lääke - Jää(中文电台)",
873            "éééé - 中文电台",
874            "éé - àà(中文电台)",
875            "Íõ· - 中文电台",
876            "ÖÐÎÄ", // Also ambiguous with letter-only Latin-1 text.
877            "’",
878        ] {
879            assert_eq!(metadata_title(&json!({"icy-title": title})), title);
880            assert_eq!(icy_title_bytes(title.as_bytes()), title);
881        }
882        assert_eq!(metadata_title(&json!({"icy-title": "中文\x1b\n"})), "中文");
883    }
884
885    #[test]
886    fn icy_titles_repair_utf8_runs_before_removing_c1_bytes() {
887        for (title, expected) in [
888            ("Beyoncé - Café", "Beyoncé - Café"),
889            ("Café — Live", "Café — Live"),
890            (
891                "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - 中文电台\x1b\n",
892                "邝美云 - 中文电台",
893            ),
894        ] {
895            assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
896        }
897    }
898
899    #[test]
900    fn icy_title_bytes_preserve_utf8_islands_and_latin1_fallbacks() {
901        let mut raw = b"\xcd\xf5\xb7\xc6 - ".to_vec();
902        raw.extend_from_slice("中文电台".as_bytes());
903        assert_eq!(icy_title_bytes(&raw), "王菲 - 中文电台");
904        let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
905        adjacent.extend_from_slice("中文".as_bytes());
906        assert_eq!(icy_title_bytes(&adjacent), "王菲中文");
907        assert_eq!(icy_title_bytes(b"Beyonc\xe9"), "Beyoncé");
908        assert_eq!(
909            icy_title_bytes(b"\xba\xd3\xcd\xbc - \xd7\xcf\xb4\xa8\xc2\xbc"),
910            "河图 - 紫川录"
911        );
912        assert_eq!(icy_title_bytes(b"Track\x1b\n\xff"), "Trackÿ");
913    }
914
915    #[test]
916    fn damaged_utf8_uses_replacement_characters_without_losing_gbk_or_accents() {
917        let mut raw = "李克".as_bytes().to_vec();
918        raw.extend_from_slice(b"\xe5\x8b?- ");
919        raw.extend_from_slice("飞".as_bytes());
920        raw.extend_from_slice(b"\xe8? (AsiaFM");
921        raw.extend_from_slice("亚洲粤语".as_bytes());
922        raw.extend_from_slice(b"\xe5\x8f?)");
923        let expected = "李克�?- 飞�? (AsiaFM亚洲粤语�?)";
924        assert_eq!(icy_title_bytes(&raw), expected);
925        let mut line = br#"{"icy-title":""#.to_vec();
926        line.extend_from_slice(&raw);
927        line.extend_from_slice(r#"","title":"Björk - Jóga"}"#.as_bytes());
928        let message = parse_ipc_message(&line).unwrap();
929        assert_eq!(metadata_title(&message), expected);
930        assert_eq!(message["title"], "Björk - Jóga");
931
932        let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
933        adjacent.extend_from_slice("中文".as_bytes());
934        adjacent.extend_from_slice(b"\xe8?");
935        assert_eq!(icy_title_bytes(&adjacent), "王菲中文�?");
936        // A two-byte lead is ambiguous with Latin-1 and remains untouched.
937        let mut two_byte_lead = "中".as_bytes().to_vec();
938        two_byte_lead.extend_from_slice(b"\xc3?");
939        assert_eq!(icy_title_bytes(&two_byte_lead), "中Ã?");
940        assert_eq!(
941            metadata_title(&json!({"icy-title": "Björk - Jóga(中文)å\u{8f}?"})),
942            "Björk - Jóga(中文)�?"
943        );
944    }
945
946    #[test]
947    fn metadata_titles_preserve_file_tags_and_explicit_empty_icy_titles() {
948        // Valid UTF-8 file tags skip ICY repair. Invalid IPC bytes may already
949        // have been repaired by parse_ipc_message before reaching this point.
950        assert_eq!(metadata_title(&json!({"title": "©\x1b\n"})), "©");
951        assert_eq!(
952            metadata_title(&json!({"icy-title": "", "title": "File title"})),
953            ""
954        );
955        assert_eq!(
956            metadata_title(&json!({"icy-title": 1, "title": "File title"})),
957            "File title"
958        );
959        assert_eq!(metadata_title(&json!(null)), "");
960    }
961
962    #[test]
963    fn radioinfo_titles_extract_the_captured_hls_song_before_truncation() {
964        // Cidade sends this document in both EXTINF and ID3v2 TIT2. It is
965        // longer than clean_text's limit, so parsing must precede sanitizing.
966        let title = include_str!("../tests/fixtures/radioinfo-cidade.xml").trim();
967        assert!(title.chars().count() > 1024);
968        for key in ["title", "icy-title"] {
969            assert_eq!(
970                metadata_title(&json!({key: title})),
971                "Taylor Swift - The Fate of Ophelia"
972            );
973        }
974        assert_eq!(
975            icy_title_bytes(title.as_bytes()),
976            "Taylor Swift - The Fate of Ophelia"
977        );
978    }
979
980    #[test]
981    fn radioinfo_titles_decode_entities_and_cdata_without_using_program_fields() {
982        let title = "\u{feff} <RadioInfo><AnimadorInfo>\
983            <DB_DALET_ARTIST_NAME>Host</DB_DALET_ARTIST_NAME><TITLE>Show</TITLE>\
984            </AnimadorInfo><Table><DB_DALET_ARTIST_NAME>Bj&#246;rk &amp; Friends</DB_DALET_ARTIST_NAME>\
985            <DB_DALET_TITLE_NAME><![CDATA[ Jóga <Live>\n ]]>&#x2665;</DB_DALET_TITLE_NAME>\
986            <DB_SONG_NAME>Other song</DB_SONG_NAME><DB_LEAD_ARTIST_NAME>Other artist</DB_LEAD_ARTIST_NAME>\
987            </Table></RadioInfo>";
988        assert_eq!(
989            metadata_title(&json!({"title": title})),
990            "Björk & Friends - Jóga <Live> ♥"
991        );
992    }
993
994    #[test]
995    fn radioinfo_titles_keep_partial_tracks_and_station_announcements() {
996        for (fields, expected) in [
997            (
998                "<DB_DALET_TITLE_NAME>CIDADE FM-So se quiseres</DB_DALET_TITLE_NAME><DB_SONG_ID>0</DB_SONG_ID>",
999                "CIDADE FM-So se quiseres",
1000            ),
1001            (
1002                "<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>",
1003                "Artist - Song",
1004            ),
1005            (
1006                "<DB_DALET_ARTIST_NAME>Artist</DB_DALET_ARTIST_NAME>",
1007                "Artist",
1008            ),
1009            ("<DB_SONG_NAME>Song</DB_SONG_NAME>", "Song"),
1010            ("<DB_RADIO_NAME>Cidade</DB_RADIO_NAME>", ""),
1011        ] {
1012            let title = format!(
1013                "<RadioInfo><Table>{fields}</Table><AnimadorInfo><TITLE>Show</TITLE></AnimadorInfo></RadioInfo>"
1014            );
1015            assert_eq!(metadata_title(&json!({"title": title})), expected);
1016        }
1017        assert_eq!(
1018            metadata_title(
1019                &json!({"icy-title": "", "title": include_str!("../tests/fixtures/radioinfo-cidade.xml")})
1020            ),
1021            ""
1022        );
1023    }
1024
1025    #[test]
1026    fn radioinfo_titles_select_the_first_nonempty_table_without_mixing_records() {
1027        let artist = "<DB_DALET_ARTIST_NAME>Artist A</DB_DALET_ARTIST_NAME>";
1028        let song = "<DB_SONG_NAME>Song B</DB_SONG_NAME>";
1029        let complete = "<DB_DALET_ARTIST_NAME>Artist B</DB_DALET_ARTIST_NAME><DB_SONG_NAME>Song B</DB_SONG_NAME>";
1030        for (tables, expected) in [
1031            (
1032                format!("<Table>{artist}</Table><Table>{complete}</Table>"),
1033                "Artist A",
1034            ),
1035            (
1036                format!("<Table>{song}</Table><Table>{artist}</Table>"),
1037                "Song B",
1038            ),
1039            (
1040                format!("<Table/><Table>{complete}</Table>"),
1041                "Artist B - Song B",
1042            ),
1043            (
1044                format!(
1045                    "<Table><DB_RADIO_NAME>Cidade</DB_RADIO_NAME></Table><Table>{complete}</Table>"
1046                ),
1047                "Artist B - Song B",
1048            ),
1049            (
1050                format!("<Table>{complete}</Table><Table>{artist}</Table>"),
1051                "Artist B - Song B",
1052            ),
1053            (
1054                format!("<Table><Table>{artist}</Table>{song}</Table>"),
1055                "Song B",
1056            ),
1057            (
1058                format!("<Other><Table>{artist}</Table></Other><Table>{complete}</Table>"),
1059                "Artist B - Song B",
1060            ),
1061        ] {
1062            let title = format!("<RadioInfo>{tables}</RadioInfo>");
1063            for key in ["title", "icy-title"] {
1064                assert_eq!(metadata_title(&json!({key: title})), expected, "{title}");
1065            }
1066        }
1067    }
1068
1069    #[test]
1070    fn radioinfo_titles_check_the_document_after_selecting_a_table() {
1071        for tail in [
1072            "<Table><DB_SONG_NAME>Unclosed",
1073            "<Other></Broken>",
1074            "<Other>&unknown;</Other>",
1075            "<Other>",
1076        ] {
1077            let title = format!(
1078                "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{tail}</RadioInfo>"
1079            );
1080            assert_eq!(metadata_title(&json!({"title": title})), title);
1081        }
1082    }
1083
1084    #[test]
1085    fn radioinfo_titles_reject_invalid_attributes_anywhere_in_the_document() {
1086        for attrs in [
1087            "broken",
1088            "key=unquoted",
1089            "key='one' key='two'",
1090            "key='&unknown;'",
1091            "key='&unterminated'",
1092            "key='<oops'",
1093            "key=\"<oops\"",
1094        ] {
1095            for title in [
1096                format!(
1097                    "<RadioInfo {attrs}><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1098                ),
1099                format!(
1100                    "<RadioInfo><Table {attrs}><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo>"
1101                ),
1102                format!(
1103                    "<RadioInfo><Table><DB_SONG_NAME {attrs}>Song</DB_SONG_NAME></Table></RadioInfo>"
1104                ),
1105                format!(
1106                    "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Other {attrs}/></RadioInfo>"
1107                ),
1108            ] {
1109                for key in ["title", "icy-title"] {
1110                    assert_eq!(metadata_title(&json!({key: title})), title);
1111                }
1112            }
1113        }
1114        let title = "<RadioInfo key='&amp;' other=\"&lt;value\"><Table key='one'><DB_SONG_NAME key='&#x2665;'>Song</DB_SONG_NAME></Table><Other key='&#60;two'/></RadioInfo>";
1115        assert_eq!(metadata_title(&json!({"title": title})), "Song");
1116    }
1117
1118    #[test]
1119    fn radioinfo_titles_preserve_unknown_or_malformed_metadata_as_text() {
1120        for title in [
1121            "Artist - <Live>",
1122            "<song><title>Song</title></song>",
1123            "<Other><RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table></RadioInfo></Other>",
1124            "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>",
1125            "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Other></RadioInfo>",
1126            "<RadioInfo><Table><DB_SONG_NAME>&unknown;</DB_SONG_NAME></Table></RadioInfo>",
1127            "<!DOCTYPE RadioInfo [<!ENTITY song 'Song'>]><RadioInfo><Table><DB_SONG_NAME>&song;</DB_SONG_NAME></Table></RadioInfo>",
1128            "<RadioInfo/><RadioInfo/>",
1129            "<RadioInfo/>trailing text",
1130        ] {
1131            assert_eq!(metadata_title(&json!({"title": title})), title);
1132        }
1133    }
1134
1135    #[test]
1136    fn radioinfo_titles_bound_parsing_and_sanitize_extracted_text() {
1137        let title = format!(
1138            "<RadioInfo><Table><DB_SONG_NAME>{}</DB_SONG_NAME></Table></RadioInfo>",
1139            "中".repeat(1100)
1140        );
1141        assert_eq!(metadata_title(&json!({"title": title})), "中".repeat(1024));
1142        for title in [
1143            format!(
1144                "<RadioInfo><Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table><Extra>{}</Extra></RadioInfo>",
1145                "x".repeat(64 * 1024)
1146            ),
1147            format!(
1148                "<RadioInfo>{}<Table><DB_SONG_NAME>Song</DB_SONG_NAME></Table>{}</RadioInfo>",
1149                "<nested>".repeat(32),
1150                "</nested>".repeat(32)
1151            ),
1152        ] {
1153            assert_eq!(
1154                metadata_title(&json!({"title": title})),
1155                crate::clean_text(&title)
1156            );
1157        }
1158        let title = "<RadioInfo><Table><DB_SONG_NAME><![CDATA[Song\x1b[31m]]></DB_SONG_NAME></Table></RadioInfo>";
1159        assert_eq!(metadata_title(&json!({"title": title})), "Song[31m");
1160    }
1161
1162    #[test]
1163    fn icy_titles_are_limited_after_repair() {
1164        let title = "ä¸\u{ad}".repeat(1100);
1165        assert_eq!(
1166            metadata_title(&json!({"icy-title": title})),
1167            "中".repeat(1024)
1168        );
1169    }
1170}