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