Skip to main content

koan_core/player/
state.rs

1use std::fmt;
2use std::path::PathBuf;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
5
6use uuid::Uuid;
7
8/// Stable identity for a queue entry. UUIDv7 — time-ordered, unique across duplicates.
9#[derive(Clone, Copy, PartialEq, Eq, Hash)]
10pub struct QueueItemId(pub Uuid);
11
12impl QueueItemId {
13    pub fn new() -> Self {
14        Self(Uuid::now_v7())
15    }
16}
17
18impl Default for QueueItemId {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl fmt::Debug for QueueItemId {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        // The tail: a v7's leading hex is its timestamp, shared by a whole batch.
27        let hex = self.0.simple().to_string();
28        write!(f, "QId({})", &hex[hex.len() - 8..])
29    }
30}
31
32/// Playback state.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[repr(u8)]
35pub enum PlaybackState {
36    Stopped = 0,
37    Playing = 1,
38    Paused = 2,
39}
40
41impl PlaybackState {
42    pub fn from_u8(v: u8) -> Self {
43        match v {
44            1 => Self::Playing,
45            2 => Self::Paused,
46            _ => Self::Stopped,
47        }
48    }
49}
50
51/// Audio format info for the currently playing track.
52#[derive(Debug, Clone)]
53pub struct TrackInfo {
54    pub id: QueueItemId,
55    pub path: PathBuf,
56    pub codec: String,
57    pub sample_rate: u32,
58    pub bit_depth: Option<u16>,
59    pub bitrate_kbps: Option<u32>,
60    pub channels: u16,
61    pub duration_ms: u64,
62}
63
64// --- Playlist data model ---
65
66/// Minimum bytes written before streaming playback can begin.
67pub const STREAM_THRESHOLD: u64 = 256 * 1024;
68
69/// Held back from the seekable extent of a downloading track.
70///
71/// Bytes are converted to time at the average bitrate, so on VBR the estimate
72/// wanders either side of the truth; landing short of the write head costs a
73/// couple of seconds of reach and landing past it costs a stall.
74pub const SEEK_SAFETY_MS: u64 = 2_000;
75
76/// What a playlist item can say about itself.
77///
78/// Only what is true of the item regardless of any transfer: whether the bytes
79/// at its path can be played. Whether one is *arriving* is the download store's
80/// business, and asking the item would mean two accounts of one fact that have
81/// to be kept in step. Read [`LoadState`] for the two
82/// together.
83#[derive(Debug, Clone, Default, PartialEq, Eq)]
84pub enum ItemState {
85    /// Nothing has resolved this yet.
86    #[default]
87    Pending,
88    /// The file at `path` is there and playable.
89    Ready,
90    /// It cannot be made playable, and this is why. Not only download
91    /// failures: a track with no local file and no remote copy fails here
92    /// without a transfer ever being attempted.
93    Failed(String),
94}
95
96/// An item's state, and any transfer against it, as one answer.
97///
98/// Derived rather than stored. `Downloading` carries the store's own figures —
99/// the very same counter the downloader writes — so there is nothing to copy
100/// and nothing that can drift.
101#[derive(Debug, Clone)]
102pub enum LoadState {
103    Pending,
104    Downloading {
105        /// Where the bytes are going: the in-progress `.part` file, not the
106        /// destination it is renamed to at the end.
107        path: PathBuf,
108        /// Total bytes expected, or 0 when the server sent no Content-Length.
109        total: u64,
110        /// How many bytes have landed. The download thread writes it per chunk
111        /// without taking any lock the player holds.
112        bytes_written: Arc<crate::remote::downloads::ByteFeed>,
113    },
114    Ready,
115    Failed(String),
116}
117
118impl LoadState {
119    /// An item's state, with whatever the download store says about it.
120    ///
121    /// The store wins while a transfer is live, because it is the thing being
122    /// told. Once one has settled the item's own state stands: a finished
123    /// transfer leaves a file, and a file is what playback cares about.
124    pub fn of(item: &PlaylistItem) -> Self {
125        use crate::remote::downloads::{DownloadState, store};
126
127        if let Some(transfer) = store().get(item.id) {
128            match transfer.state {
129                DownloadState::Queued | DownloadState::Running => {
130                    return Self::Downloading {
131                        path: transfer.source,
132                        total: transfer.total,
133                        bytes_written: transfer.written,
134                    };
135                }
136                // A transfer that failed explains an item that cannot play,
137                // but only while the item has not since been resolved some
138                // other way — a retry, or a copy found on disk.
139                DownloadState::Failed(reason) if item.state == ItemState::Pending => {
140                    return Self::Failed(reason);
141                }
142                DownloadState::Failed(_) | DownloadState::Done => {}
143            }
144        }
145
146        match &item.state {
147            ItemState::Pending => Self::Pending,
148            ItemState::Ready => Self::Ready,
149            ItemState::Failed(reason) => Self::Failed(reason.clone()),
150        }
151    }
152}
153
154/// Resolved playback source for a playlist item.
155pub enum PlaybackSource {
156    /// File fully downloaded — play from path.
157    Ready(PathBuf),
158    /// File being downloaded — enough data buffered to start streaming.
159    Streaming {
160        path: PathBuf,
161        bytes_written: Arc<crate::remote::downloads::ByteFeed>,
162        total: u64,
163    },
164}
165
166/// A single item in the playlist. Created once when tracks are added to the playlist.
167#[derive(Debug, Clone)]
168pub struct PlaylistItem {
169    pub id: QueueItemId,
170    /// Database track ID — set for tracks loaded from DB, used for downloads.
171    pub db_id: Option<i64>,
172    /// The playlist entry this came from, when it came from a playlist.
173    ///
174    /// A playlist may hold the same track twice, and two copies are two queue
175    /// items. Without this a playlist row can only ask "is my *track* playing?"
176    /// and both copies answer yes. The entry id is the one thing that tells
177    /// them apart, so the queue carries it.
178    pub playlist_entry_id: Option<i64>,
179    pub path: PathBuf,
180    pub title: String,
181    pub artist: String,
182    pub album_artist: String,
183    pub album: String,
184    pub year: Option<String>,
185    pub codec: Option<String>,
186    pub track_number: Option<i64>,
187    pub disc: Option<i64>,
188    pub duration_ms: Option<u64>,
189    /// What the item can say about itself. Ask [`SharedPlayerState::load_state`]
190    /// for this together with any transfer against it.
191    pub state: ItemState,
192}
193
194/// The playlist — one flat array, one cursor. Everything else derived.
195#[derive(Debug, Clone, Default)]
196pub struct Playlist {
197    pub items: Vec<PlaylistItem>,
198    pub cursor: Option<QueueItemId>,
199}
200
201// --- UI view types ---
202
203/// Status of a track in the queue — for UI display.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum QueueEntryStatus {
206    Queued,
207    Playing,
208    Played,
209    Downloading,
210    /// User double-clicked — this track is priority, will play when ready.
211    PriorityPending,
212    Failed,
213}
214
215/// A single entry in the UI-visible queue snapshot.
216#[derive(Debug, Clone)]
217pub struct QueueEntry {
218    pub id: QueueItemId,
219    /// Database track ID — set for tracks loaded from DB, used for downloads.
220    pub db_id: Option<i64>,
221    /// The playlist row this came from — see `PlaylistItem::playlist_entry_id`.
222    pub playlist_entry_id: Option<i64>,
223    pub path: PathBuf,
224    pub title: String,
225    pub artist: String,
226    pub album_artist: String,
227    pub album: String,
228    pub year: Option<String>,
229    pub codec: Option<String>,
230    pub track_number: Option<i64>,
231    pub disc: Option<i64>,
232    pub duration_ms: Option<u64>,
233    pub status: QueueEntryStatus,
234    pub download_progress: Option<(u64, u64)>,
235    /// Why this entry cannot play, when `status` is `Failed`.
236    pub error: Option<String>,
237}
238
239/// Pre-built visible queue — single atomic snapshot for the UI.
240#[derive(Debug, Clone, Default)]
241pub struct VisibleQueueSnapshot {
242    pub entries: Vec<QueueEntry>,
243    pub finished_count: usize,
244    pub has_playing: bool,
245    pub queue_count: usize,
246}
247
248/// Shared player state — atomics for lock-free reads from UI thread.
249///
250/// The engine writes these, the UI reads them. No mutexes in the hot path.
251#[derive(Debug)]
252pub struct SharedPlayerState {
253    state: AtomicU8,
254    position_ms: AtomicU64,
255    track_info: parking_lot::RwLock<Option<TrackInfo>>,
256
257    /// The playlist and its cursor, under one lock.
258    playlist: parking_lot::RwLock<Playlist>,
259
260    /// Bumped on every playlist mutation so UI can skip redundant redraws.
261    playlist_version: AtomicU64,
262
263    /// Set by external signals (e.g. souvlaki Quit event) to request clean shutdown.
264    quit_requested: AtomicBool,
265
266    /// Set when metadata has been refreshed (e.g. download completed while streaming).
267    /// The UI loop checks this to force a souvlaki/cover-art update without a track change.
268    metadata_refresh_pending: AtomicBool,
269
270    /// The rate the output device settled at for the current track, or 0 when
271    /// nothing has played yet. Compared against the source rate, it is the one
272    /// thing koan can say for certain about the path to the DAC: whether it
273    /// handed the device the samples as they are, or something had to resample
274    /// to reach it. Everything past that — other clients, the volume stage — is
275    /// the system's, and not ours to claim.
276    output_sample_rate: AtomicU64,
277
278    /// Radio mode — automatically queue similar tracks when the queue runs low.
279    /// Shared so GQL/MCP can toggle it without going through the TUI.
280    radio_mode: AtomicBool,
281}
282
283impl SharedPlayerState {
284    pub fn new() -> Arc<Self> {
285        Arc::new(Self {
286            state: AtomicU8::new(PlaybackState::Stopped as u8),
287            position_ms: AtomicU64::new(0),
288            track_info: parking_lot::RwLock::new(None),
289            playlist: parking_lot::RwLock::new(Playlist::default()),
290            playlist_version: AtomicU64::new(0),
291            quit_requested: AtomicBool::new(false),
292            metadata_refresh_pending: AtomicBool::new(false),
293            output_sample_rate: AtomicU64::new(0),
294            radio_mode: AtomicBool::new(false),
295        })
296    }
297
298    // --- Playback state ---
299
300    pub fn playback_state(&self) -> PlaybackState {
301        PlaybackState::from_u8(self.state.load(Ordering::Acquire))
302    }
303
304    pub fn set_playback_state(&self, state: PlaybackState) {
305        self.state.store(state as u8, Ordering::Release);
306        self.changed();
307    }
308
309    pub fn position_ms(&self) -> u64 {
310        self.position_ms.load(Ordering::Acquire)
311    }
312
313    pub fn set_position_ms(&self, pos: u64) {
314        self.position_ms.store(pos, Ordering::Release);
315        // Deliberately silent. The playhead advances on its own and is
316        // published as an anchor rather than as a reading — a wake per
317        // position would be the tick this whole arrangement removes. A seek, a
318        // pause and a track change all move something else here as well, and
319        // those are exactly the ones a client has to be told about.
320    }
321
322    pub fn track_info(&self) -> Option<TrackInfo> {
323        self.track_info.read().clone()
324    }
325
326    pub fn set_track_info(&self, info: Option<TrackInfo>) {
327        *self.track_info.write() = info;
328        self.changed();
329    }
330
331    /// How far into the currently playing track a seek can land.
332    ///
333    /// A track on disk is seekable end to end. One still downloading is
334    /// seekable only as far as its bytes reach: bytes map to time by the
335    /// average bitrate, exact for lossless and CBR and drifting on VBR, which
336    /// is what `SEEK_SAFETY_MS` covers. Zero when nothing is playing.
337    ///
338    /// The one value both the clamp in `Player::seek` and the extent front ends
339    /// draw on the seek bar come from — a bar that shows a reachable position
340    /// the player then refuses is worse than no bar.
341    pub fn seekable_ms(&self) -> u64 {
342        let Some(info) = self.track_info.read().clone() else {
343            return 0;
344        };
345
346        // Released before the playlist lock is taken: derive_visible_queue takes
347        // these two in the opposite order, so holding both would close a cycle.
348        let pl = self.playlist.read();
349        let Some(item) = pl.items.iter().find(|item| item.id == info.id) else {
350            return info.duration_ms;
351        };
352
353        let LoadState::Downloading {
354            total,
355            bytes_written,
356            ..
357        } = LoadState::of(item)
358        else {
359            return info.duration_ms;
360        };
361
362        // A container that could not describe itself from the bytes downloaded
363        // states no duration, and cannot be seeked at all until the rest of it
364        // lands — there is no index to seek against and no end to seek within.
365        // Ogg is the one that does this; it keeps its duration in its last page.
366        if info.duration_ms == 0 {
367            return 0;
368        }
369
370        let written = bytes_written.load(Ordering::Acquire);
371        let reached = if total > 0 && info.duration_ms > 0 {
372            ((written as f64 / total as f64) * info.duration_ms as f64) as u64
373        } else if let Some(kbps) = info.bitrate_kbps.filter(|k| *k > 0) {
374            // No Content-Length. Bytes still say how much audio has arrived,
375            // given what the probe measured the bitrate to be: 1 kbps is
376            // 1 bit per ms, so bits divided by kbps is milliseconds.
377            written.saturating_mul(8) / kbps as u64
378        } else {
379            // Nothing to derive a position from — forward seeking would be a
380            // guess, so allow only what has already been played.
381            return self.position_ms();
382        };
383
384        reached.saturating_sub(SEEK_SAFETY_MS).min(info.duration_ms)
385    }
386
387    /// The duration to show for what is playing.
388    ///
389    /// The container's own answer wherever it gave one. A partial file that
390    /// could not be read far enough to state a duration has none, and the
391    /// library's figure stands in — it came from the server, it is right, and
392    /// a transport that reads 0:00 for nine hours of music is worse than one
393    /// reading a figure the container has not caught up with yet.
394    pub fn duration_ms(&self) -> u64 {
395        let Some(info) = self.track_info.read().clone() else {
396            return 0;
397        };
398        if info.duration_ms > 0 {
399            return info.duration_ms;
400        }
401        // Released before the playlist lock, as everywhere else here.
402        self.playlist
403            .read()
404            .items
405            .iter()
406            .find(|item| item.id == info.id)
407            .and_then(|item| item.duration_ms)
408            .unwrap_or(0)
409    }
410
411    /// `seekable_ms`, but `None` when the whole track is reachable — which is
412    /// every track that is not mid-download. What a front end draws a boundary
413    /// from: no boundary is the normal case and should cost no mark.
414    pub fn seek_ceiling_ms(&self) -> Option<u64> {
415        let duration = self.duration_ms();
416        if duration == 0 {
417            return None;
418        }
419        let seekable = self.seekable_ms();
420        (seekable < duration).then_some(seekable)
421    }
422
423    /// Download fraction (0.0..1.0) for the currently playing track, if streaming.
424    /// Returns `None` for fully-downloaded or non-playing tracks.
425    pub fn current_download_fraction(&self) -> Option<f64> {
426        // Released before the playlist lock is taken: derive_visible_queue takes
427        // these two in the opposite order, so holding both would close a cycle.
428        let id = self.track_info.read().as_ref()?.id;
429        let pl = self.playlist.read();
430        pl.items
431            .iter()
432            .find(|item| item.id == id)
433            .and_then(|item| match LoadState::of(item) {
434                LoadState::Downloading {
435                    bytes_written,
436                    total,
437                    ..
438                } => {
439                    let written = bytes_written.load(Ordering::Acquire);
440                    (total > 0).then(|| (written as f64 / total as f64).min(1.0))
441                }
442                _ => None,
443            })
444    }
445
446    // --- Quit ---
447
448    pub fn request_quit(&self) {
449        self.quit_requested.store(true, Ordering::Release);
450    }
451
452    pub fn quit_requested(&self) -> bool {
453        self.quit_requested.load(Ordering::Acquire)
454    }
455
456    // --- Metadata refresh ---
457
458    /// Signal that metadata has been refreshed mid-stream (e.g. download completed).
459    /// The UI loop calls `take_metadata_refresh()` to consume this flag and
460    /// force a souvlaki/cover-art update without waiting for a track change.
461    pub fn signal_metadata_refresh(&self) {
462        self.metadata_refresh_pending.store(true, Ordering::Release);
463        self.changed();
464    }
465
466    /// Returns true and clears the flag if a metadata refresh is pending.
467    pub fn take_metadata_refresh(&self) -> bool {
468        self.metadata_refresh_pending
469            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
470            .is_ok()
471    }
472
473    // --- Radio mode ---
474
475    pub fn radio_mode(&self) -> bool {
476        self.radio_mode.load(Ordering::Acquire)
477    }
478
479    pub fn set_radio_mode(&self, enabled: bool) {
480        self.radio_mode.store(enabled, Ordering::Release);
481        self.changed();
482    }
483
484    // --- Output device rate ---
485
486    /// `None` until a track has started and the device rate is known.
487    pub fn output_sample_rate(&self) -> Option<u32> {
488        match self.output_sample_rate.load(Ordering::Acquire) {
489            0 => None,
490            rate => Some(rate as u32),
491        }
492    }
493
494    pub fn set_output_sample_rate(&self, rate: u32) {
495        self.output_sample_rate
496            .store(u64::from(rate), Ordering::Release);
497        self.changed();
498    }
499
500    /// Back to "not known yet", for the window where the device is between
501    /// rates. A switch takes as long as the hardware needs to reclock — the
502    /// better part of a second on USB — and the previous track's rate is not
503    /// an answer for this one.
504    pub fn clear_output_sample_rate(&self) {
505        self.output_sample_rate.store(0, Ordering::Release);
506    }
507
508    // --- Playlist version ---
509
510    pub fn playlist_version(&self) -> u64 {
511        self.playlist_version.load(Ordering::Acquire)
512    }
513
514    fn bump_version(&self) {
515        self.playlist_version.fetch_add(1, Ordering::AcqRel);
516        self.changed();
517    }
518
519    /// Say that something here moved, without saying what.
520    ///
521    /// Every version and atomic in this struct stays exactly as it was — they
522    /// are what a watcher consults to find out what changed. This is what
523    /// spares it looking when nothing did. See `crate::signal`.
524    pub fn changed(&self) {
525        crate::signal::engine_changed().bump();
526    }
527
528    // --- Playlist mutations (called from player thread via commands) ---
529
530    /// Append items to the playlist.
531    pub fn add_items(&self, items: Vec<PlaylistItem>) {
532        let mut pl = self.playlist.write();
533        pl.items.extend(items);
534        drop(pl);
535        self.bump_version();
536    }
537
538    /// Insert items after a specific queue item.
539    pub fn insert_items_after(&self, items: Vec<PlaylistItem>, after: QueueItemId) {
540        let mut pl = self.playlist.write();
541        let insert_at = match pl.items.iter().position(|item| item.id == after) {
542            Some(pos) => pos + 1,
543            None => pl.items.len(), // fallback: append
544        };
545        for (i, item) in items.into_iter().enumerate() {
546            pl.items.insert(insert_at + i, item);
547        }
548        drop(pl);
549        self.bump_version();
550    }
551
552    /// Update file paths for playlist items (after organize moves files).
553    pub fn update_paths(&self, updates: &[(QueueItemId, PathBuf)]) {
554        let mut pl = self.playlist.write();
555        for (id, new_path) in updates {
556            if let Some(item) = pl.items.iter_mut().find(|item| item.id == *id) {
557                item.path = new_path.clone();
558            }
559        }
560        drop(pl);
561        self.bump_version();
562    }
563
564    /// Remove an item by ID.
565    pub fn remove_item(&self, id: QueueItemId) {
566        let mut pl = self.playlist.write();
567        pl.items.retain(|item| item.id != id);
568        // If cursor was on removed item, clear it (caller handles next_track).
569        if pl.cursor == Some(id) {
570            pl.cursor = None;
571        }
572        drop(pl);
573        self.bump_version();
574    }
575
576    /// Move an item relative to another entry.
577    pub fn move_item(&self, id: QueueItemId, target: QueueItemId, after: bool) {
578        let mut pl = self.playlist.write();
579        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
580            return;
581        };
582        let item = pl.items.remove(from);
583        let Some(to) = pl.items.iter().position(|item| item.id == target) else {
584            // Target gone — put it back.
585            let pos = from.min(pl.items.len());
586            pl.items.insert(pos, item);
587            return;
588        };
589        let insert_at = if after { to + 1 } else { to };
590        pl.items.insert(insert_at, item);
591        drop(pl);
592        self.bump_version();
593    }
594
595    /// Batch move: extract items by ID, reinsert them at `target` position.
596    /// Preserves the relative order of the moved items.
597    pub fn move_items(&self, ids: &[QueueItemId], target: QueueItemId, after: bool) {
598        use std::collections::HashSet;
599        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();
600
601        let mut pl = self.playlist.write();
602
603        // Partition: extract moved items, keep the rest.
604        let mut remaining = Vec::with_capacity(pl.items.len());
605        let mut moved = Vec::with_capacity(ids.len());
606        for item in pl.items.drain(..) {
607            if id_set.contains(&item.id) {
608                moved.push(item);
609            } else {
610                remaining.push(item);
611            }
612        }
613
614        // Find target in the remaining items.
615        let insert_at = match remaining.iter().position(|item| item.id == target) {
616            Some(pos) => {
617                if after {
618                    pos + 1
619                } else {
620                    pos
621                }
622            }
623            None => remaining.len(),
624        };
625
626        // Splice moved items in at the target position.
627        for (i, item) in moved.into_iter().enumerate() {
628            remaining.insert(insert_at + i, item);
629        }
630
631        pl.items = remaining;
632        drop(pl);
633        self.bump_version();
634    }
635
636    /// Set the cursor (what's playing / should play).
637    pub fn set_cursor(&self, id: Option<QueueItemId>) {
638        let mut pl = self.playlist.write();
639        pl.cursor = id;
640        drop(pl);
641        self.bump_version();
642    }
643
644    pub fn cursor(&self) -> Option<QueueItemId> {
645        self.playlist.read().cursor
646    }
647
648    /// Clear the entire playlist + cursor.
649    pub fn clear_playlist(&self) {
650        let mut pl = self.playlist.write();
651        pl.items.clear();
652        pl.cursor = None;
653        drop(pl);
654        self.bump_version();
655    }
656
657    // --- Called from decode thread (gapless) ---
658
659    /// Move the cursor to the next item that can still play — the first item
660    /// after the cursor that is not `Failed` — and return its ID.
661    ///
662    /// An item that is still downloading parks the cursor rather than being
663    /// skipped, so playback resumes from it when its data lands. Skipping it
664    /// would drop it from the queue for good.
665    ///
666    /// With no cursor set, starts from the top. A cursor pointing at an item
667    /// that is no longer in the playlist yields `None` — restarting from the
668    /// top would silently replay the queue.
669    pub fn advance_cursor_loadable(&self) -> Option<QueueItemId> {
670        let mut pl = self.playlist.write();
671        let start = match pl.cursor {
672            Some(cid) => pl.items.iter().position(|item| item.id == cid)? + 1,
673            None => 0,
674        };
675
676        let next = pl
677            .items
678            .get(start..)?
679            .iter()
680            .find(|item| !matches!(item.state, ItemState::Failed(_)))
681            .map(|item| item.id)?;
682
683        pl.cursor = Some(next);
684        drop(pl);
685        self.bump_version();
686        Some(next)
687    }
688
689    /// Peek at the next Ready item after a given item ID WITHOUT moving the cursor.
690    /// Used by the decode thread for gapless lookahead — the cursor is moved
691    /// later by update_playback_state when playback actually reaches the track.
692    pub fn peek_next_ready_after(&self, after_id: QueueItemId) -> Option<(QueueItemId, PathBuf)> {
693        let pl = self.playlist.read();
694        // A reference item that has been removed means the lookahead has nothing
695        // to follow; starting from the top would gaplessly replay the queue.
696        let start = pl.items.iter().position(|item| item.id == after_id)? + 1;
697
698        for i in start..pl.items.len() {
699            if matches!(pl.items[i].state, ItemState::Ready) {
700                let item = &pl.items[i];
701                return Some((item.id, item.path.clone()));
702            }
703        }
704        None
705    }
706
707    /// Retreat cursor to the previous item. Returns (id, path) if found.
708    /// For prev_track — goes to the item before cursor regardless of load state.
709    pub fn retreat_cursor(&self) -> Option<(QueueItemId, PathBuf)> {
710        let mut pl = self.playlist.write();
711        let cursor_pos = match pl.cursor {
712            Some(cid) => pl.items.iter().position(|item| item.id == cid),
713            None => None,
714        };
715
716        let prev_pos = cursor_pos.and_then(|p| p.checked_sub(1));
717
718        match prev_pos {
719            Some(pos) => {
720                let item = &pl.items[pos];
721                let result = (item.id, item.path.clone());
722                pl.cursor = Some(item.id);
723                drop(pl);
724                self.bump_version();
725                Some(result)
726            }
727            None => None,
728        }
729    }
730
731    // --- Called from resolve thread ---
732
733    /// Update the load state of a playlist item.
734    pub fn update_item_state(&self, id: QueueItemId, new_state: ItemState) {
735        let mut pl = self.playlist.write();
736        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
737            item.state = new_state;
738        }
739        drop(pl);
740        self.bump_version();
741    }
742
743    /// Take what a finished download's own tags can add.
744    ///
745    /// Streaming starts on partial Symphonia tags, so an item with nothing
746    /// behind it takes the lot once the whole file is there. An item that came
747    /// out of the library does not: the record is what the queue was built
748    /// from and what every other track on it carries, and a file whose tags
749    /// disagree — a server album titled one way, the file inside titled
750    /// another — would split its album in two the moment it finished
751    /// downloading. The duration is the file's to know either way.
752    pub fn update_item_metadata(
753        &self,
754        id: QueueItemId,
755        title: String,
756        artist: String,
757        album_artist: String,
758        album: String,
759        duration_ms: Option<u64>,
760    ) {
761        let mut pl = self.playlist.write();
762        if let Some(item) = pl.items.iter_mut().find(|item| item.id == id) {
763            if item.db_id.is_none() {
764                item.title = title;
765                item.artist = artist;
766                item.album_artist = album_artist;
767                item.album = album;
768            }
769            if let Some(dur) = duration_ms {
770                item.duration_ms = Some(dur);
771            }
772        }
773        drop(pl);
774        self.bump_version();
775    }
776
777    /// Get the playback source for an item if it's ready to play.
778    /// Returns `None` if not enough data is available yet.
779    pub fn item_playback_source(&self, id: QueueItemId) -> Option<PlaybackSource> {
780        let pl = self.playlist.read();
781        pl.items
782            .iter()
783            .find(|item| item.id == id)
784            .and_then(|item| match LoadState::of(item) {
785                LoadState::Ready => Some(PlaybackSource::Ready(item.path.clone())),
786                LoadState::Downloading {
787                    path,
788                    total,
789                    bytes_written,
790                } => {
791                    let written = bytes_written.load(Ordering::Acquire);
792                    (written >= STREAM_THRESHOLD).then_some(PlaybackSource::Streaming {
793                        path,
794                        bytes_written,
795                        total,
796                    })
797                }
798                _ => None,
799            })
800    }
801
802    /// Put back to `Pending` every queue item whose file has gone, and say
803    /// which they were so they can be fetched again.
804    ///
805    /// The queue holds paths, and clearing downloads deletes the files under
806    /// them. An item left claiming `Ready` opens nothing when it is played —
807    /// it is not broken, it is a remote track that has to be fetched a second
808    /// time. Only items with a database row behind them: one without has
809    /// nowhere to be fetched from, and parking the cursor on it would be worse
810    /// than letting it fail honestly.
811    pub fn reset_items_with_missing_files(&self) -> Vec<(i64, QueueItemId)> {
812        let mut pl = self.playlist.write();
813        let mut reset = Vec::new();
814        for item in pl.items.iter_mut() {
815            let Some(db_id) = item.db_id else { continue };
816            if !matches!(item.state, ItemState::Ready) {
817                continue;
818            }
819            if item.path.exists() {
820                continue;
821            }
822            item.state = ItemState::Pending;
823            reset.push((db_id, item.id));
824        }
825        drop(pl);
826        if !reset.is_empty() {
827            self.bump_version();
828        }
829        reset
830    }
831
832    /// The item's path if it is `Ready`. A caller that can stream wants `item_playback_source`.
833    pub fn item_path_if_ready(&self, id: QueueItemId) -> Option<PathBuf> {
834        let pl = self.playlist.read();
835        pl.items.iter().find(|item| item.id == id).and_then(|item| {
836            if matches!(item.state, ItemState::Ready) {
837                Some(item.path.clone())
838            } else {
839                None
840            }
841        })
842    }
843
844    pub fn is_cursor(&self, id: QueueItemId) -> bool {
845        self.playlist.read().cursor == Some(id)
846    }
847
848    /// Get QueueItemIds of all playlist items sharing the same album as the given item.
849    /// Matches on both album name and album artist to avoid false positives
850    /// (e.g. two different "Greatest Hits" by different artists).
851    pub fn same_album_item_ids(&self, id: QueueItemId) -> Vec<QueueItemId> {
852        let pl = self.playlist.read();
853        let Some(cursor) = pl.items.iter().find(|item| item.id == id) else {
854            return vec![];
855        };
856        let album = cursor.album.clone();
857        let album_artist = cursor.album_artist.clone();
858        pl.items
859            .iter()
860            .filter(|item| {
861                item.id != id && item.album == album && item.album_artist == album_artist
862            })
863            .map(|item| item.id)
864            .collect()
865    }
866
867    /// Get all playlist items that are Pending and have a db_id.
868    /// Returns `(db_id, QueueItemId)` pairs suitable for the download queue.
869    pub fn pending_downloads(&self) -> Vec<(i64, QueueItemId)> {
870        let pl = self.playlist.read();
871        pl.items
872            .iter()
873            .filter(|item| matches!(item.state, ItemState::Pending))
874            .filter_map(|item| item.db_id.map(|db_id| (db_id, item.id)))
875            .collect()
876    }
877
878    /// Every item mid-transfer, with the bytes it has and the bytes it expects.
879    ///
880    /// Progress moves without the playlist version moving — the download thread
881    /// writes the byte counter directly — so anything following the version
882    /// alone shows a frozen bar. This is how a watcher sees it move.
883    pub fn downloads_in_flight(&self) -> Vec<(QueueItemId, u64, u64)> {
884        crate::remote::downloads::store()
885            .all()
886            .iter()
887            .filter(|d| !d.state.is_settled())
888            .map(|d| (d.id, d.bytes_written(), d.total))
889            .collect()
890    }
891
892    /// Get the db_id for a specific playlist item.
893    pub fn item_db_id(&self, id: QueueItemId) -> Option<i64> {
894        let pl = self.playlist.read();
895        pl.items
896            .iter()
897            .find(|item| item.id == id)
898            .and_then(|item| item.db_id)
899    }
900
901    /// Get the load state of a specific playlist item.
902    pub fn item_load_state(&self, id: QueueItemId) -> Option<LoadState> {
903        let pl = self.playlist.read();
904        pl.items
905            .iter()
906            .find(|item| item.id == id)
907            .map(LoadState::of)
908    }
909
910    // --- Snapshot helpers for undo ---
911
912    /// Get the full playlist snapshot (items + cursor) for undo of ClearPlaylist.
913    pub fn snapshot_playlist(&self) -> (Vec<PlaylistItem>, Option<QueueItemId>) {
914        let pl = self.playlist.read();
915        (pl.items.clone(), pl.cursor)
916    }
917
918    /// Get an item by ID (for undo of RemoveFromPlaylist).
919    pub fn get_item(&self, id: QueueItemId) -> Option<PlaylistItem> {
920        let pl = self.playlist.read();
921        pl.items.iter().find(|item| item.id == id).cloned()
922    }
923
924    /// Get the ID of the item immediately before the given ID (None if first).
925    pub fn item_before(&self, id: QueueItemId) -> Option<QueueItemId> {
926        let pl = self.playlist.read();
927        let pos = pl.items.iter().position(|item| item.id == id)?;
928        if pos == 0 {
929            None
930        } else {
931            Some(pl.items[pos - 1].id)
932        }
933    }
934
935    /// Put the items in exactly this order.
936    ///
937    /// Items not named keep their relative order and follow at the end, so a
938    /// stale order cannot lose anything. The items themselves are moved, not
939    /// rebuilt: their ids, load states and download progress are what the rest
940    /// of the player is holding on to.
941    pub fn reorder_to(&self, order: &[QueueItemId]) {
942        let mut pl = self.playlist.write();
943        let mut taken: Vec<Option<PlaylistItem>> = pl.items.drain(..).map(Some).collect();
944        let mut sorted = Vec::with_capacity(taken.len());
945        for id in order {
946            if let Some(slot) = taken
947                .iter_mut()
948                .find(|i| i.as_ref().is_some_and(|i| i.id == *id))
949                && let Some(item) = slot.take()
950            {
951                sorted.push(item);
952            }
953        }
954        sorted.extend(taken.into_iter().flatten());
955        pl.items = sorted;
956        drop(pl);
957        self.bump_version();
958    }
959
960    /// For each ID, the ID of the item before it (or None if first), returned in
961    /// playlist order regardless of the order `ids` arrives in.
962    ///
963    /// Undo replays these left to right, so an item whose recorded predecessor is
964    /// also in `ids` must come after it — otherwise the predecessor is missing at
965    /// replay time and the item lands at the end of the playlist instead.
966    pub fn items_before(&self, ids: &[QueueItemId]) -> Vec<(QueueItemId, Option<QueueItemId>)> {
967        use std::collections::HashSet;
968        let wanted: HashSet<QueueItemId> = ids.iter().copied().collect();
969        let pl = self.playlist.read();
970        pl.items
971            .iter()
972            .enumerate()
973            .filter(|(_, item)| wanted.contains(&item.id))
974            .map(|(pos, item)| {
975                let before = if pos == 0 {
976                    None
977                } else {
978                    Some(pl.items[pos - 1].id)
979                };
980                (item.id, before)
981            })
982            .collect()
983    }
984
985    /// The nearest item before `id` that is not itself being removed — where
986    /// playback resumes from after a batch delete that takes out the cursor.
987    /// `None` means resume from the top of what survives.
988    pub fn surviving_item_before(
989        &self,
990        id: QueueItemId,
991        removed: &[QueueItemId],
992    ) -> Option<QueueItemId> {
993        use std::collections::HashSet;
994        let removed: HashSet<QueueItemId> = removed.iter().copied().collect();
995        let pl = self.playlist.read();
996        let pos = pl.items.iter().position(|item| item.id == id)?;
997        pl.items[..pos]
998            .iter()
999            .rev()
1000            .find(|item| !removed.contains(&item.id))
1001            .map(|item| item.id)
1002    }
1003
1004    /// Restore a full playlist from snapshot (for redo of ClearPlaylist undo).
1005    pub fn restore_playlist(&self, items: Vec<PlaylistItem>, cursor: Option<QueueItemId>) {
1006        let mut pl = self.playlist.write();
1007        pl.items = items;
1008        pl.cursor = cursor;
1009        drop(pl);
1010        self.bump_version();
1011    }
1012
1013    /// Remove multiple items by IDs.
1014    pub fn remove_items(&self, ids: &[QueueItemId]) {
1015        use std::collections::HashSet;
1016        let id_set: HashSet<QueueItemId> = ids.iter().copied().collect();
1017        let mut pl = self.playlist.write();
1018        pl.items.retain(|item| !id_set.contains(&item.id));
1019        if let Some(cursor) = pl.cursor
1020            && id_set.contains(&cursor)
1021        {
1022            pl.cursor = None;
1023        }
1024        drop(pl);
1025        self.bump_version();
1026    }
1027
1028    /// Insert a single item after a given ID (or at front if None).
1029    pub fn insert_item_at(&self, item: PlaylistItem, after: Option<QueueItemId>) {
1030        let mut pl = self.playlist.write();
1031        let insert_at = match after {
1032            Some(after_id) => {
1033                match pl.items.iter().position(|i| i.id == after_id) {
1034                    Some(pos) => pos + 1,
1035                    None => pl.items.len(), // fallback
1036                }
1037            }
1038            None => 0,
1039        };
1040        pl.items.insert(insert_at, item);
1041        drop(pl);
1042        self.bump_version();
1043    }
1044
1045    /// Move a single item to after `after` (or to front if None).
1046    pub fn move_item_to(&self, id: QueueItemId, after: Option<QueueItemId>) {
1047        let mut pl = self.playlist.write();
1048        let Some(from) = pl.items.iter().position(|item| item.id == id) else {
1049            return;
1050        };
1051        let item = pl.items.remove(from);
1052        let insert_at = match after {
1053            Some(after_id) => match pl.items.iter().position(|i| i.id == after_id) {
1054                Some(pos) => pos + 1,
1055                None => pl.items.len(),
1056            },
1057            None => 0,
1058        };
1059        pl.items.insert(insert_at, item);
1060        drop(pl);
1061        self.bump_version();
1062    }
1063
1064    /// Batch move: reposition each item to after its given predecessor.
1065    /// Processes in order so earlier insertions don't corrupt later positions.
1066    pub fn move_items_to(&self, entries: &[(QueueItemId, Option<QueueItemId>)]) {
1067        for &(id, after) in entries {
1068            self.move_item_to(id, after);
1069        }
1070    }
1071
1072    // --- Called from UI thread (read lock) ---
1073
1074    /// Derive the visible queue from the playlist + cursor. O(n).
1075    /// Called once per UI tick.
1076    pub fn derive_visible_queue(&self) -> VisibleQueueSnapshot {
1077        // Read before the playlist lock — see current_download_fraction.
1078        let playing_duration_ms = self.track_info.read().as_ref().map(|ti| ti.duration_ms);
1079        let pl = self.playlist.read();
1080
1081        let cursor_pos = match pl.cursor {
1082            Some(cid) => pl.items.iter().position(|item| item.id == cid),
1083            None => None,
1084        };
1085
1086        let mut entries = Vec::with_capacity(pl.items.len());
1087        let mut finished_count = 0;
1088        let mut has_playing = false;
1089        let mut queue_count = 0;
1090
1091        for (i, item) in pl.items.iter().enumerate() {
1092            let is_cursor = cursor_pos == Some(i);
1093            let is_before_cursor = cursor_pos.is_some_and(|cp| i < cp);
1094
1095            // The byte count is the download thread's own counter, written per
1096            // chunk without the playlist lock, so a transfer never bumps the
1097            // playlist version. Derived once per row because every branch below
1098            // wants the item's state and its transfer together.
1099            let load_state = LoadState::of(item);
1100
1101            let dl_progress = match &load_state {
1102                LoadState::Downloading {
1103                    total,
1104                    bytes_written,
1105                    ..
1106                } => Some((bytes_written.load(Ordering::Relaxed), *total)),
1107                _ => None,
1108            };
1109
1110            let status = if is_cursor {
1111                has_playing = true;
1112                match &load_state {
1113                    LoadState::Ready => QueueEntryStatus::Playing,
1114                    LoadState::Downloading { .. } => QueueEntryStatus::PriorityPending,
1115                    LoadState::Pending => QueueEntryStatus::PriorityPending,
1116                    LoadState::Failed(_) => QueueEntryStatus::Failed,
1117                }
1118            } else if is_before_cursor {
1119                finished_count += 1;
1120                match &load_state {
1121                    LoadState::Ready => QueueEntryStatus::Played,
1122                    LoadState::Downloading { .. } => QueueEntryStatus::Downloading,
1123                    LoadState::Pending => QueueEntryStatus::Downloading,
1124                    LoadState::Failed(_) => QueueEntryStatus::Failed,
1125                }
1126            } else {
1127                queue_count += 1;
1128                match &load_state {
1129                    LoadState::Ready => QueueEntryStatus::Queued,
1130                    LoadState::Downloading { .. } => QueueEntryStatus::Downloading,
1131                    LoadState::Pending => QueueEntryStatus::Downloading,
1132                    LoadState::Failed(_) => QueueEntryStatus::Failed,
1133                }
1134            };
1135
1136            // Override duration from TrackInfo if we have it and this is playing.
1137            let duration_ms =
1138                if has_playing && status == QueueEntryStatus::Playing && item.duration_ms.is_none()
1139                {
1140                    playing_duration_ms
1141                } else {
1142                    item.duration_ms
1143                };
1144
1145            entries.push(QueueEntry {
1146                id: item.id,
1147                db_id: item.db_id,
1148                playlist_entry_id: item.playlist_entry_id,
1149                path: item.path.clone(),
1150                title: item.title.clone(),
1151                artist: item.artist.clone(),
1152                album_artist: item.album_artist.clone(),
1153                album: item.album.clone(),
1154                year: item.year.clone(),
1155                codec: item.codec.clone(),
1156                track_number: item.track_number,
1157                disc: item.disc,
1158                duration_ms,
1159                status,
1160                download_progress: dl_progress,
1161                error: match &load_state {
1162                    LoadState::Failed(reason) => Some(reason.clone()),
1163                    _ => None,
1164                },
1165            });
1166        }
1167
1168        VisibleQueueSnapshot {
1169            entries,
1170            finished_count,
1171            has_playing,
1172            queue_count,
1173        }
1174    }
1175}
1176
1177#[cfg(test)]
1178mod tests {
1179    use super::*;
1180
1181    // --- helpers ---
1182
1183    fn make_item(title: &str, state: ItemState) -> PlaylistItem {
1184        PlaylistItem {
1185            playlist_entry_id: None,
1186            id: QueueItemId::new(),
1187            db_id: None,
1188            path: PathBuf::from(format!("/music/{title}.flac")),
1189            title: title.to_string(),
1190            artist: "Artist".to_string(),
1191            album_artist: "Artist".to_string(),
1192            album: "Album".to_string(),
1193            year: None,
1194            codec: Some("FLAC".to_string()),
1195            track_number: None,
1196            disc: None,
1197            duration_ms: Some(200_000),
1198            state,
1199        }
1200    }
1201
1202    /// An item with a transfer running against it, told to the store the way
1203    /// the downloader tells it.
1204    fn downloading_item(
1205        title: &str,
1206        total: u64,
1207        written: Arc<crate::remote::downloads::ByteFeed>,
1208    ) -> PlaylistItem {
1209        let item = make_item(title, ItemState::Pending);
1210        let store = crate::remote::downloads::store();
1211        store.queued(crate::remote::downloads::Download {
1212            id: item.id,
1213            track_id: 1,
1214            title: title.into(),
1215            artist: String::new(),
1216            source: PathBuf::from(format!("/cache/{title}.flac.part")),
1217            dest: PathBuf::from(format!("/cache/{title}.flac")),
1218            total,
1219            written: written.clone(),
1220            state: crate::remote::downloads::DownloadState::Queued,
1221            bytes_per_second: 0,
1222        });
1223        store.started(item.id, total, written);
1224        item
1225    }
1226
1227    fn ready_item(title: &str) -> PlaylistItem {
1228        make_item(title, ItemState::Ready)
1229    }
1230
1231    fn pending_item(title: &str) -> PlaylistItem {
1232        make_item(title, ItemState::Pending)
1233    }
1234
1235    fn failed_item(title: &str) -> PlaylistItem {
1236        make_item(title, ItemState::Failed("nope".into()))
1237    }
1238
1239    const DURATION_MS: u64 = 32_523_787;
1240
1241    /// A nine-hour track under the cursor, `downloaded` bytes of `total` in.
1242    /// `total` of 0 stands for a server that sent no Content-Length.
1243    fn streaming_state(
1244        downloaded: u64,
1245        total: u64,
1246        bitrate_kbps: Option<u32>,
1247    ) -> Arc<SharedPlayerState> {
1248        streaming_state_with_duration(downloaded, total, bitrate_kbps, DURATION_MS)
1249    }
1250
1251    /// The same, but saying what the container managed to state about itself.
1252    /// A partial Ogg states nothing, which is zero here.
1253    fn streaming_state_with_duration(
1254        downloaded: u64,
1255        total: u64,
1256        bitrate_kbps: Option<u32>,
1257        container_duration_ms: u64,
1258    ) -> Arc<SharedPlayerState> {
1259        let written = crate::remote::downloads::ByteFeed::new();
1260        written.set(downloaded);
1261        let item = make_item("train", ItemState::Pending);
1262        let id = item.id;
1263        let path = item.path.clone();
1264
1265        // The transfer goes where transfers go. Ids are unique per item, so
1266        // tests sharing the process store never see each other's.
1267        let store = crate::remote::downloads::store();
1268        store.queued(crate::remote::downloads::Download {
1269            id,
1270            track_id: 1,
1271            title: "train".into(),
1272            artist: String::new(),
1273            source: PathBuf::from("/cache/train.opus.part"),
1274            dest: PathBuf::from("/cache/train.opus"),
1275            total,
1276            written: written.clone(),
1277            state: crate::remote::downloads::DownloadState::Queued,
1278            bytes_per_second: 0,
1279        });
1280        store.started(id, total, written);
1281
1282        let state = SharedPlayerState::new();
1283        state.add_items(vec![item]);
1284        state.set_cursor(Some(id));
1285        state.set_track_info(Some(TrackInfo {
1286            id,
1287            path,
1288            codec: "Opus".into(),
1289            sample_rate: 48_000,
1290            bit_depth: None,
1291            bitrate_kbps,
1292            channels: 2,
1293            duration_ms: container_duration_ms,
1294        }));
1295        state
1296    }
1297
1298    // --- seekable_ms ---
1299
1300    #[test]
1301    fn a_track_on_disk_is_seekable_end_to_end() {
1302        let item = ready_item("done");
1303        let id = item.id;
1304        let path = item.path.clone();
1305        let state = SharedPlayerState::new();
1306        state.add_items(vec![item]);
1307        state.set_cursor(Some(id));
1308        state.set_track_info(Some(TrackInfo {
1309            id,
1310            path,
1311            codec: "FLAC".into(),
1312            sample_rate: 44_100,
1313            bit_depth: Some(16),
1314            bitrate_kbps: None,
1315            channels: 2,
1316            duration_ms: 200_000,
1317        }));
1318
1319        assert_eq!(state.seekable_ms(), 200_000);
1320        // Nothing to draw a boundary for, so front ends are told there isn't one.
1321        assert_eq!(state.seek_ceiling_ms(), None);
1322    }
1323
1324    #[test]
1325    fn a_downloading_track_is_seekable_as_far_as_its_bytes_reach() {
1326        // A quarter of a nine-hour file in: a quarter of the way through it,
1327        // less the margin the byte-to-time estimate is worth.
1328        let state = streaming_state(100, 400, None);
1329        assert_eq!(state.seekable_ms(), 32_523_787 / 4 - SEEK_SAFETY_MS);
1330        assert_eq!(
1331            state.seek_ceiling_ms(),
1332            Some(32_523_787 / 4 - SEEK_SAFETY_MS)
1333        );
1334    }
1335
1336    #[test]
1337    fn a_transfer_without_a_content_length_falls_back_to_bitrate() {
1338        // No total to take a fraction of. 128 kbps is 128 bits per ms, so a
1339        // megabyte is 8 388 608 bits and a little over 65 seconds.
1340        let state = streaming_state(1024 * 1024, 0, Some(128));
1341        assert_eq!(state.seekable_ms(), 1024 * 1024 * 8 / 128 - SEEK_SAFETY_MS);
1342    }
1343
1344    #[test]
1345    fn nothing_to_estimate_from_allows_no_forward_seek() {
1346        // Neither a length nor a bitrate: anywhere past the playhead is a
1347        // guess, and a guess that lands past the write head is a stall.
1348        let state = streaming_state(1024 * 1024, 0, None);
1349        state.set_position_ms(12_000);
1350        assert_eq!(state.seekable_ms(), 12_000);
1351    }
1352
1353    #[test]
1354    fn the_seekable_extent_never_exceeds_the_track() {
1355        // A download reporting more bytes than it advertised must not offer a
1356        // seek past the end of the music.
1357        let state = streaming_state(500, 400, None);
1358        assert_eq!(state.seekable_ms(), 32_523_787);
1359    }
1360
1361    #[test]
1362    fn nothing_playing_is_seekable_nowhere() {
1363        assert_eq!(SharedPlayerState::new().seekable_ms(), 0);
1364        assert_eq!(SharedPlayerState::new().seek_ceiling_ms(), None);
1365    }
1366
1367    #[test]
1368    fn a_container_that_cannot_state_its_duration_cannot_be_seeked() {
1369        // A partial Ogg keeps its duration in a last page that has not arrived,
1370        // so it opens and plays but has nothing to seek against. Half the bytes
1371        // being present does not change that.
1372        let state = streaming_state_with_duration(200, 400, Some(128), 0);
1373        assert_eq!(state.seekable_ms(), 0);
1374    }
1375
1376    #[test]
1377    fn the_library_duration_stands_in_for_a_silent_container() {
1378        // What is shown on the transport, so nine hours of music does not read
1379        // as 0:00 while it caches.
1380        let state = streaming_state_with_duration(200, 400, Some(128), 0);
1381        assert_eq!(state.duration_ms(), 200_000, "the item's own figure");
1382        // And it is a display figure only — it grants no seeking.
1383        assert_eq!(state.seekable_ms(), 0);
1384        assert_eq!(state.seek_ceiling_ms(), Some(0));
1385    }
1386
1387    #[test]
1388    fn the_container_duration_wins_where_there_is_one() {
1389        let state = streaming_state(200, 400, None);
1390        assert_eq!(state.duration_ms(), DURATION_MS);
1391    }
1392
1393    #[test]
1394    fn the_download_landing_restores_seeking() {
1395        // The sequence the whole design turns on: a track that opened without a
1396        // duration gets one when the finished file is re-read, and is seekable
1397        // end to end from that moment — no restart, no handover.
1398        let state = streaming_state_with_duration(400, 400, Some(128), 0);
1399        assert_eq!(state.seekable_ms(), 0);
1400
1401        // What the downloader does when the bytes land: settle the transfer,
1402        // then say the file is playable. In that order — while the store still
1403        // says a transfer is running, it is.
1404        let id = state.cursor().expect("cursor");
1405        crate::remote::downloads::store().finished(id);
1406        state.update_item_state(id, ItemState::Ready);
1407        let info = state.track_info().expect("track info");
1408        state.set_track_info(Some(TrackInfo {
1409            duration_ms: DURATION_MS,
1410            ..info
1411        }));
1412
1413        assert_eq!(state.seekable_ms(), DURATION_MS);
1414        assert_eq!(state.seek_ceiling_ms(), None, "no boundary left to draw");
1415    }
1416
1417    // --- advance_cursor_loadable ---
1418
1419    #[test]
1420    fn advance_parks_on_a_still_downloading_track() {
1421        // A track that has not arrived yet must hold the cursor, not be skipped:
1422        // skipping it drops it from the queue for good, and it is the item whose
1423        // TrackReady has to resume playback.
1424        let state = SharedPlayerState::new();
1425        let item0 = ready_item("track-0");
1426        let item1 = pending_item("track-1");
1427        let item2 = ready_item("track-2");
1428        let (id0, id1) = (item0.id, item1.id);
1429
1430        state.add_items(vec![item0, item1, item2]);
1431
1432        assert_eq!(state.advance_cursor_loadable(), Some(id0));
1433        assert_eq!(state.advance_cursor_loadable(), Some(id1));
1434        assert_eq!(state.cursor(), Some(id1));
1435    }
1436
1437    #[test]
1438    fn advance_skips_failed_items() {
1439        let state = SharedPlayerState::new();
1440        let item0 = ready_item("track-0");
1441        let item1 = failed_item("track-1");
1442        let item2 = ready_item("track-2");
1443        let (id0, id2) = (item0.id, item2.id);
1444
1445        state.add_items(vec![item0, item1, item2]);
1446        state.set_cursor(Some(id0));
1447
1448        assert_eq!(state.advance_cursor_loadable(), Some(id2));
1449    }
1450
1451    #[test]
1452    fn advance_stops_at_end_of_playlist() {
1453        let state = SharedPlayerState::new();
1454        let item0 = ready_item("track-0");
1455        let item1 = ready_item("track-1");
1456        let id1 = item1.id;
1457
1458        state.add_items(vec![item0, item1]);
1459        state.set_cursor(Some(id1));
1460
1461        assert_eq!(state.advance_cursor_loadable(), None);
1462        assert_eq!(
1463            state.cursor(),
1464            Some(id1),
1465            "cursor unchanged on a failed advance"
1466        );
1467    }
1468
1469    #[test]
1470    fn advance_with_only_failed_items_returns_none() {
1471        let state = SharedPlayerState::new();
1472        state.add_items(vec![failed_item("bad-0"), failed_item("bad-1")]);
1473
1474        assert_eq!(state.advance_cursor_loadable(), None);
1475    }
1476
1477    #[test]
1478    fn advance_from_a_vanished_cursor_does_not_restart_the_queue() {
1479        let state = SharedPlayerState::new();
1480        let item0 = ready_item("track-0");
1481        let item1 = ready_item("track-1");
1482        let id0 = item0.id;
1483
1484        state.add_items(vec![item0, item1]);
1485        let ghost = QueueItemId::new();
1486        state.set_cursor(Some(ghost));
1487
1488        assert_eq!(state.advance_cursor_loadable(), None);
1489        assert_ne!(state.cursor(), Some(id0));
1490    }
1491
1492    // --- peek_next_ready_after ---
1493
1494    #[test]
1495    fn peek_after_a_removed_item_returns_none() {
1496        // The decode thread's lookahead runs seconds ahead of what is audible.
1497        // Removing the track it is pre-decoding must end the lookahead, not send
1498        // it back to the top of the queue.
1499        let state = SharedPlayerState::new();
1500        let item0 = ready_item("track-0");
1501        let item1 = ready_item("track-1");
1502        let item2 = ready_item("track-2");
1503        let (id0, id1, id2) = (item0.id, item1.id, item2.id);
1504
1505        state.add_items(vec![item0, item1, item2]);
1506        assert_eq!(
1507            state.peek_next_ready_after(id1).map(|(id, _)| id),
1508            Some(id2)
1509        );
1510
1511        state.remove_item(id2);
1512        assert!(
1513            state.peek_next_ready_after(id2).is_none(),
1514            "a vanished reference must not resolve to the head of the queue"
1515        );
1516        assert_ne!(
1517            state.peek_next_ready_after(id2).map(|(id, _)| id),
1518            Some(id0)
1519        );
1520    }
1521
1522    // --- surviving_item_before ---
1523
1524    #[test]
1525    fn surviving_predecessor_skips_items_being_removed() {
1526        let state = SharedPlayerState::new();
1527        let items: Vec<_> = (0..4).map(|i| ready_item(&format!("track-{i}"))).collect();
1528        let ids: Vec<_> = items.iter().map(|i| i.id).collect();
1529        state.add_items(items);
1530
1531        // Deleting 1..=3 leaves 0 as the resume point for a cursor on 3.
1532        assert_eq!(
1533            state.surviving_item_before(ids[3], &ids[1..4]),
1534            Some(ids[0])
1535        );
1536        // Deleting everything from the top leaves nothing to resume after.
1537        assert_eq!(state.surviving_item_before(ids[2], &ids), None);
1538    }
1539
1540    // --- retreat_cursor ---
1541
1542    #[test]
1543    fn test_retreat_cursor_goes_to_previous_item() {
1544        let state = SharedPlayerState::new();
1545        let item0 = ready_item("track-0");
1546        let item1 = ready_item("track-1");
1547        let id0 = item0.id;
1548        let id1 = item1.id;
1549
1550        state.add_items(vec![item0, item1]);
1551        state.set_cursor(Some(id1));
1552
1553        let result = state.retreat_cursor();
1554        assert!(result.is_some(), "expected to retreat to previous item");
1555        assert_eq!(result.unwrap().0, id0, "should retreat to first item");
1556        assert_eq!(state.cursor(), Some(id0));
1557    }
1558
1559    #[test]
1560    fn test_retreat_cursor_returns_none_when_at_first_item() {
1561        let state = SharedPlayerState::new();
1562        let item0 = ready_item("only-track");
1563        let id0 = item0.id;
1564
1565        state.add_items(vec![item0]);
1566        state.set_cursor(Some(id0));
1567
1568        let result = state.retreat_cursor();
1569        assert!(result.is_none(), "cannot retreat before the first item");
1570        // Cursor stays on the first item.
1571        assert_eq!(state.cursor(), Some(id0));
1572    }
1573
1574    #[test]
1575    fn test_retreat_cursor_returns_none_when_cursor_is_unset() {
1576        let state = SharedPlayerState::new();
1577        state.add_items(vec![ready_item("track-0")]);
1578
1579        let result = state.retreat_cursor();
1580        assert!(
1581            result.is_none(),
1582            "retreat with no cursor should return None"
1583        );
1584    }
1585
1586    // --- derive_visible_queue ---
1587
1588    #[test]
1589    fn test_derive_visible_queue_statuses() {
1590        // playlist: [played, playing, queued]
1591        let state = SharedPlayerState::new();
1592        let item0 = ready_item("played-track");
1593        let item1 = ready_item("playing-track");
1594        let item2 = ready_item("queued-track");
1595        let id1 = item1.id;
1596
1597        state.add_items(vec![item0, item1, item2]);
1598        state.set_cursor(Some(id1));
1599
1600        let snap = state.derive_visible_queue();
1601
1602        assert_eq!(snap.entries.len(), 3);
1603        assert_eq!(snap.entries[0].status, QueueEntryStatus::Played);
1604        assert_eq!(snap.entries[1].status, QueueEntryStatus::Playing);
1605        assert_eq!(snap.entries[2].status, QueueEntryStatus::Queued);
1606        assert!(snap.has_playing);
1607        assert_eq!(snap.finished_count, 1);
1608        assert_eq!(snap.queue_count, 1);
1609    }
1610
1611    #[test]
1612    fn test_derive_visible_queue_downloading_statuses() {
1613        // A Downloading item at cursor → PriorityPending; after cursor → Downloading.
1614        let state = SharedPlayerState::new();
1615        let bytes_cursor = crate::remote::downloads::ByteFeed::new();
1616        let bytes_queued = crate::remote::downloads::ByteFeed::new();
1617        let dl_cursor = downloading_item("downloading-at-cursor", 1_000_000, bytes_cursor.clone());
1618        let dl_queued = downloading_item("downloading-queued", 500_000, bytes_queued.clone());
1619        let id_cursor = dl_cursor.id;
1620
1621        state.add_items(vec![dl_cursor, dl_queued]);
1622        state.set_cursor(Some(id_cursor));
1623
1624        let snap = state.derive_visible_queue();
1625
1626        assert_eq!(snap.entries[0].status, QueueEntryStatus::PriorityPending);
1627        assert_eq!(snap.entries[1].status, QueueEntryStatus::Downloading);
1628    }
1629
1630    #[test]
1631    fn progress_follows_the_counter_without_touching_the_playlist() {
1632        // The download thread writes bytes and nothing else. A queue derived
1633        // afterwards must see them — the version has not moved, and the load
1634        // state it was given is the one it still holds.
1635        let state = SharedPlayerState::new();
1636        let bytes = crate::remote::downloads::ByteFeed::new();
1637        let item = downloading_item("downloading", 1_000, bytes.clone());
1638        state.add_items(vec![item]);
1639
1640        let version = state.playlist_version();
1641        bytes.set(250);
1642
1643        let snap = state.derive_visible_queue();
1644        assert_eq!(snap.entries[0].download_progress, Some((250, 1_000)));
1645        assert_eq!(
1646            state.playlist_version(),
1647            version,
1648            "progress must not read as a queue mutation"
1649        );
1650        // Every transfer the process knows about, not just this playlist's —
1651        // a fetch with no queue item behind it is still a transfer, and the
1652        // store is what is asked. Other tests share it, so this looks for its
1653        // own rather than asserting the whole list.
1654        assert!(
1655            state
1656                .downloads_in_flight()
1657                .contains(&(snap.entries[0].id, 250, 1_000)),
1658            "the counter should be visible through the store"
1659        );
1660    }
1661
1662    #[test]
1663    fn test_derive_visible_queue_no_cursor_all_queued() {
1664        let state = SharedPlayerState::new();
1665        state.add_items(vec![ready_item("a"), ready_item("b"), ready_item("c")]);
1666
1667        let snap = state.derive_visible_queue();
1668
1669        assert_eq!(snap.entries.len(), 3);
1670        for entry in &snap.entries {
1671            assert_eq!(entry.status, QueueEntryStatus::Queued);
1672        }
1673        assert!(!snap.has_playing);
1674        assert_eq!(snap.finished_count, 0);
1675        assert_eq!(snap.queue_count, 3);
1676    }
1677
1678    // --- same_album_item_ids ---
1679
1680    fn make_album_item(title: &str, album: &str, album_artist: &str) -> PlaylistItem {
1681        PlaylistItem {
1682            playlist_entry_id: None,
1683            id: QueueItemId::new(),
1684            db_id: None,
1685            path: PathBuf::from(format!("/music/{title}.flac")),
1686            title: title.to_string(),
1687            artist: "Artist".to_string(),
1688            album_artist: album_artist.to_string(),
1689            album: album.to_string(),
1690            year: None,
1691            codec: Some("FLAC".to_string()),
1692            track_number: None,
1693            disc: None,
1694            duration_ms: Some(200_000),
1695            state: ItemState::Ready,
1696        }
1697    }
1698
1699    #[test]
1700    fn test_same_album_item_ids_returns_album_mates() {
1701        let state = SharedPlayerState::new();
1702        let a1 = make_album_item("A1", "Album A", "Artist A");
1703        let a2 = make_album_item("A2", "Album A", "Artist A");
1704        let b1 = make_album_item("B1", "Album B", "Artist B");
1705        let a3 = make_album_item("A3", "Album A", "Artist A");
1706
1707        let id_a1 = a1.id;
1708        let id_a2 = a2.id;
1709        let id_a3 = a3.id;
1710
1711        state.add_items(vec![a1, a2, b1, a3]);
1712
1713        let mates = state.same_album_item_ids(id_a1);
1714        assert_eq!(mates.len(), 2);
1715        assert!(mates.contains(&id_a2));
1716        assert!(mates.contains(&id_a3));
1717    }
1718
1719    #[test]
1720    fn test_same_album_item_ids_distinguishes_album_artists() {
1721        // Two albums named the same but by different artists — should NOT match.
1722        let state = SharedPlayerState::new();
1723        let a1 = make_album_item("A1", "Greatest Hits", "Artist A");
1724        let b1 = make_album_item("B1", "Greatest Hits", "Artist B");
1725
1726        let id_a1 = a1.id;
1727
1728        state.add_items(vec![a1, b1]);
1729
1730        let mates = state.same_album_item_ids(id_a1);
1731        assert!(mates.is_empty(), "different album_artist should not match");
1732    }
1733
1734    #[test]
1735    fn test_same_album_item_ids_unknown_id_returns_empty() {
1736        let state = SharedPlayerState::new();
1737        state.add_items(vec![ready_item("track-0")]);
1738
1739        let bogus = QueueItemId::new();
1740        let mates = state.same_album_item_ids(bogus);
1741        assert!(mates.is_empty());
1742    }
1743
1744    // --- update_item_metadata ---
1745
1746    #[test]
1747    fn test_update_item_metadata_leaves_library_tags_alone() {
1748        let state = SharedPlayerState::new();
1749        let mut item = make_album_item("A1", "Nite Versions (mixed)", "Soulwax");
1750        item.db_id = Some(29615);
1751        let id = item.id;
1752        state.add_items(vec![item]);
1753
1754        state.update_item_metadata(
1755            id,
1756            "[unknown]".into(),
1757            "Soulwax".into(),
1758            "Soulwax".into(),
1759            "Nite Versions".into(),
1760            Some(54_000),
1761        );
1762
1763        let pl = state.playlist.read();
1764        assert_eq!(pl.items[0].album, "Nite Versions (mixed)");
1765        assert_eq!(pl.items[0].title, "A1");
1766        assert_eq!(pl.items[0].duration_ms, Some(54_000));
1767    }
1768
1769    #[test]
1770    fn test_update_item_metadata_fills_in_an_item_with_nothing_behind_it() {
1771        let state = SharedPlayerState::new();
1772        let item = make_album_item("A1", "", "");
1773        let id = item.id;
1774        state.add_items(vec![item]);
1775
1776        state.update_item_metadata(
1777            id,
1778            "Teachers".into(),
1779            "Soulwax".into(),
1780            "Soulwax".into(),
1781            "Nite Versions".into(),
1782            Some(148_000),
1783        );
1784
1785        let pl = state.playlist.read();
1786        assert_eq!(pl.items[0].title, "Teachers");
1787        assert_eq!(pl.items[0].album, "Nite Versions");
1788        assert_eq!(pl.items[0].duration_ms, Some(148_000));
1789    }
1790
1791    // --- move_item_to ---
1792
1793    #[test]
1794    fn test_move_item_to_reorders_playlist() {
1795        // Start: [A, B, C]. Move C to after A → [A, C, B].
1796        let state = SharedPlayerState::new();
1797        let item_a = ready_item("A");
1798        let item_b = ready_item("B");
1799        let item_c = ready_item("C");
1800        let id_a = item_a.id;
1801        let id_b = item_b.id;
1802        let id_c = item_c.id;
1803
1804        state.add_items(vec![item_a, item_b, item_c]);
1805        state.move_item_to(id_c, Some(id_a));
1806
1807        let (items, _) = state.snapshot_playlist();
1808        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
1809        assert_eq!(titles, vec!["A", "C", "B"]);
1810        assert_eq!(items[0].id, id_a);
1811        assert_eq!(items[1].id, id_c);
1812        assert_eq!(items[2].id, id_b);
1813    }
1814
1815    #[test]
1816    fn test_move_item_to_front_when_after_is_none() {
1817        // Start: [A, B, C]. Move C to front (after=None) → [C, A, B].
1818        let state = SharedPlayerState::new();
1819        let item_a = ready_item("A");
1820        let item_b = ready_item("B");
1821        let item_c = ready_item("C");
1822        let id_c = item_c.id;
1823
1824        state.add_items(vec![item_a, item_b, item_c]);
1825        state.move_item_to(id_c, None);
1826
1827        let (items, _) = state.snapshot_playlist();
1828        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
1829        assert_eq!(titles, vec!["C", "A", "B"]);
1830    }
1831
1832    // --- move_items (batch) ---
1833
1834    #[test]
1835    fn test_move_items_batch_preserves_relative_order() {
1836        // Start: [A, B, C, D]. Move [A, C] after D → [B, D, A, C].
1837        let state = SharedPlayerState::new();
1838        let item_a = ready_item("A");
1839        let item_b = ready_item("B");
1840        let item_c = ready_item("C");
1841        let item_d = ready_item("D");
1842        let id_a = item_a.id;
1843        let id_b = item_b.id;
1844        let id_c = item_c.id;
1845        let id_d = item_d.id;
1846
1847        state.add_items(vec![item_a, item_b, item_c, item_d]);
1848        state.move_items(&[id_a, id_c], id_d, true);
1849
1850        let (items, _) = state.snapshot_playlist();
1851        let titles: Vec<&str> = items.iter().map(|i| i.title.as_str()).collect();
1852        assert_eq!(titles, vec!["B", "D", "A", "C"]);
1853        assert_eq!(items[0].id, id_b);
1854        assert_eq!(items[1].id, id_d);
1855        assert_eq!(items[2].id, id_a);
1856        assert_eq!(items[3].id, id_c);
1857    }
1858
1859    // --- pending_downloads ---
1860
1861    #[test]
1862    fn test_pending_downloads_collects_pending_with_db_id() {
1863        let state = SharedPlayerState::new();
1864        let mut item_a = ready_item("local");
1865        item_a.db_id = None;
1866
1867        let mut item_b = pending_item("remote-1");
1868        item_b.db_id = Some(10);
1869        let id_b = item_b.id;
1870
1871        let mut item_c = ready_item("cached");
1872        item_c.db_id = Some(20);
1873
1874        let mut item_d = pending_item("remote-2");
1875        item_d.db_id = Some(30);
1876        let id_d = item_d.id;
1877
1878        // Pending without db_id — should NOT appear (no way to download).
1879        let item_e = pending_item("orphan");
1880
1881        state.add_items(vec![item_a, item_b, item_c, item_d, item_e]);
1882
1883        let pending = state.pending_downloads();
1884        assert_eq!(pending.len(), 2);
1885        assert_eq!(pending[0], (10, id_b));
1886        assert_eq!(pending[1], (30, id_d));
1887    }
1888
1889    #[test]
1890    fn test_item_db_id_and_load_state() {
1891        let state = SharedPlayerState::new();
1892        let mut item = pending_item("track");
1893        item.db_id = Some(42);
1894        let id = item.id;
1895        state.add_items(vec![item]);
1896
1897        assert_eq!(state.item_db_id(id), Some(42));
1898        assert!(matches!(
1899            state.item_load_state(id),
1900            Some(LoadState::Pending)
1901        ));
1902
1903        state.update_item_state(id, ItemState::Ready);
1904        assert!(matches!(state.item_load_state(id), Some(LoadState::Ready)));
1905    }
1906}