plexus-mono 0.2.0

Monochrome music API Plexus RPC activation — search, metadata, lyrics, and recommendations
Documentation
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! Playback engine — dedicated audio thread with queue management
//!
//! All rodio interaction is isolated to a single OS thread (OutputStream is !Send).
//! The Sink is Send+Sync and shared via Arc for control from async code.

use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::sync::{watch, Mutex};

use crate::client::MonoClient;
use crate::types::{MonoEvent, PlayStatus, QueuedTrack};

/// Persisted player state — saved to disk so playback can resume across restarts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlayerState {
    pub current_track: Option<QueuedTrack>,
    pub position_secs: f32,
    pub queue: Vec<QueuedTrack>,
    pub history: Vec<QueuedTrack>,
    pub volume: f32,
    #[serde(default = "default_preamp")]
    pub preamp: f32,
}

fn default_preamp() -> f32 {
    1.0
}

impl PlayerState {
    fn state_path() -> PathBuf {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".plexus/monochrome/player/state.json")
    }

    pub fn load() -> Option<Self> {
        let path = Self::state_path();
        let data = std::fs::read_to_string(&path).ok()?;
        serde_json::from_str(&data).ok()
    }

    pub fn save(&self) {
        let path = Self::state_path();
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if let Ok(json) = serde_json::to_string_pretty(self) {
            let _ = std::fs::write(&path, json);
        }
    }
}

/// Helper trait to erase the concrete StreamDownload type behind Box.
/// Rust doesn't allow `dyn Read + Seek + Send` (multiple non-auto traits),
/// so we combine them into one trait and blanket-implement it.
trait ReadSeekSend: std::io::Read + std::io::Seek + Send + Sync {}
impl<T: std::io::Read + std::io::Seek + Send + Sync> ReadSeekSend for T {}

/// Snapshot of current playback state, broadcast via watch channel
#[derive(Debug, Clone)]
pub struct NowPlaying {
    pub track_id: Option<u64>,
    pub title: Option<String>,
    pub artist: Option<String>,
    pub album: Option<String>,
    pub status: PlayStatus,
    pub position_secs: f32,
    pub duration_secs: f32,
    pub volume: f32,
    pub preamp: f32,
    pub queue_length: usize,
    pub url: Option<String>,
}

impl Default for NowPlaying {
    fn default() -> Self {
        Self {
            track_id: None,
            title: None,
            artist: None,
            album: None,
            status: PlayStatus::Idle,
            position_secs: 0.0,
            duration_secs: 0.0,
            volume: 1.0,
            preamp: 1.0,
            queue_length: 0,
            url: None,
        }
    }
}

struct PlayerInner {
    queue: VecDeque<QueuedTrack>,
    current_track: Option<QueuedTrack>,
    status: PlayStatus,
    volume: f32,
    preamp: f32,
    history: Vec<QueuedTrack>,
    /// Pre-buffered audio readers keyed by track ID.
    /// Each entry is a StreamDownload that's already connected and downloading.
    /// Dropped automatically when removed (temp file cleaned up via RAII).
    prefetched: HashMap<u64, Box<dyn ReadSeekSend>>,
}

/// Audio playback engine with queue and controls
pub struct Player {
    sink: Arc<rodio::Sink>,
    inner: Mutex<PlayerInner>,
    now_playing_tx: watch::Sender<NowPlaying>,
    now_playing_rx: watch::Receiver<NowPlaying>,
    client: Arc<MonoClient>,
    // Dropping this signals the audio thread to exit
    _shutdown_tx: std::sync::mpsc::Sender<()>,
}

impl Player {
    /// Create a new Player. Spawns a dedicated audio thread and background watchers.
    pub async fn new(client: Arc<MonoClient>) -> Arc<Self> {
        let (sink_tx, sink_rx) = std::sync::mpsc::channel();
        let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<()>();

        std::thread::spawn(move || {
            let (_stream, handle) = rodio::OutputStream::try_default()
                .expect("failed to open default audio output device");
            let sink = rodio::Sink::try_new(&handle)
                .expect("failed to create audio sink");
            let _ = sink_tx.send(sink);
            // Keep _stream alive until Player is dropped
            let _ = shutdown_rx.recv();
        });

        let sink = Arc::new(sink_rx.recv().expect("audio thread failed to initialize"));
        sink.pause(); // Start idle

        let (now_playing_tx, now_playing_rx) = watch::channel(NowPlaying::default());

        let player = Arc::new(Self {
            sink,
            inner: Mutex::new(PlayerInner {
                queue: VecDeque::new(),
                current_track: None,
                status: PlayStatus::Idle,
                volume: 1.0,
                preamp: 1.0,
                history: Vec::new(),
                prefetched: HashMap::new(),
            }),
            now_playing_tx,
            now_playing_rx,
            client,
            _shutdown_tx: shutdown_tx,
        });

        // Position reporter (~1s updates while playing)
        let weak = Arc::downgrade(&player);
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(Duration::from_secs(1)).await;
                let Some(this) = weak.upgrade() else { break };
                let is_playing = {
                    let inner = this.inner.lock().await;
                    matches!(inner.status, PlayStatus::Playing)
                };
                if is_playing {
                    this.broadcast_now_playing().await;
                }
            }
        });

        // Track watcher — auto-advance when current track ends
        let weak = Arc::downgrade(&player);
        tokio::spawn(async move {
            loop {
                tokio::time::sleep(Duration::from_millis(250)).await;
                let Some(this) = weak.upgrade() else { break };
                if !this.sink.empty() {
                    continue;
                }
                let mut inner = this.inner.lock().await;
                if matches!(inner.status, PlayStatus::Playing) {
                    // Track ended naturally
                    if let Some(current) = inner.current_track.take() {
                        inner.history.push(current);
                    }
                    if let Some(next) = inner.queue.pop_front() {
                        inner.status = PlayStatus::Buffering;
                        drop(inner);
                        if let Err(e) = this.start_playback(next).await {
                            tracing::error!("auto-advance failed: {e}");
                            let mut inner = this.inner.lock().await;
                            inner.status = PlayStatus::Idle;
                            inner.current_track = None;
                            drop(inner);
                            this.broadcast_now_playing().await;
                        }
                        this.save_state().await;
                    } else {
                        inner.status = PlayStatus::Idle;
                        inner.current_track = None;
                        drop(inner);
                        this.broadcast_now_playing().await;
                        this.save_state().await;
                    }
                }
            }
        });

        // Prefetch watcher — pre-buffers queued tracks when playing
        let weak = Arc::downgrade(&player);
        tokio::spawn(async move {
            let mut last_track_id: Option<u64> = None;
            loop {
                tokio::time::sleep(Duration::from_secs(2)).await;
                let Some(this) = weak.upgrade() else { break };
                let current_id = {
                    let inner = this.inner.lock().await;
                    if !matches!(inner.status, PlayStatus::Playing) {
                        continue;
                    }
                    inner.current_track.as_ref().map(|t| t.id)
                };
                // Prefetch when track changes or on first play
                if current_id != last_track_id {
                    last_track_id = current_id;
                    this.prefetch_queue().await;
                }
            }
        });

        // OS media controls (play/pause keys, Now Playing widget)
        player.setup_media_controls();

        // Restore persisted state (queue, history, volume) from previous session
        player.restore_state().await;

        player
    }

    /// Wire up macOS Now Playing / media key integration via souvlaki.
    /// Spawns a dedicated thread that owns MediaControls and polls for
    /// metadata updates from the watch channel.
    fn setup_media_controls(self: &Arc<Self>) {
        use souvlaki::{
            MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition,
            PlatformConfig,
        };

        let tokio_handle = tokio::runtime::Handle::current();
        let weak = Arc::downgrade(self);
        let mut np_rx = self.subscribe_now_playing();

        std::thread::Builder::new()
            .name("media-controls".into())
            .spawn(move || {
                let config = PlatformConfig {
                    dbus_name: "plexus_mono",
                    display_name: "Plexus Mono",
                    hwnd: None,
                };
                let mut controls = match MediaControls::new(config) {
                    Ok(c) => c,
                    Err(e) => {
                        tracing::warn!("media controls unavailable: {e:?}");
                        return;
                    }
                };

                // Event handler — dispatches media key presses to player via tokio
                let weak2 = weak.clone();
                let handle = tokio_handle.clone();
                if let Err(e) = controls.attach(move |event: MediaControlEvent| {
                    let Some(player) = weak2.upgrade() else {
                        return;
                    };
                    let player = player.clone();
                    handle.spawn(async move {
                        match event {
                            MediaControlEvent::Play => player.resume().await,
                            MediaControlEvent::Pause => player.pause().await,
                            MediaControlEvent::Toggle => {
                                let is_playing = {
                                    let inner = player.inner.lock().await;
                                    matches!(inner.status, PlayStatus::Playing)
                                };
                                if is_playing {
                                    player.pause().await;
                                } else {
                                    player.resume().await;
                                }
                            }
                            MediaControlEvent::Next => {
                                let _ = player.next().await;
                            }
                            MediaControlEvent::Previous => {
                                let _ = player.previous().await;
                            }
                            _ => {}
                        }
                    });
                }) {
                    tracing::warn!("failed to attach media controls: {e:?}");
                    return;
                }

                tracing::info!("media controls active (Now Playing + media keys)");

                // Set initial state immediately to claim media keys from macOS
                let _ = controls.set_metadata(MediaMetadata {
                    title: Some("Plexus Mono"),
                    artist: None,
                    album: None,
                    duration: None,
                    cover_url: None,
                });
                let _ = controls.set_playback(MediaPlayback::Paused { progress: None });

                // Poll watch channel and update OS metadata
                loop {
                    std::thread::sleep(Duration::from_millis(500));

                    if !np_rx.has_changed().unwrap_or(false) {
                        // Also check if player is dropped
                        if weak.upgrade().is_none() {
                            break;
                        }
                        continue;
                    }

                    let np = np_rx.borrow_and_update().clone();

                    // Build cover art URL from Tidal cover UUID
                    let cover_url = np.title.as_ref().and_then(|_| {
                        // We don't have cover_id in NowPlaying, so skip for now
                        None::<String>
                    });

                    let _ = controls.set_metadata(MediaMetadata {
                        title: np.title.as_deref(),
                        artist: np.artist.as_deref(),
                        album: np.album.as_deref(),
                        duration: if np.duration_secs > 0.0 {
                            Some(Duration::from_secs_f32(np.duration_secs))
                        } else {
                            None
                        },
                        cover_url: cover_url.as_deref(),
                    });

                    let playback = match np.status {
                        PlayStatus::Playing => MediaPlayback::Playing {
                            progress: Some(MediaPosition(Duration::from_secs_f32(
                                np.position_secs,
                            ))),
                        },
                        PlayStatus::Paused => MediaPlayback::Paused {
                            progress: Some(MediaPosition(Duration::from_secs_f32(
                                np.position_secs,
                            ))),
                        },
                        _ => MediaPlayback::Stopped,
                    };
                    let _ = controls.set_playback(playback);
                }
            })
            .expect("failed to spawn media-controls thread");
    }

    /// Broadcast current state through the watch channel
    async fn broadcast_now_playing(&self) {
        let inner = self.inner.lock().await;
        let np = NowPlaying {
            track_id: inner.current_track.as_ref().map(|t| t.id),
            title: inner.current_track.as_ref().map(|t| t.title.clone()),
            artist: inner.current_track.as_ref().map(|t| t.artist.clone()),
            album: inner.current_track.as_ref().map(|t| t.album.clone()),
            status: inner.status.clone(),
            position_secs: self.sink.get_pos().as_secs_f32(),
            duration_secs: inner
                .current_track
                .as_ref()
                .map(|t| t.duration_secs as f32)
                .unwrap_or(0.0),
            volume: inner.volume,
            preamp: inner.preamp,
            queue_length: inner.queue.len(),
            url: inner.current_track.as_ref().map(|t| format!("https://monochrome.tf/track/t/{}", t.id)),
        };
        let _ = self.now_playing_tx.send(np);
    }

    /// Resolve stream URL, create decoder, and start playback on the sink.
    async fn start_playback(&self, track: QueuedTrack) -> Result<(), String> {
        {
            let mut inner = self.inner.lock().await;
            inner.current_track = Some(track.clone());
            inner.status = PlayStatus::Buffering;
        }
        self.broadcast_now_playing().await;

        // Check for a pre-buffered reader first
        let prefetched: Option<Box<dyn ReadSeekSend>> = {
            let mut inner = self.inner.lock().await;
            inner.prefetched.remove(&track.id)
        };

        let reader: Box<dyn ReadSeekSend> = if let Some(r) = prefetched {
            tracing::debug!("using prefetched audio for track {}", track.id);
            r
        } else {
            // Resolve CDN URL
            let manifest = self.client.stream_manifest(track.id, &track.quality).await?;
            let url = match &manifest {
                MonoEvent::StreamManifest { url, .. } => url.clone(),
                _ => return Err("unexpected manifest type".to_string()),
            };

            // Create streaming reader (async HTTP → Read+Seek buffer)
            let r = stream_download::StreamDownload::new_http(
                url.parse::<reqwest::Url>()
                    .map_err(|e| format!("bad stream url: {e}"))?,
                stream_download::storage::temp::TempStorageProvider::new(),
                stream_download::Settings::default(),
            )
            .await
            .map_err(|e| format!("stream download error: {e}"))?;
            Box::new(r)
        };

        // Decode on blocking thread (reads file headers from network buffer)
        let source = tokio::task::spawn_blocking(move || rodio::Decoder::new(reader))
            .await
            .map_err(|e| format!("decoder task panicked: {e}"))?
            .map_err(|e| format!("audio decode error: {e}"))?;

        // Stop previous audio, append new source, play
        self.sink.stop();
        self.sink.append(source);
        self.sink.play();

        {
            let mut inner = self.inner.lock().await;
            inner.status = PlayStatus::Playing;
        }
        self.broadcast_now_playing().await;

        Ok(())
    }

    /// Play a track immediately, stopping whatever is currently playing.
    pub async fn play_track(&self, id: u64, quality: &str) -> Result<(), String> {
        let track_info = self.client.track_info(id).await.ok();
        let queued = make_queued_track(id, quality, track_info);

        // Move current to history
        {
            let mut inner = self.inner.lock().await;
            if let Some(current) = inner.current_track.take() {
                inner.history.push(current);
            }
        }

        self.start_playback(queued).await
    }

    /// Pause playback
    pub async fn pause(&self) {
        self.sink.pause();
        let mut inner = self.inner.lock().await;
        if matches!(inner.status, PlayStatus::Playing | PlayStatus::Buffering) {
            inner.status = PlayStatus::Paused;
        }
        drop(inner);
        self.broadcast_now_playing().await;
    }

    /// Resume playback
    pub async fn resume(&self) {
        self.sink.play();
        let mut inner = self.inner.lock().await;
        if matches!(inner.status, PlayStatus::Paused) {
            inner.status = PlayStatus::Playing;
        }
        drop(inner);
        self.broadcast_now_playing().await;
    }

    /// Stop playback and clear current track
    pub async fn stop(&self) {
        self.sink.stop();
        let mut inner = self.inner.lock().await;
        if let Some(current) = inner.current_track.take() {
            inner.history.push(current);
        }
        inner.status = PlayStatus::Stopped;
        inner.prefetched.clear(); // Drop all pre-buffered temp files
        drop(inner);
        self.broadcast_now_playing().await;
        self.save_state().await;
    }

    /// Skip to next track in queue
    pub async fn next(&self) -> Result<(), String> {
        self.sink.stop();
        let next = {
            let mut inner = self.inner.lock().await;
            if let Some(current) = inner.current_track.take() {
                inner.history.push(current);
            }
            inner.queue.pop_front()
        };

        if let Some(track) = next {
            self.start_playback(track).await
        } else {
            let mut inner = self.inner.lock().await;
            inner.status = PlayStatus::Idle;
            drop(inner);
            self.broadcast_now_playing().await;
            Err("queue is empty".to_string())
        }
    }

    /// Go to previous track (from history), or restart current if >5s in
    pub async fn previous(&self) -> Result<(), String> {
        // If we're more than 5 seconds into the current track, restart it
        if self.sink.get_pos().as_secs_f32() > 5.0 {
            let track = {
                let inner = self.inner.lock().await;
                inner.current_track.clone()
            };
            if let Some(track) = track {
                return self.start_playback(track).await;
            }
        }

        self.sink.stop();
        let prev = {
            let mut inner = self.inner.lock().await;
            // Push current back to front of queue
            if let Some(current) = inner.current_track.take() {
                inner.queue.push_front(current);
            }
            inner.history.pop()
        };

        if let Some(track) = prev {
            self.start_playback(track).await
        } else {
            Err("no previous track".to_string())
        }
    }

    /// Apply combined volume (preamp × volume) to the sink
    fn apply_volume(&self, inner: &PlayerInner) {
        self.sink.set_volume(inner.preamp * inner.volume);
    }

    /// Set volume (0.0–1.0)
    pub async fn set_volume(&self, level: f32) {
        let level = level.clamp(0.0, 1.0);
        let mut inner = self.inner.lock().await;
        inner.volume = level;
        self.apply_volume(&inner);
        drop(inner);
        self.broadcast_now_playing().await;
        self.save_state().await;
    }

    /// Set pre-amp gain (0.0–4.0, where >1.0 boosts)
    pub async fn set_preamp(&self, level: f32) {
        let level = level.clamp(0.0, 4.0);
        let mut inner = self.inner.lock().await;
        inner.preamp = level;
        self.apply_volume(&inner);
        drop(inner);
        self.broadcast_now_playing().await;
        self.save_state().await;
    }

    /// Add a track to the end of the queue. Auto-starts if idle.
    pub async fn queue_add(&self, id: u64, quality: &str) -> Result<(), String> {
        let track_info = self.client.track_info(id).await.ok();
        let queued = make_queued_track(id, quality, track_info);

        let should_start = {
            let mut inner = self.inner.lock().await;
            let idle = matches!(inner.status, PlayStatus::Idle | PlayStatus::Stopped);
            if idle {
                // Will start this track directly
                true
            } else {
                inner.queue.push_back(queued.clone());
                false
            }
        };

        let result = if should_start {
            self.start_playback(queued).await
        } else {
            self.broadcast_now_playing().await;
            Ok(())
        };
        self.save_state().await;
        result
    }

    /// Add all tracks from an album to the queue. Auto-starts if idle.
    pub async fn queue_album(&self, album_id: u64, quality: &str) -> Result<Vec<QueuedTrack>, String> {
        let (_album_event, track_events) = self.client.album(album_id).await?;

        let mut queued_tracks = Vec::new();
        for event in &track_events {
            if let MonoEvent::AlbumTrack { id, title, artist, duration_secs, .. } = event {
                queued_tracks.push(QueuedTrack {
                    id: *id,
                    title: title.clone(),
                    artist: artist.clone(),
                    album: String::new(), // filled below
                    duration_secs: *duration_secs,
                    quality: quality.to_string(),
                    cover_id: None,
                });
            }
        }

        // Get album name from the album event
        let album_name = if let MonoEvent::Album { title, cover_id, .. } = &_album_event {
            for t in &mut queued_tracks {
                t.album = title.clone();
                t.cover_id = cover_id.clone();
            }
            title.clone()
        } else {
            format!("Album {album_id}")
        };

        if queued_tracks.is_empty() {
            return Err(format!("no tracks found in album {album_name}"));
        }

        let should_start = {
            let mut inner = self.inner.lock().await;
            let idle = matches!(inner.status, PlayStatus::Idle | PlayStatus::Stopped);
            if idle {
                // Queue all but the first; we'll start the first directly
                for t in queued_tracks.iter().skip(1) {
                    inner.queue.push_back(t.clone());
                }
                true
            } else {
                for t in &queued_tracks {
                    inner.queue.push_back(t.clone());
                }
                false
            }
        };

        if should_start {
            self.start_playback(queued_tracks[0].clone()).await?;
        } else {
            self.broadcast_now_playing().await;
        }

        Ok(queued_tracks)
    }

    /// Add multiple tracks to the queue at once. Auto-starts if idle.
    pub async fn queue_batch(&self, ids: &[u64], quality: &str) -> Result<Vec<QueuedTrack>, String> {
        if ids.is_empty() {
            return Err("no track IDs provided".into());
        }

        // Resolve all track metadata in parallel
        let futs: Vec<_> = ids.iter().map(|&id| {
            let client = self.client.clone();
            let q = quality.to_string();
            async move {
                let info = client.track_info(id).await.ok();
                make_queued_track(id, &q, info)
            }
        }).collect();
        let tracks: Vec<QueuedTrack> = futures::future::join_all(futs).await;

        let should_start = {
            let mut inner = self.inner.lock().await;
            let idle = matches!(inner.status, PlayStatus::Idle | PlayStatus::Stopped);
            if idle {
                // Queue all but the first; we'll start the first directly
                for t in tracks.iter().skip(1) {
                    inner.queue.push_back(t.clone());
                }
                true
            } else {
                for t in &tracks {
                    inner.queue.push_back(t.clone());
                }
                false
            }
        };

        if should_start {
            self.start_playback(tracks[0].clone()).await?;
        } else {
            self.broadcast_now_playing().await;
        }

        self.save_state().await;
        Ok(tracks)
    }

    /// Clear the queue (does not stop current track)
    pub async fn queue_clear(&self) {
        let mut inner = self.inner.lock().await;
        inner.queue.clear();
        inner.prefetched.clear(); // Drop all pre-buffered temp files
        drop(inner);
        self.broadcast_now_playing().await;
    }

    /// Get current track and queue contents
    pub async fn queue_get(&self) -> (Option<QueuedTrack>, Vec<QueuedTrack>) {
        let inner = self.inner.lock().await;
        (
            inner.current_track.clone(),
            inner.queue.iter().cloned().collect(),
        )
    }

    /// Reorder a track in the queue
    pub async fn queue_reorder(&self, from: usize, to: usize) -> Result<(), String> {
        let mut inner = self.inner.lock().await;
        if from >= inner.queue.len() || to >= inner.queue.len() {
            return Err(format!(
                "index out of bounds (queue has {} tracks)",
                inner.queue.len()
            ));
        }
        let track = inner.queue.remove(from).unwrap();
        inner.queue.insert(to, track);
        Ok(())
    }

    /// Pre-buffer queued tracks by resolving their stream URLs and starting downloads.
    /// Each StreamDownload writes to a temp file (cleaned up on drop via RAII).
    async fn prefetch_queue(&self) {
        let tracks: Vec<QueuedTrack> = {
            let inner = self.inner.lock().await;
            inner
                .queue
                .iter()
                .filter(|t| !inner.prefetched.contains_key(&t.id))
                .take(10)
                .cloned()
                .collect()
        };

        for track in tracks {
            // Resolve manifest
            let manifest = match self.client.stream_manifest(track.id, &track.quality).await {
                Ok(m) => m,
                Err(e) => {
                    tracing::debug!("prefetch manifest failed for {}: {e}", track.id);
                    continue;
                }
            };
            let url = match &manifest {
                MonoEvent::StreamManifest { url, .. } => url.clone(),
                _ => continue,
            };
            let parsed = match url.parse::<reqwest::Url>() {
                Ok(u) => u,
                Err(_) => continue,
            };

            // Start download — the temp file will buffer audio in the background
            let reader = match stream_download::StreamDownload::new_http(
                parsed,
                stream_download::storage::temp::TempStorageProvider::new(),
                stream_download::Settings::default(),
            )
            .await
            {
                Ok(r) => r,
                Err(e) => {
                    tracing::debug!("prefetch download failed for {}: {e}", track.id);
                    continue;
                }
            };

            tracing::debug!("prefetched track {} ({})", track.id, track.title);
            let mut inner = self.inner.lock().await;
            inner.prefetched.insert(track.id, Box::new(reader));
        }
    }

    /// Subscribe to now-playing updates
    pub fn subscribe_now_playing(&self) -> watch::Receiver<NowPlaying> {
        self.now_playing_rx.clone()
    }

    /// Snapshot current state for persistence
    pub async fn get_state(&self) -> PlayerState {
        let inner = self.inner.lock().await;
        PlayerState {
            current_track: inner.current_track.clone(),
            position_secs: self.sink.get_pos().as_secs_f32(),
            queue: inner.queue.iter().cloned().collect(),
            history: inner.history.clone(),
            volume: inner.volume,
            preamp: inner.preamp,
        }
    }

    /// Save current state to disk
    pub async fn save_state(&self) {
        let state = self.get_state().await;
        state.save();
    }

    /// Restore state from disk — resumes playback at the saved position
    pub async fn restore_state(&self) {
        if let Some(state) = PlayerState::load() {
            let resume_track = state.current_track.clone();
            let resume_pos = state.position_secs;

            {
                let mut inner = self.inner.lock().await;
                inner.queue = state.queue.into_iter().collect();
                inner.history = state.history;
                inner.volume = state.volume;
                inner.preamp = state.preamp;
                self.apply_volume(&inner);
            }

            // Resume the track that was playing, seeking to saved position
            if let Some(track) = resume_track {
                tracing::info!(
                    "resuming '{}' at {:.0}s",
                    track.title,
                    resume_pos
                );
                match self.start_playback(track).await {
                    Ok(()) => {
                        // Start paused so it doesn't blast on startup
                        self.sink.pause();
                        let mut inner = self.inner.lock().await;
                        inner.status = PlayStatus::Paused;
                        drop(inner);
                        self.broadcast_now_playing().await;
                    }
                    Err(e) => {
                        tracing::error!("failed to resume track: {e}");
                    }
                }
            } else {
                self.broadcast_now_playing().await;
            }

            tracing::info!("restored player state from disk");
        }
    }
}

/// Build a QueuedTrack from track info (or fallback to minimal metadata)
fn make_queued_track(id: u64, quality: &str, info: Option<MonoEvent>) -> QueuedTrack {
    match info {
        Some(MonoEvent::Track {
            title,
            artist,
            album,
            duration_secs,
            cover_id,
            ..
        }) => QueuedTrack {
            id,
            title,
            artist,
            album,
            duration_secs,
            quality: quality.to_string(),
            cover_id,
        },
        _ => QueuedTrack {
            id,
            title: format!("Track {id}"),
            artist: String::new(),
            album: String::new(),
            duration_secs: 0,
            quality: quality.to_string(),
            cover_id: None,
        },
    }
}