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;
25
26#[derive(Debug)]
27pub enum Event {
28    Playing,
29    Title(String),
30    End(String),
31    Failed(DomainError),
32    Paused(bool),
33    Volume(u8),
34    Muted(bool),
35}
36
37pub struct Player {
38    child: Child,
39    stream: UnixStream,
40    socket: PathBuf,
41    buffer: Vec<u8>,
42    audio_device: Option<String>,
43    asiafm_metadata_patch: bool,
44}
45
46#[derive(Debug, serde::Serialize)]
47pub struct AudioDevice {
48    pub name: String,
49    pub description: String,
50}
51
52fn parse_audio_devices(output: &str) -> Vec<AudioDevice> {
53    output
54        .lines()
55        .filter_map(|line| {
56            let line = line.trim().strip_prefix('\'')?;
57            let (name, description) = line.rsplit_once("' (")?;
58            Some(AudioDevice {
59                name: name.into(),
60                description: description.strip_suffix(')')?.into(),
61            })
62        })
63        .collect()
64}
65
66pub fn audio_devices(config: &Config, stop: &Arc<AtomicBool>) -> Result<Vec<AudioDevice>> {
67    let output = crate::process::output(
68        Command::new(&config.settings.mpv).args(["--no-config", "--audio-device=help"]),
69        Duration::from_secs(3),
70        stop,
71    )?;
72    let devices = parse_audio_devices(&String::from_utf8_lossy(&output));
73    if devices.is_empty() {
74        bail!(DomainError::new(ErrorCode::AudioDevicesUnavailable));
75    }
76    Ok(devices)
77}
78
79fn supports_normalization(config: &Config, stop: &Arc<AtomicBool>) -> Result<bool> {
80    type Probe = Arc<Mutex<Option<bool>>>;
81    static PROBES: OnceLock<Mutex<HashMap<String, Probe>>> = OnceLock::new();
82    let probe = PROBES
83        .get_or_init(Mutex::default)
84        .lock()
85        .unwrap()
86        .entry(config.settings.mpv.clone())
87        .or_default()
88        .clone();
89    // Serialize only probes for this executable, including concurrent starts.
90    // Failed or cancelled subprocesses remain retryable on the next start.
91    let mut cached = probe.lock().unwrap();
92    if let Some(supported) = *cached {
93        return Ok(supported);
94    }
95    let filters = crate::process::output(
96        Command::new(&config.settings.mpv).args(["--no-config", "--af=help"]),
97        Duration::from_secs(3),
98        stop,
99    )?;
100    let supported = String::from_utf8_lossy(&filters)
101        .lines()
102        .any(|line| line.split_whitespace().next() == Some("dynaudnorm"));
103    *cached = Some(supported);
104    Ok(supported)
105}
106
107fn metadata_title(metadata: &Value) -> String {
108    let Some(title) = metadata["icy-title"].as_str() else {
109        return crate::clean_text(metadata["title"].as_str().unwrap_or(""));
110    };
111    icy_title(&repair_mpv_gbk_runs(title))
112}
113
114fn repair_mpv_gbk_runs(title: &str) -> String {
115    let mut repaired = String::with_capacity(title.len());
116    let mut start = 0;
117    for (end, character) in title
118        .char_indices()
119        .chain(std::iter::once((title.len(), ' ')))
120    {
121        if character.is_ascii() || is_cjk(character) || !character.is_alphabetic() {
122            let run = &title[start..end];
123            // Some mpv builds turn invalid bytes into Latin-1 while retaining
124            // valid UTF-8 subsequences (C5 B9 -> Ź inside GBK 张国荣).
125            // Reconstruct that mixed run only when the normal conservative
126            // GBK heuristic accepts it. Like pure Latin-1 runs, mixed Unicode
127            // runs can be false positives (e.g. Ωéé -> 惟殚); this is not
128            // encoding detection.
129            if run.chars().any(|c| c > '\u{ff}') && run.chars().any(|c| c <= '\u{ff}') {
130                let mut bytes = Vec::new();
131                for c in run.chars() {
132                    if c <= '\u{ff}' {
133                        bytes.push(c as u8);
134                    } else {
135                        bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
136                    }
137                }
138                let latin1: String = bytes.iter().map(|&byte| char::from(byte)).collect();
139                if let Cow::Owned(decoded) = repair_latin1_run(&latin1, false)
140                    && decoded.chars().all(is_cjk)
141                {
142                    repaired.push_str(&decoded);
143                } else {
144                    repaired.push_str(run);
145                }
146            } else {
147                repaired.push_str(run);
148            }
149            if end < title.len() {
150                repaired.push(character);
151                start = end + character.len_utf8();
152            }
153        }
154    }
155    repaired
156}
157
158fn parse_ipc_message(line: &[u8]) -> serde_json::Result<Value> {
159    if let Ok(valid) = std::str::from_utf8(line) {
160        return serde_json::from_str(valid);
161    }
162    // Repair whole non-ASCII runs before UTF-8 chunking: GBK bytes can contain
163    // valid UTF-8 subsequences, which would otherwise hide recoverable bytes.
164    // This fallback applies to every IPC field, including file tags such as
165    // title, not only icy-title. Complete UTF-8 runs remain unchanged.
166    // Do not sanitize JSON here; other fields must retain their Unicode.
167    let decoded = decode_metadata_bytes(line);
168    serde_json::from_str(&decoded)
169}
170
171fn push_metadata_bytes(bytes: &[u8], text: &mut String) {
172    let mut offset = 0;
173    for chunk in bytes.utf8_chunks() {
174        text.push_str(chunk.valid());
175        offset += chunk.valid().len() + chunk.invalid().len();
176        // A lone three/four-byte UTF-8 lead after Han text and before ASCII
177        // suggests a truncated character. Detect this in the raw bytes, so actual
178        // Unicode accents such as "中文é?" remain intact.
179        if matches!(chunk.invalid(), [0xe0..=0xf4])
180            && chunk.valid().chars().next_back().is_some_and(is_cjk)
181            && bytes.get(offset).is_none_or(u8::is_ascii)
182        {
183            text.push('\u{fffd}');
184        } else {
185            text.extend(chunk.invalid().iter().map(|&byte| char::from(byte)));
186        }
187    }
188}
189
190pub(crate) fn icy_title(title: &str) -> String {
191    // Repair Latin-1 byte runs before sanitizing: C1 characters can be
192    // UTF-8 continuation bytes. ASCII and existing Unicode delimit runs,
193    // so GBK guesses cannot consume ASCII letters or span separate words.
194    // Latin-1 and wrapped UTF-8 remain ambiguous: a genuine accent followed
195    // by malformed continuation bytes can be reinterpreted as Han text.
196    // A complete UTF-8 Han prefix is repaired even without Han elsewhere.
197    let mut repaired = String::with_capacity(title.len());
198    let utf8_han = title.chars().any(is_cjk);
199    let mut start = 0;
200    for (index, character) in title.char_indices() {
201        if !matches!(character, '\u{80}'..='\u{ff}') {
202            repaired.push_str(&repair_latin1_run(&title[start..index], utf8_han));
203            repaired.push(character);
204            start = index + character.len_utf8();
205        }
206    }
207    repaired.push_str(&repair_latin1_run(&title[start..], utf8_han));
208    crate::clean_text(&repaired)
209}
210
211pub(crate) fn icy_title_bytes(bytes: &[u8]) -> String {
212    icy_title(&decode_metadata_bytes(bytes))
213}
214
215fn decode_metadata_bytes(bytes: &[u8]) -> String {
216    // Decode each non-ASCII run independently. Some GBK bytes happen to form
217    // short UTF-8 sequences, so try a complete run before the byte fallback.
218    let mut title = String::with_capacity(bytes.len());
219    let mut start = 0;
220    for (index, &byte) in bytes.iter().enumerate() {
221        if byte.is_ascii() {
222            decode_icy_run(&bytes[start..index], &mut title);
223            title.push(char::from(byte));
224            start = index + 1;
225        }
226    }
227    decode_icy_run(&bytes[start..], &mut title);
228    title
229}
230
231fn decode_icy_run(bytes: &[u8], title: &mut String) {
232    if let Ok(valid) = std::str::from_utf8(bytes) {
233        title.push_str(valid);
234        return;
235    }
236    // Existing UTF-8 Han text is stronger evidence than a GBK guess over
237    // the entire run. Preserve it even when adjacent bytes are malformed.
238    let has_utf8_han = bytes
239        .utf8_chunks()
240        .any(|chunk| chunk.valid().chars().any(is_cjk));
241    if !has_utf8_han {
242        let latin1: String = bytes.iter().map(|&byte| char::from(byte)).collect();
243        if let Cow::Owned(repaired) = repair_latin1_run(&latin1, false) {
244            title.push_str(&repaired);
245            return;
246        }
247    }
248    push_metadata_bytes(bytes, title);
249}
250
251fn repair_latin1_run(run: &str, utf8_han: bool) -> Cow<'_, str> {
252    if run.is_empty() {
253        return Cow::Borrowed(run);
254    }
255    let bytes: Vec<u8> = run.chars().map(|c| c as u8).collect();
256    let error = match std::str::from_utf8(&bytes) {
257        Ok(repaired) => return Cow::Owned(repaired.to_owned()),
258        Err(error) => error,
259    };
260    let incomplete_prefix = error
261        .error_len()
262        .is_none()
263        .then(|| std::str::from_utf8(&bytes[..error.valid_up_to()]).unwrap());
264    // Prefer a complete UTF-8 Han prefix over a GBK guess, as decode_icy_run
265    // does for valid Han islands. Mark only the incomplete trailing character;
266    // this evidence comes from the run itself, independently of utf8_han.
267    if let Some(prefix) = incomplete_prefix
268        && prefix.chars().any(is_cjk)
269    {
270        return Cow::Owned(format!("{prefix}\u{fffd}"));
271    }
272
273    // GBK and genuine Latin-1 text overlap. Require a contiguous run of at
274    // least two double-byte Han characters and some evidence beyond letters
275    // (e.g. the symbols in "Íõ·Æ" or "ºÓͼ"). Letter-only runs such as "ää"
276    // and "éééé" stay untouched. This remains a conservative heuristic, not
277    // encoding detection; ambiguous titles may need a source-specific policy.
278    if bytes.len() >= 4
279        && run
280            .chars()
281            .any(|c| !c.is_alphabetic() && !c.is_control() && !c.is_whitespace())
282        && let Some(decoded) =
283            encoding_rs::GB18030.decode_without_bom_handling_and_without_replacement(&bytes)
284        && decoded.chars().all(is_cjk)
285        && decoded.chars().count() * 2 == bytes.len()
286    {
287        return Cow::Owned(decoded.into_owned());
288    }
289
290    // With Han elsewhere in the title, mark a UTF-8 lead and continuation
291    // that remain incomplete after a lossless GBK repair was ruled out.
292    // A lone byte is ambiguous with a genuine accent and stays unchanged.
293    if let Some(prefix) = incomplete_prefix
294        && utf8_han
295        && bytes.len() - prefix.len() >= 2
296    {
297        return Cow::Owned(format!("{prefix}\u{fffd}"));
298    }
299    Cow::Borrowed(run)
300}
301
302fn is_cjk(character: char) -> bool {
303    matches!(character, '\u{3400}'..='\u{9fff}' | '\u{f900}'..='\u{faff}')
304}
305
306/// `sockaddr_un.sun_path` holds 104 bytes on macOS (108 on Linux) including
307/// the terminating NUL; stay at the lowest common denominator. The default
308/// per-user data directory (`~/Library/Application Support` on macOS) plus a
309/// full UUID socket name could exceed it, so the runtime-directory name keeps
310/// only 12 hex characters; when the runtime directory runs deeper, fall back
311/// to the system temp directory with the full UUID, which stays unguessable
312/// in shared temp dirs. Do not lengthen the runtime-directory name again: the
313/// default macOS path leaves room for little more than the truncation.
314/// Session uniqueness comes from the random suffix; the application allows a
315/// single media session per data directory anyway.
316const SOCKET_PATH_LIMIT: usize = 100;
317
318fn ipc_socket_path(runtime_dir: &Path) -> PathBuf {
319    let id = uuid::Uuid::new_v4().simple().to_string();
320    let primary = runtime_dir.join(format!("mpv-{}.sock", &id[..12]));
321    if primary.as_os_str().len() <= SOCKET_PATH_LIMIT {
322        return primary;
323    }
324    std::env::temp_dir().join(format!("mpv-{id}.sock"))
325}
326
327fn playback_command(config: &Config, socket: &Path) -> Command {
328    let mut command = Command::new(&config.settings.mpv);
329    command
330        .args([
331            "--no-config",
332            "--load-scripts=no",
333            "--no-video",
334            "--no-audio-display",
335            "--terminal=no",
336            "--input-default-bindings=no",
337            "--idle=yes",
338            "--keep-open=no",
339            "--cache=yes",
340            "--cache-secs=3",
341            "--demuxer-max-bytes=2097152",
342            // Keep recent packets until playback observes timed ICY metadata.
343            // Disabling the back buffer can lose one-shot title updates.
344            "--demuxer-max-back-bytes=524288",
345            "--demuxer-donate-buffer=no",
346            "--audio-buffer=0.2",
347        ])
348        .arg(format!("--user-agent={USER_AGENT}"))
349        .arg(format!("--volume={}", config.settings.volume))
350        .arg(format!(
351            "--network-timeout={}",
352            config.settings.playback_timeout_secs
353        ))
354        .arg(format!("--input-ipc-server={}", socket.display()))
355        .stdin(Stdio::null())
356        .stdout(Stdio::null())
357        .stderr(Stdio::null());
358    if config.settings.normalize_loudness {
359        command.arg("--af=dynaudnorm=f=150:g=5");
360    }
361    if let Some(device) = config
362        .settings
363        .audio_device
364        .as_deref()
365        .filter(|s| !s.trim().is_empty())
366    {
367        command.arg(format!("--audio-device={device}"));
368    }
369    command
370}
371
372impl Player {
373    pub fn start(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Self> {
374        Self::start_station(config, url, "", stop)
375    }
376
377    pub(crate) fn start_station(
378        config: &Config,
379        url: &str,
380        stationuuid: &str,
381        stop: &Arc<AtomicBool>,
382    ) -> Result<Self> {
383        validate_url(url)?;
384        Self::start_input(
385            config,
386            url,
387            stop,
388            asiafm::enabled(&config.settings, stationuuid, url),
389        )
390    }
391
392    pub fn start_local(
393        config: &Config,
394        path: &std::path::Path,
395        stop: &Arc<AtomicBool>,
396    ) -> Result<Self> {
397        let path = fs::canonicalize(path)?;
398        let url = reqwest::Url::from_file_path(path)
399            .map_err(|_| DomainError::new(ErrorCode::InvalidUrl))?;
400        Self::start_input(config, url.as_str(), stop, false)
401    }
402
403    fn start_input(
404        config: &Config,
405        url: &str,
406        stop: &Arc<AtomicBool>,
407        asiafm_metadata_patch: bool,
408    ) -> Result<Self> {
409        let socket = ipc_socket_path(&config.runtime_dir);
410        if socket.as_os_str().len() > SOCKET_PATH_LIMIT {
411            // The runtime directory and the system temp directory are both
412            // too deep; surface the path so the JSON report shows the culprit.
413            bail!(DomainError::new(ErrorCode::RuntimePathTooLong).with("path", socket.display()));
414        }
415        if config.settings.normalize_loudness && !supports_normalization(config, stop)? {
416            bail!(DomainError::new(ErrorCode::NormalizationUnavailable));
417        }
418        let command = playback_command(config, &socket);
419        let mut child = crate::process::spawn_owned(command)
420            .context(DomainError::new(ErrorCode::MissingDependency).with("program", "mpv"))?;
421        let deadline = Instant::now() + Duration::from_secs(3);
422        let stream = loop {
423            if let Ok(stream) = UnixStream::connect(&socket) {
424                break stream;
425            }
426            if child.try_wait()?.is_some()
427                || Instant::now() >= deadline
428                || stop.load(Ordering::Relaxed)
429            {
430                let _ = child.kill();
431                let _ = child.wait();
432                let _ = fs::remove_file(&socket);
433                bail!(DomainError::new(ErrorCode::PlayerStartup));
434            }
435            thread::sleep(Duration::from_millis(20));
436        };
437        stream.set_read_timeout(Some(Duration::from_millis(1)))?;
438        stream.set_write_timeout(Some(Duration::from_secs(1)))?;
439        let mut player = Self {
440            child,
441            stream,
442            socket,
443            buffer: vec![],
444            audio_device: config.settings.audio_device.clone(),
445            asiafm_metadata_patch,
446        };
447        for (id, property) in [(1, "metadata"), (2, "pause"), (3, "volume"), (4, "mute")] {
448            player.command(json!(["observe_property", id, property]))?;
449        }
450        player.command(json!(["loadfile", url, "replace"]))?;
451        Ok(player)
452    }
453
454    pub fn command(&mut self, command: Value) -> Result<()> {
455        let mut bytes = serde_json::to_vec(&json!({"command":command}))?;
456        bytes.push(b'\n');
457        self.stream.write_all(&bytes)?;
458        Ok(())
459    }
460
461    pub fn toggle_pause(&mut self) -> Result<()> {
462        self.command(json!(["cycle", "pause"]))
463    }
464    pub fn toggle_mute(&mut self) -> Result<()> {
465        self.command(json!(["cycle", "mute"]))
466    }
467    pub fn volume(&mut self, delta: i32) -> Result<()> {
468        self.command(json!(["add", "volume", delta]))
469    }
470
471    pub fn poll(&mut self) -> Result<Vec<Event>> {
472        let mut out = vec![];
473        let mut buf = [0u8; 8192];
474        let mut closed = false;
475        loop {
476            match self.stream.read(&mut buf) {
477                Ok(0) => {
478                    closed = true;
479                    break;
480                }
481                Ok(n) => self.buffer.extend_from_slice(&buf[..n]),
482                Err(e)
483                    if matches!(
484                        e.kind(),
485                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
486                    ) =>
487                {
488                    break;
489                }
490                Err(e) => return Err(e.into()),
491            }
492            if self.buffer.len() > 1024 * 1024 {
493                bail!(DomainError::new(ErrorCode::PlayerMessageTooLarge));
494            }
495            if self.buffer.len() >= 8192 {
496                break;
497            }
498        }
499        while let Some(end) = self.buffer.iter().position(|b| *b == b'\n') {
500            let line: Vec<_> = self.buffer.drain(..=end).collect();
501            let Ok(value) = parse_ipc_message(&line) else {
502                continue;
503            };
504            match value["event"].as_str().unwrap_or("") {
505                "playback-restart" => out.push(Event::Playing),
506                "end-file" => {
507                    if value["file_error"]
508                        .as_str()
509                        .is_some_and(|error| error.contains("audio output"))
510                        && let Some(device) = self
511                            .audio_device
512                            .as_deref()
513                            .filter(|s| !s.trim().is_empty())
514                    {
515                        out.push(Event::Failed(
516                            DomainError::new(ErrorCode::AudioDeviceFailed).with("device", device),
517                        ));
518                        continue;
519                    }
520                    out.push(Event::End(
521                        value["reason"].as_str().unwrap_or("unknown").into(),
522                    ));
523                }
524                "property-change" => match value["name"].as_str().unwrap_or("") {
525                    "metadata" => {
526                        let title = metadata_title(&value["data"]);
527                        let title = if self.asiafm_metadata_patch
528                            && value["data"]["icy-title"].is_string()
529                        {
530                            asiafm::title(&title)
531                        } else {
532                            title
533                        };
534                        out.push(Event::Title(title));
535                    }
536                    "pause" => out.push(Event::Paused(value["data"].as_bool().unwrap_or(false))),
537                    "mute" => out.push(Event::Muted(value["data"].as_bool().unwrap_or(false))),
538                    "volume" => out.push(Event::Volume(
539                        value["data"].as_f64().unwrap_or(80.).clamp(0., 100.) as u8,
540                    )),
541                    _ => {}
542                },
543                _ => {}
544            }
545        }
546        // Deliver buffered end-file errors even when mpv closes IPC or exits
547        // immediately afterward; otherwise their structured reason is lost.
548        if out.is_empty() && closed {
549            bail!(DomainError::new(ErrorCode::PlayerClosed));
550        }
551        if out.is_empty() && self.child.try_wait()?.is_some() {
552            bail!(DomainError::new(ErrorCode::PlayerExited));
553        }
554        Ok(out)
555    }
556}
557
558impl Drop for Player {
559    fn drop(&mut self) {
560        let _ = self.command(json!(["quit"]));
561        let deadline = Instant::now() + Duration::from_millis(800);
562        while Instant::now() < deadline {
563            if self.child.try_wait().ok().flatten().is_some() {
564                break;
565            }
566            thread::sleep(Duration::from_millis(20));
567        }
568        let _ = self.child.kill();
569        let _ = self.child.wait();
570        let _ = fs::remove_file(&self.socket);
571    }
572}
573
574#[cfg(test)]
575mod socket_path_tests {
576    use super::{SOCKET_PATH_LIMIT, ipc_socket_path};
577    use std::path::Path;
578
579    #[test]
580    fn prefers_runtime_dir_with_a_short_name() {
581        let dir = Path::new("/tmp/radio-test-run");
582        let path = ipc_socket_path(dir);
583        assert!(path.starts_with(dir));
584        assert!(path.as_os_str().len() <= SOCKET_PATH_LIMIT);
585        let name = path.file_name().unwrap().to_str().unwrap();
586        assert!(name.starts_with("mpv-") && name.ends_with(".sock"));
587    }
588
589    #[test]
590    fn falls_back_to_temp_dir_for_deep_runtime_dirs() {
591        let deep = std::env::temp_dir().join("a".repeat(160));
592        let path = ipc_socket_path(&deep);
593        // The function only guarantees the primary path fits; a fallback path
594        // that is still too long is rejected by the caller's length check.
595        assert!(path.starts_with(std::env::temp_dir()));
596        assert!(!path.starts_with(&deep));
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::{
603        icy_title_bytes, metadata_title, parse_audio_devices, parse_ipc_message, playback_command,
604    };
605    use serde_json::json;
606
607    #[test]
608    fn device_names_preserve_backend_syntax_and_optional_arguments() {
609        let parsed = parse_audio_devices(
610            "List of detected audio devices:\n  'auto' (Autoselect device)\n  'alsa/plughw:CARD=USB,DEV=0' (Listener's USB (stereo))\nignored\n",
611        );
612        assert_eq!(parsed.len(), 2);
613        assert_eq!(parsed[1].name, "alsa/plughw:CARD=USB,DEV=0");
614        assert_eq!(parsed[1].description, "Listener's USB (stereo)");
615        let dir = tempfile::tempdir().unwrap();
616        let mut config = crate::test_support::config(dir.path());
617        let socket = std::path::Path::new("/tmp/radio.sock");
618        let original: Vec<_> = playback_command(&config, socket)
619            .get_args()
620            .map(|a| a.to_owned())
621            .collect();
622        config.settings.audio_device = Some(String::new());
623        assert_eq!(
624            playback_command(&config, socket)
625                .get_args()
626                .collect::<Vec<_>>(),
627            original
628        );
629        config.settings.audio_device = Some(parsed[1].name.clone());
630        let command = playback_command(&config, socket);
631        let args: Vec<_> = command.get_args().collect();
632        assert_eq!(&args[..original.len()], original);
633        assert_eq!(
634            args.last().unwrap(),
635            &"--audio-device=alsa/plughw:CARD=USB,DEV=0"
636        );
637    }
638
639    #[test]
640    fn normalization_changes_only_the_opt_in_filter_argument() {
641        let dir = tempfile::tempdir().unwrap();
642        let mut config = crate::test_support::config(dir.path());
643        let socket = std::path::Path::new("/tmp/radio-test.sock");
644        let command = playback_command(&config, socket);
645        let original: Vec<_> = command
646            .get_args()
647            .map(|a| a.to_string_lossy().into_owned())
648            .collect();
649        assert_eq!(
650            original,
651            vec![
652                "--no-config",
653                "--load-scripts=no",
654                "--no-video",
655                "--no-audio-display",
656                "--terminal=no",
657                "--input-default-bindings=no",
658                "--idle=yes",
659                "--keep-open=no",
660                "--cache=yes",
661                "--cache-secs=3",
662                "--demuxer-max-bytes=2097152",
663                "--demuxer-max-back-bytes=524288",
664                "--demuxer-donate-buffer=no",
665                "--audio-buffer=0.2",
666                &format!("--user-agent={}", crate::USER_AGENT),
667                "--volume=80",
668                "--network-timeout=12",
669                "--input-ipc-server=/tmp/radio-test.sock",
670            ]
671        );
672        config.settings.normalize_loudness = true;
673        let command = playback_command(&config, socket);
674        let enabled: Vec<_> = command
675            .get_args()
676            .map(|a| a.to_string_lossy().into_owned())
677            .collect();
678        assert_eq!(&enabled[..original.len()], original);
679        assert_eq!(&enabled[original.len()..], ["--af=dynaudnorm=f=150:g=5"]);
680    }
681
682    #[test]
683    fn icy_titles_repair_latin1_mojibake_before_sanitizing() {
684        // UTF-8 bytes for "邝美云 - 雪花" were decoded as Latin-1 and then
685        // encoded as UTF-8. The C1 characters must survive until repaired.
686        let title = "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - é\u{9b}ªè\u{8a}±\x1b\n";
687        assert_eq!(
688            metadata_title(&json!({"icy-title": title})),
689            "邝美云 - 雪花"
690        );
691    }
692
693    #[test]
694    fn ipc_metadata_keeps_unicode_and_recovers_invalid_gbk_bytes() {
695        let mut line =
696            br#"{"event":"property-change","name":"metadata","data":{"icy-title":""#.to_vec();
697        line.extend_from_slice(b"\xcd\xf5\xb7\xc6 - ");
698        line.extend_from_slice("中文电台".as_bytes());
699        line.extend_from_slice(br#"","title":"File tag"}}"#);
700        let message = parse_ipc_message(&line).unwrap();
701        assert_eq!(message["event"], "property-change");
702        assert_eq!(metadata_title(&message["data"]), "王菲 - 中文电台");
703        assert_eq!(message["data"]["title"], "File tag");
704        assert!(parse_ipc_message(b"{\"data\":\"\xff\"").is_err());
705    }
706
707    #[test]
708    fn ipc_metadata_repairs_gbk_runs_with_valid_utf8_subsequences() {
709        for (raw, expected) in [
710            (b"\xd5\xc5\xb9\xfa\xc8\xd9".as_slice(), "张国荣"),
711            (b"\xba\xd3\xcd\xbc".as_slice(), "河图"),
712        ] {
713            let mut line = br#"{"icy-title":""#.to_vec();
714            line.extend_from_slice(raw);
715            line.extend_from_slice(r#" - Björk(中文)","title":"Café"}"#.as_bytes());
716            let message = parse_ipc_message(&line).unwrap();
717            assert_eq!(
718                metadata_title(&message),
719                format!("{expected} - Björk(中文)")
720            );
721            assert_eq!(message["title"], "Café");
722        }
723        // A valid accent alongside unrelated invalid bytes stays Unicode.
724        let message = parse_ipc_message(b"{\"icy-title\":\"Caf\xc3\xa9\xff\"}").unwrap();
725        assert_eq!(metadata_title(&message), "Caféÿ");
726
727        // mpv versions which wrap only invalid bytes already send valid JSON.
728        for (title, expected) in [("ÕŹúÈÙ", "张国荣"), ("ºÓͼ", "河图")] {
729            assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
730        }
731    }
732
733    #[test]
734    fn icy_titles_repair_gbk_segments_in_mixed_mojibake() {
735        // AsiaFM sends GBK song text before UTF-8 station text. The final
736        // metadata byte is already a literal question mark and cannot be
737        // recovered from the stream, so only the recoverable part is repaired.
738        let title = "\u{cd}\u{f5}\u{b7}\u{c6} -  (AsiaFM亚洲粤语\u{e5}\u{8f}?)";
739        assert_eq!(
740            metadata_title(&json!({"icy-title": title})),
741            "王菲 -  (AsiaFM亚洲粤语�?)"
742        );
743        // A lone GBK pair decodes to a single character; guessing one
744        // character from two ambiguous bytes is not worth the risk, so such
745        // runs stay untouched. Rejecting a single-character guess is the safe
746        // side: the raw bytes are shown instead of a wrong character.
747        let lone_pair = "\u{b7}\u{c6} -  (AsiaFM亚洲粤语)";
748        assert_eq!(
749            metadata_title(&json!({"icy-title": lone_pair})),
750            "\u{b7}\u{c6} -  (AsiaFM亚洲粤语)"
751        );
752        let another_lone_pair = "\u{cd}\u{f5} -  (AsiaFM亚洲粤语)";
753        assert_eq!(
754            metadata_title(&json!({"icy-title": another_lone_pair})),
755            "\u{cd}\u{f5} -  (AsiaFM亚洲粤语)"
756        );
757        // Ordinary text and controls elsewhere must not veto a good segment.
758        assert_eq!(
759            metadata_title(&json!({"icy-title": "Íõ·Æ\n - Café(中文电台)"})),
760            "王菲 - Café(中文电台)"
761        );
762    }
763
764    #[test]
765    fn icy_titles_repair_latin1_wrapped_gbk() {
766        // A Zeno stream wraps GBK title bytes in Latin-1 and then UTF-8.
767        let title = "ºÓͼ - ×Ï´¨Â¼";
768        assert_eq!(
769            metadata_title(&json!({"icy-title": title})),
770            "河图 - 紫川录"
771        );
772        // GBK can overlap with a valid UTF-8 character and a truncated prefix.
773        let title = "Ã©æ± - 中文电台";
774        assert_eq!(
775            metadata_title(&json!({"icy-title": title})),
776            "茅姹 - 中文电台"
777        );
778        assert_eq!(icy_title_bytes(title.as_bytes()), "茅姹 - 中文电台");
779    }
780
781    #[test]
782    fn icy_titles_prefer_utf8_han_prefixes_over_gbk_without_external_han_context() {
783        // UTF-8 for 王 followed by an incomplete E4 lead, wrapped in Latin-1.
784        // The same bytes form two valid GBK Han characters (鐜嬩), so this
785        // fixes the priority of the UTF-8 prefix rather than the GBK guess.
786        let title = "ç\u{8e}\u{8b}ä";
787        assert_eq!(metadata_title(&json!({"icy-title": title})), "王�");
788        assert_eq!(icy_title_bytes(title.as_bytes()), "王�");
789    }
790
791    #[test]
792    fn icy_titles_keep_text_without_a_lossless_latin1_repair() {
793        for title in [
794            "Radio Swiss Jazz",
795            "张柏芝 - 乱了感觉",
796            "Café à côté",
797            "Björk - Jóga",
798            "Motörhead - Ace of Spades",
799            "Sigur Rós - Hoppípolla",
800            "ΩΩ - ŹŹ - Ελλάδα - Łódź",
801            "Chloéë",
802            "Chloéë - 中文电台",
803            "Café - 中文电台",
804            "Björk - Jóga(中文)",
805            "Café? - 中文电台",
806            "中文é?",
807            "Lääke - 中文电台",
808            "Lääke - Jää(中文电台)",
809            "éééé - 中文电台",
810            "éé - àà(中文电台)",
811            "Íõ· - 中文电台",
812            "ÖÐÎÄ", // Also ambiguous with letter-only Latin-1 text.
813            "’",
814        ] {
815            assert_eq!(metadata_title(&json!({"icy-title": title})), title);
816            assert_eq!(icy_title_bytes(title.as_bytes()), title);
817        }
818        assert_eq!(metadata_title(&json!({"icy-title": "中文\x1b\n"})), "中文");
819    }
820
821    #[test]
822    fn icy_titles_repair_utf8_runs_before_removing_c1_bytes() {
823        for (title, expected) in [
824            ("Beyoncé - Café", "Beyoncé - Café"),
825            ("Café — Live", "Café — Live"),
826            (
827                "é\u{82}\u{9d}ç¾\u{8e}äº\u{91} - 中文电台\x1b\n",
828                "邝美云 - 中文电台",
829            ),
830        ] {
831            assert_eq!(metadata_title(&json!({"icy-title": title})), expected);
832        }
833    }
834
835    #[test]
836    fn icy_title_bytes_preserve_utf8_islands_and_latin1_fallbacks() {
837        let mut raw = b"\xcd\xf5\xb7\xc6 - ".to_vec();
838        raw.extend_from_slice("中文电台".as_bytes());
839        assert_eq!(icy_title_bytes(&raw), "王菲 - 中文电台");
840        let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
841        adjacent.extend_from_slice("中文".as_bytes());
842        assert_eq!(icy_title_bytes(&adjacent), "王菲中文");
843        assert_eq!(icy_title_bytes(b"Beyonc\xe9"), "Beyoncé");
844        assert_eq!(
845            icy_title_bytes(b"\xba\xd3\xcd\xbc - \xd7\xcf\xb4\xa8\xc2\xbc"),
846            "河图 - 紫川录"
847        );
848        assert_eq!(icy_title_bytes(b"Track\x1b\n\xff"), "Trackÿ");
849    }
850
851    #[test]
852    fn damaged_utf8_uses_replacement_characters_without_losing_gbk_or_accents() {
853        let mut raw = "李克".as_bytes().to_vec();
854        raw.extend_from_slice(b"\xe5\x8b?- ");
855        raw.extend_from_slice("飞".as_bytes());
856        raw.extend_from_slice(b"\xe8? (AsiaFM");
857        raw.extend_from_slice("亚洲粤语".as_bytes());
858        raw.extend_from_slice(b"\xe5\x8f?)");
859        let expected = "李克�?- 飞�? (AsiaFM亚洲粤语�?)";
860        assert_eq!(icy_title_bytes(&raw), expected);
861        let mut line = br#"{"icy-title":""#.to_vec();
862        line.extend_from_slice(&raw);
863        line.extend_from_slice(r#"","title":"Björk - Jóga"}"#.as_bytes());
864        let message = parse_ipc_message(&line).unwrap();
865        assert_eq!(metadata_title(&message), expected);
866        assert_eq!(message["title"], "Björk - Jóga");
867
868        let mut adjacent = b"\xcd\xf5\xb7\xc6".to_vec();
869        adjacent.extend_from_slice("中文".as_bytes());
870        adjacent.extend_from_slice(b"\xe8?");
871        assert_eq!(icy_title_bytes(&adjacent), "王菲中文�?");
872        // A two-byte lead is ambiguous with Latin-1 and remains untouched.
873        let mut two_byte_lead = "中".as_bytes().to_vec();
874        two_byte_lead.extend_from_slice(b"\xc3?");
875        assert_eq!(icy_title_bytes(&two_byte_lead), "中Ã?");
876        assert_eq!(
877            metadata_title(&json!({"icy-title": "Björk - Jóga(中文)å\u{8f}?"})),
878            "Björk - Jóga(中文)�?"
879        );
880    }
881
882    #[test]
883    fn metadata_titles_preserve_file_tags_and_explicit_empty_icy_titles() {
884        // Valid UTF-8 file tags skip ICY repair. Invalid IPC bytes may already
885        // have been repaired by parse_ipc_message before reaching this point.
886        assert_eq!(metadata_title(&json!({"title": "©\x1b\n"})), "©");
887        assert_eq!(
888            metadata_title(&json!({"icy-title": "", "title": "File title"})),
889            ""
890        );
891        assert_eq!(
892            metadata_title(&json!({"icy-title": 1, "title": "File title"})),
893            "File title"
894        );
895        assert_eq!(metadata_title(&json!(null)), "");
896    }
897
898    #[test]
899    fn icy_titles_are_limited_after_repair() {
900        let title = "ä¸\u{ad}".repeat(1100);
901        assert_eq!(
902            metadata_title(&json!({"icy-title": title})),
903            "中".repeat(1024)
904        );
905    }
906}