ferrosonic 0.8.1

A terminal-based Subsonic music client with bit-perfect audio playback
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! MPV controller via JSON IPC

use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::task;
use tracing::{debug, info, trace, warn};

use crate::config::paths::mpv_socket_path;
use crate::error::AudioError;

/// Parsed live metadata for an internet radio stream.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RadioMetadata {
    pub title: Option<String>,
    pub artist: Option<String>,
}

/// MPV IPC command
#[derive(Debug, Serialize)]
struct MpvCommand {
    command: Vec<Value>,
    request_id: u64,
}

/// MPV IPC response
#[derive(Debug, Deserialize)]
struct MpvResponse {
    #[serde(default)]
    request_id: Option<u64>,
    #[serde(default)]
    data: Option<Value>,
    #[serde(default)]
    error: String,
}

/// MPV event (used for deserialization and debug tracing)
#[derive(Debug, Deserialize)]
#[allow(dead_code)] // Fields populated by deserialization, read via Debug
struct MpvEvent {
    event: String,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    data: Option<Value>,
}

/// MPV controller
pub struct MpvController {
    /// Path to the IPC socket
    socket_path: PathBuf,
    /// MPV process handle
    process: Option<Child>,
    /// Request ID counter
    request_id: AtomicU64,
    /// Socket connection
    socket: Option<UnixStream>,
}

impl MpvController {
    /// Create a new MPV controller
    pub fn new() -> Self {
        Self {
            socket_path: mpv_socket_path(),
            process: None,
            request_id: AtomicU64::new(1),
            socket: None,
        }
    }

    /// Start MPV process if not running
    pub fn start(&mut self) -> Result<(), AudioError> {
        if self.process.is_some() {
            return Ok(());
        }

        // Remove existing socket if present
        let _ = std::fs::remove_file(&self.socket_path);

        info!("Starting MPV with socket: {}", self.socket_path.display());

        let child = Command::new("mpv")
            .arg("--idle") // Stay running when nothing playing
            .arg("--no-video") // Audio only
            .arg("--no-terminal") // No MPV UI
            .arg("--gapless-audio=yes") // Gapless playback between tracks
            .arg("--prefetch-playlist=yes") // Pre-buffer next track
            .arg("--cache=yes") // Enable cache for network streams
            .arg("--cache-secs=120") // Cache up to 2 minutes ahead
            .arg("--demuxer-max-bytes=100MiB") // Allow large demuxer buffer
            .arg(format!("--input-ipc-server={}", self.socket_path.display()))
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map_err(AudioError::MpvSpawn)?;

        self.process = Some(child);

        // Wait for socket to become available
        task::block_in_place(|| {
            for _ in 0..50 {
                if self.socket_path.exists() {
                    std::thread::sleep(Duration::from_millis(50));
                    break;
                }
                std::thread::sleep(Duration::from_millis(100));
            }
        });

        if !self.socket_path.exists() {
            return Err(AudioError::MpvIpc("Socket not created".to_string()));
        }

        self.connect()?;
        info!("MPV started successfully");
        Ok(())
    }

    /// Connect to the MPV socket
    fn connect(&mut self) -> Result<(), AudioError> {
        let stream = task::block_in_place(|| {
            UnixStream::connect(&self.socket_path).map_err(AudioError::MpvSocket)
        })?;

        // Set read timeout
        stream
            .set_read_timeout(Some(Duration::from_millis(100)))
            .map_err(AudioError::MpvSocket)?;

        self.socket = Some(stream);
        debug!("Connected to MPV socket");
        Ok(())
    }

    /// Check if MPV is running
    pub fn is_running(&mut self) -> bool {
        if self.socket.is_none() {
            return false;
        }
        if let Some(ref mut child) = self.process {
            match child.try_wait() {
                Ok(None) => true,
                Ok(Some(_status)) => {
                    self.socket = None;
                    false
                }
                Err(e) => {
                    warn!("MPV process check failed: {}", e);
                    self.socket = None;
                    false
                }
            }
        } else {
            self.socket = None;
            false
        }
    }

    /// Send a command to MPV
    fn send_command(&mut self, args: Vec<Value>) -> Result<Option<Value>, AudioError> {
        let result = self.try_send_command(args);
        if matches!(
            &result,
            Err(AudioError::MpvIpc(_) | AudioError::MpvSocket(_))
        ) {
            self.socket = None;
        }
        result
    }

    fn try_send_command(&mut self, args: Vec<Value>) -> Result<Option<Value>, AudioError> {
        task::block_in_place(|| {
            let socket = self.socket.as_mut().ok_or(AudioError::MpvNotRunning)?;

            let request_id = self.request_id.fetch_add(1, Ordering::SeqCst);
            let cmd = MpvCommand {
                command: args,
                request_id,
            };

            let json = serde_json::to_string(&cmd)?;
            debug!("Sending MPV command: {}", json);

            writeln!(socket, "{}", json).map_err(|e| AudioError::MpvIpc(e.to_string()))?;
            socket
                .flush()
                .map_err(|e| AudioError::MpvIpc(e.to_string()))?;

            // Read response
            let mut reader = BufReader::new(socket.try_clone().map_err(AudioError::MpvSocket)?);
            let mut line = String::new();

            loop {
                line.clear();
                match reader.read_line(&mut line) {
                    Ok(0) => return Err(AudioError::MpvIpc("Socket closed".to_string())),
                    Ok(_) => {
                        if let Ok(resp) = serde_json::from_str::<MpvResponse>(&line) {
                            if resp.request_id == Some(request_id) {
                                if resp.error != "success" {
                                    return Err(AudioError::MpvCommand(resp.error));
                                }
                                return Ok(resp.data);
                            }
                        }
                        // Log discarded events for diagnostics
                        if let Ok(event) = serde_json::from_str::<MpvEvent>(&line) {
                            trace!("MPV event: {:?}", event);
                        }
                    }
                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(1));
                    }
                    Err(e) => return Err(AudioError::MpvIpc(e.to_string())),
                }
            }
        })
    }

    /// Load and play a file/URL (replaces current playlist)
    pub fn loadfile(&mut self, path: &str) -> Result<(), AudioError> {
        info!("Loading: {}", path.split('?').next().unwrap_or(path));
        self.send_command(vec![json!("loadfile"), json!(path), json!("replace")])?;
        Ok(())
    }

    /// Append a file/URL to the playlist (for gapless playback)
    pub fn loadfile_append(&mut self, path: &str) -> Result<(), AudioError> {
        debug!(
            "Appending to playlist: {}",
            path.split('?').next().unwrap_or(path)
        );
        self.send_command(vec![json!("loadfile"), json!(path), json!("append")])?;
        Ok(())
    }

    /// Remove a specific entry from the playlist by index
    pub fn playlist_remove(&mut self, index: usize) -> Result<(), AudioError> {
        debug!("Removing playlist entry {}", index);
        self.send_command(vec![json!("playlist-remove"), json!(index)])?;
        Ok(())
    }

    /// Get current playlist position (0-indexed)
    pub fn get_playlist_pos(&mut self) -> Result<Option<i64>, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("playlist-pos")])?;
        Ok(data.and_then(|v| v.as_i64()))
    }

    /// Get playlist count
    pub fn get_playlist_count(&mut self) -> Result<usize, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("playlist-count")])?;
        Ok(data.and_then(|v| v.as_u64()).unwrap_or(0) as usize)
    }

    /// Pause playback
    pub fn pause(&mut self) -> Result<(), AudioError> {
        debug!("Pausing playback");
        self.send_command(vec![json!("set_property"), json!("pause"), json!(true)])?;
        Ok(())
    }

    /// Resume playback
    pub fn resume(&mut self) -> Result<(), AudioError> {
        debug!("Resuming playback");
        self.send_command(vec![json!("set_property"), json!("pause"), json!(false)])?;
        Ok(())
    }

    /// Toggle pause
    pub fn toggle_pause(&mut self) -> Result<bool, AudioError> {
        let paused = self.is_paused()?;
        if paused {
            self.resume()?;
        } else {
            self.pause()?;
        }
        Ok(!paused)
    }

    /// Check if paused
    pub fn is_paused(&mut self) -> Result<bool, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("pause")])?;
        Ok(data.and_then(|v| v.as_bool()).unwrap_or(false))
    }

    /// Stop playback
    pub fn stop(&mut self) -> Result<(), AudioError> {
        debug!("Stopping playback");
        self.send_command(vec![json!("stop")])?;
        Ok(())
    }

    /// Seek to position (seconds)
    pub fn seek(&mut self, position: f64) -> Result<(), AudioError> {
        debug!("Seeking to {:.1}s", position);
        self.send_command(vec![json!("seek"), json!(position), json!("absolute")])?;
        Ok(())
    }

    /// Seek relative to current position
    pub fn seek_relative(&mut self, offset: f64) -> Result<(), AudioError> {
        debug!("Seeking {:+.1}s", offset);
        self.send_command(vec![json!("seek"), json!(offset), json!("relative")])?;
        Ok(())
    }

    /// Get current playback position in seconds
    pub fn get_time_pos(&mut self) -> Result<f64, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("time-pos")])?;
        Ok(data.and_then(|v| v.as_f64()).unwrap_or(0.0))
    }

    /// Get total duration in seconds
    pub fn get_duration(&mut self) -> Result<f64, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("duration")])?;
        Ok(data.and_then(|v| v.as_f64()).unwrap_or(0.0))
    }

    /// Set volume (0-100)
    pub fn set_volume(&mut self, volume: i32) -> Result<(), AudioError> {
        debug!("Setting volume to {}", volume);
        self.send_command(vec![
            json!("set_property"),
            json!("volume"),
            json!(volume.clamp(0, 100)),
        ])?;
        Ok(())
    }

    /// Get audio sample rate
    pub fn get_sample_rate(&mut self) -> Result<Option<u32>, AudioError> {
        let data = self.send_command(vec![
            json!("get_property"),
            json!("audio-params/samplerate"),
        ])?;
        Ok(data.and_then(|v| v.as_u64()).map(|v| v as u32))
    }

    /// Get audio bit depth
    pub fn get_bit_depth(&mut self) -> Result<Option<u32>, AudioError> {
        // MPV returns format string like "s16" or "s32"
        let data = self.send_command(vec![json!("get_property"), json!("audio-params/format")])?;
        let format = data.and_then(|v| v.as_str().map(String::from));

        Ok(format.and_then(|f| {
            if f.contains("32") || f.contains("float") {
                Some(32)
            } else if f.contains("24") {
                Some(24)
            } else if f.contains("16") {
                Some(16)
            } else if f.contains("8") {
                Some(8)
            } else {
                None
            }
        }))
    }

    /// Get audio format string
    pub fn get_audio_format(&mut self) -> Result<Option<String>, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("audio-params/format")])?;
        Ok(data.and_then(|v| v.as_str().map(String::from)))
    }

    /// Get audio channel layout
    pub fn get_channels(&mut self) -> Result<Option<String>, AudioError> {
        let data = self.send_command(vec![
            json!("get_property"),
            json!("audio-params/channel-count"),
        ])?;
        let count = data.and_then(|v| v.as_u64()).map(|v| v as u32);

        Ok(count.map(|c| match c {
            1 => "Mono".to_string(),
            2 => "Stereo".to_string(),
            n => format!("{}ch", n),
        }))
    }

    /// Get parsed live metadata for radio streams.
    pub fn get_radio_metadata(&mut self) -> Result<RadioMetadata, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("metadata")])?;
        Ok(data.as_ref().map(parse_radio_metadata).unwrap_or_default())
    }

    /// Check if anything is loaded
    pub fn is_idle(&mut self) -> Result<bool, AudioError> {
        let data = self.send_command(vec![json!("get_property"), json!("idle-active")])?;
        Ok(data.and_then(|v| v.as_bool()).unwrap_or(true))
    }

    /// Quit MPV
    pub fn quit(&mut self) -> Result<(), AudioError> {
        if self.socket.is_some() {
            let _ = self.send_command(vec![json!("quit")]);
        }

        if let Some(mut child) = self.process.take() {
            let _ = child.kill();
            let _ = child.wait();
        }

        self.socket = None;
        let _ = std::fs::remove_file(&self.socket_path);

        info!("MPV shut down");
        Ok(())
    }
}

fn parse_radio_metadata(metadata: &Value) -> RadioMetadata {
    let artist = metadata_string(metadata, "artist");
    let title = metadata_string(metadata, "title");

    if artist.is_some() && title.is_some() {
        return RadioMetadata { title, artist };
    }

    if let Some(icy_title) = metadata_string(metadata, "icy-title") {
        if let Some((artist, title)) = split_icy_title(&icy_title) {
            return RadioMetadata {
                title: Some(title),
                artist: Some(artist),
            };
        }

        return RadioMetadata {
            title: Some(icy_title),
            artist,
        };
    }

    RadioMetadata { title, artist }
}

fn metadata_string(metadata: &Value, key: &str) -> Option<String> {
    metadata
        .get(key)
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string)
}

fn split_icy_title(value: &str) -> Option<(String, String)> {
    let (artist, title) = value.split_once(" - ")?;
    let artist = artist.trim();
    let title = title.trim();
    if artist.is_empty() || title.is_empty() {
        None
    } else {
        Some((artist.to_string(), title.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_artist_and_title_metadata() {
        let metadata = json!({ "artist": "Artist", "title": "Track" });

        assert_eq!(
            parse_radio_metadata(&metadata),
            RadioMetadata {
                title: Some("Track".to_string()),
                artist: Some("Artist".to_string()),
            }
        );
    }

    #[test]
    fn splits_icy_title_artist_title() {
        let metadata = json!({ "icy-title": "Artist - Track" });

        assert_eq!(
            parse_radio_metadata(&metadata),
            RadioMetadata {
                title: Some("Track".to_string()),
                artist: Some("Artist".to_string()),
            }
        );
    }

    #[test]
    fn uses_raw_icy_title_when_unsplittable() {
        let metadata = json!({ "icy-title": "Live Stream Title" });

        assert_eq!(
            parse_radio_metadata(&metadata),
            RadioMetadata {
                title: Some("Live Stream Title".to_string()),
                artist: None,
            }
        );
    }
}

impl Drop for MpvController {
    fn drop(&mut self) {
        let _ = self.quit();
    }
}

impl Default for MpvController {
    fn default() -> Self {
        Self::new()
    }
}