selene-daemon 0.4.2

Official music player daemon for Selene
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
use std::{
    collections::{HashSet, VecDeque},
    fmt::Display,
    sync::{
        atomic::{AtomicU8, Ordering},
        mpsc::Sender,
    },
};

use blake3::Hash;
use lunar_lib::database::{DatabaseEntry, DatabaseError};
use rand::{rng, seq::SliceRandom};
use selene_core::{
    database::LibraryDb,
    library::{
        album::Album,
        artist::{Artist, ArtistId},
        collection::{Collectable, Collection, CollectionId},
        track::{Track, TrackId, track_meta::TrackMeta},
    },
    media_container::MediaContainer,
};
use serde::{Deserialize, Serialize};

use crate::{PlayerEvent, event_handler::EventTx};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedTrack {
    pub track: PlayableTrack,
    pub position: usize,

    pub album: Option<Album>,
    pub album_artists: Option<Vec<Artist>>,

    pub artists: Vec<Artist>,
}

impl ResolvedTrack {
    #[cfg(feature = "mpris")]
    pub fn mpris_id(&self) -> mpris_server::TrackId {
        use mpris_server::zbus::zvariant::ObjectPath;

        ObjectPath::from_string_unchecked(format!(
            "/org/mpris/MediaPlayer2/TrackList/{}",
            self.position,
        ))
        .into()
    }

    pub fn from_tracklist(
        track: PlayableTrack,
        id: usize,
        db: &LibraryDb,
    ) -> Result<Self, DatabaseError> {
        let album = track.metadata().album(db)?;
        let album_artists = album
            .as_ref()
            .map(|a| a.artists().artists(db))
            .transpose()?;

        Ok(Self {
            position: id,
            album,
            album_artists,
            artists: track.metadata().artists(db)?,
            track,
        })
    }
}

#[derive(Debug)]
pub struct Playlist {
    event_tx: Sender<PlayerEvent>,

    pub queue: VecDeque<PlayableTrack>,
    playlist: Vec<Playable>,
    tracklist: Vec<PlayableTrack>,
    tracklist_index: Option<usize>,

    pub shuffle_mode: ShuffleMode,
    pub loop_mode: LoopMode,
}

impl Playlist {
    #[must_use]
    pub fn new(event_tx: Sender<PlayerEvent>) -> Self {
        Self {
            event_tx,

            queue: VecDeque::new(),
            playlist: Vec::new(),
            tracklist: Vec::new(),
            tracklist_index: None,

            shuffle_mode: ShuffleMode::None,
            loop_mode: LoopMode::None,
        }
    }

    /// Clears the playlist and the tracklist
    pub fn clear(&mut self) {
        self.playlist.clear();
        self.tracklist.clear();
        self.tracklist_index = None;
        self.event_tx.event(PlayerEvent::TracklistChanged {
            tracklist: Vec::new(),
        });
    }

    pub fn position(&self) -> (usize, usize) {
        (self.tracklist_index.unwrap_or(0), self.tracklist.len())
    }

    /// Peeks at the next item
    ///
    /// If this function returns none, it means the end of the track list has been reached, and the next consumption will follow the [`LoopMode`]
    pub fn peek_next(&self, db: &LibraryDb) -> Result<Option<ResolvedTrack>, DatabaseError> {
        if self.tracklist.is_empty() {
            return Ok(None);
        }

        match self.loop_mode {
            LoopMode::None | LoopMode::LoopAndReshuffle => {
                let start = self.tracklist_index.map_or(0, |i| i + 1);

                for i in start..self.tracklist.len() {
                    if self.tracklist[i].can_play() {
                        let resolved =
                            ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                        return Ok(Some(resolved));
                    }
                }
            }
            LoopMode::Loop => {
                let start = self.tracklist_index.map_or(0, |i| i + 1);

                for n in 0..self.tracklist.len() {
                    let i = (start + n) % self.tracklist.len();

                    if self.tracklist[i].can_play() {
                        let resolved =
                            ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                        return Ok(Some(resolved));
                    }
                }
            }
            LoopMode::RepeatTrack => {
                let Some(i) = self.tracklist_index else {
                    return Ok(None);
                };
                if self.tracklist[i].can_play() {
                    let resolved = ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                    return Ok(Some(resolved));
                }
            }
        }
        Ok(None)
    }

    /// Returns the item at the current index
    pub fn current(&mut self, db: &LibraryDb) -> Result<Option<ResolvedTrack>, DatabaseError> {
        let Some(i) = self.tracklist_index else {
            return Ok(None);
        };
        let resolved = ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
        Ok(Some(resolved))
    }

    /// Moves to the next item and returns it
    ///
    /// If this function returns none, it means there is nothing left to play or nothing to play
    ///
    /// This function will skip tracks without a container.
    pub fn pop_next(&mut self, db: &LibraryDb) -> Result<Option<ResolvedTrack>, DatabaseError> {
        if self.tracklist.is_empty() {
            return Ok(None);
        }

        match self.loop_mode {
            LoopMode::None => {
                let start = self.tracklist_index.map_or(0, |i| i + 1);

                for i in start..self.tracklist.len() {
                    if self.tracklist[i].can_play() {
                        self.tracklist_index = Some(i);
                        let resolved =
                            ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                        return Ok(Some(resolved));
                    }
                }
            }
            LoopMode::Loop => {
                let start = self.tracklist_index.map_or(0, |i| i + 1);

                for n in 0..self.tracklist.len() {
                    let i = (start + n) % self.tracklist.len();

                    if self.tracklist[i].can_play() {
                        self.tracklist_index = Some(i);
                        let resolved =
                            ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                        return Ok(Some(resolved));
                    }
                }
            }
            LoopMode::LoopAndReshuffle => {
                let start = self.tracklist_index.map_or(0, |i| i + 1);

                for n in 0..self.tracklist.len() {
                    let i = (start + n) % self.tracklist.len();

                    if i == 0 && n != 0 {
                        self.rebuild_tracklist();
                    }

                    if self.tracklist[i].can_play() {
                        self.tracklist_index = Some(i);
                        let resolved =
                            ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                        return Ok(Some(resolved));
                    }
                }
            }
            LoopMode::RepeatTrack => {
                let Some(i) = self.tracklist_index else {
                    return Ok(None);
                };
                if self.tracklist[i].can_play() {
                    let resolved = ResolvedTrack::from_tracklist(self.tracklist[i].clone(), i, db)?;
                    return Ok(Some(resolved));
                }
            }
        }
        Ok(None)
    }

    /// Rebuilds the interior tracklist
    pub fn rebuild_tracklist(&mut self) {
        let mut index_map: Vec<usize> = (0..self.playlist.len()).collect();
        if matches!(
            self.shuffle_mode,
            ShuffleMode::CollectionsOnly | ShuffleMode::CollectionsAndTracks
        ) {
            index_map.shuffle(&mut rng());
        }

        let mut tracklist: Vec<_> = index_map
            .into_iter()
            .flat_map(|i| self.playlist[i].clone().flatten_shuffle(self.shuffle_mode))
            .collect();

        if matches!(self.shuffle_mode, ShuffleMode::Full) {
            tracklist.shuffle(&mut rng());
        }

        self.tracklist_index = None;
        self.tracklist = tracklist;
        self.event_tx.event(PlayerEvent::TracklistChanged {
            tracklist: self.tracklist().iter().map(|t| t.id()).collect(),
        });
    }

    /// If the looping mode is set to `Loop`, this function will modulo the input
    ///
    /// If the looping mode is set to `LoopAndReshuffle`, this function will modulo the input and reshuffle the tracklist
    pub fn tracklist_seek(&mut self, to: isize, increment: bool) -> usize {
        let to = if increment {
            self.tracklist_index.unwrap_or(0) as isize + to
        } else {
            to
        };

        let len = self.tracklist.len() as isize;

        match self.loop_mode {
            LoopMode::None => {
                self.tracklist_index = Some(to.clamp(0, len) as usize);
            }
            LoopMode::Loop => {
                self.tracklist_index = Some(to.rem_euclid(len) as usize);
            }
            LoopMode::LoopAndReshuffle => {
                if to >= len && !matches!(self.shuffle_mode, ShuffleMode::None) {
                    self.rebuild_tracklist();
                }
                self.tracklist_index = Some(to.rem_euclid(len) as usize);
            }
            LoopMode::RepeatTrack => {
                if !increment {
                    self.tracklist_index = Some(to.clamp(0, len) as usize);
                }
            }
        }
        self.tracklist_index.unwrap()
    }

    /// Gets the current state of the playlist
    #[must_use]
    pub fn playlist(&self) -> &[Playable] {
        &self.playlist
    }

    /// Sets the current state of the playlist
    pub fn set_playlist(&mut self, playlist: impl IntoIterator<Item = Playable>) {
        self.playlist = playlist.into_iter().collect();
        self.rebuild_tracklist();
    }

    pub fn queue_extend(&mut self, with: impl IntoIterator<Item = Playable>) {
        self.queue.extend(
            with.into_iter()
                .flat_map(|p| p.flatten_shuffle(ShuffleMode::None)),
        );
    }

    #[must_use]
    pub fn tracklist(&self) -> &[PlayableTrack] {
        &self.tracklist
    }

    // Returns the hash of the queue
    #[must_use]
    pub fn queue_hash(&self) -> Hash {
        let mut hash_seed = Vec::with_capacity(self.queue.len() * 32);
        for playable in &self.queue {
            hash_seed.extend(*playable.track);
        }
        blake3::hash(&hash_seed)
    }

    // Returns the hash of the playlist
    #[must_use]
    pub fn playlist_hash(&self) -> Hash {
        let mut hash_seed = Vec::with_capacity(self.playlist.len() * 32);
        for playable in &self.playlist {
            hash_seed.extend(playable.id_as_bytes());
        }
        blake3::hash(&hash_seed)
    }
}

impl Extend<Playable> for Playlist {
    fn extend<T: IntoIterator<Item = Playable>>(&mut self, iter: T) {
        let mut vec: Vec<_> = iter.into_iter().collect();
        if matches!(
            self.shuffle_mode,
            ShuffleMode::CollectionsOnly | ShuffleMode::CollectionsAndTracks
        ) {
            vec.shuffle(&mut rng());
        }

        self.tracklist.extend(
            vec.iter()
                .cloned()
                .flat_map(|p| p.flatten_shuffle(self.shuffle_mode)),
        );
        self.event_tx.event(PlayerEvent::TracklistChanged {
            tracklist: self.tracklist().iter().map(|t| t.id()).collect(),
        });
        self.playlist.extend(vec);
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PlayableTrack {
    container: Option<MediaContainer>,
    metadata: TrackMeta,
    track: TrackId,
}

impl PartialEq for PlayableTrack {
    fn eq(&self, other: &Self) -> bool {
        self.track == other.track
    }
}

impl Eq for PlayableTrack {}

impl PlayableTrack {
    #[must_use]
    pub fn container(&self) -> Option<&MediaContainer> {
        self.container.as_ref()
    }

    #[must_use]
    pub fn can_play(&self) -> bool {
        self.container.is_some()
    }

    #[must_use]
    pub fn metadata(&self) -> &TrackMeta {
        &self.metadata
    }

    #[must_use]
    pub fn id(&self) -> TrackId {
        self.track
    }

    #[must_use]
    pub fn from_track(track: &Track, fallback: bool) -> Self {
        Self {
            container: if fallback {
                Some(
                    track
                        .lib_container()
                        .unwrap_or(track.src_container())
                        .clone(),
                )
            } else {
                track.lib_container().cloned()
            },
            metadata: track.metadata.clone(),
            track: track.id(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PlayableAlbum {
    album: Album,
    tracks: Vec<PlayableTrack>,
}
impl PlayableAlbum {
    fn from_album(album: Album, db: &LibraryDb) -> Result<PlayableAlbum, DatabaseError> {
        let tracks = album
            .tracks(db)?
            .iter()
            .map(|t| PlayableTrack::from_track(t, false))
            .collect();

        Ok(Self { album, tracks })
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Playable {
    Track {
        track: Box<PlayableTrack>,
    },
    Album {
        album: Box<PlayableAlbum>,
    },
    Artist {
        artist: ArtistId,
        tracks: Vec<PlayableTrack>,
        albums: Vec<PlayableAlbum>,
    },
    Collection {
        collection: CollectionId,
        playables: Vec<Playable>,
    },
}

impl Playable {
    #[must_use]
    pub fn flatten_shuffle(self, shuffle_mode: ShuffleMode) -> Vec<PlayableTrack> {
        let mut buf = Vec::new();
        let mut stack = vec![self];

        while let Some(last) = stack.pop() {
            match last {
                Playable::Track { track } => buf.push(*track),
                Playable::Album { mut album, .. } => {
                    if matches!(
                        shuffle_mode,
                        ShuffleMode::TracksOnly | ShuffleMode::CollectionsAndTracks
                    ) {
                        album.tracks.shuffle(&mut rng());
                    }

                    buf.extend(album.tracks);
                }
                Playable::Artist {
                    mut tracks,
                    mut albums,
                    ..
                } => {
                    if matches!(
                        shuffle_mode,
                        ShuffleMode::Full | ShuffleMode::CollectionsAndTracks
                    ) {
                        albums.shuffle(&mut rng());
                    }

                    buf.extend(albums.into_iter().flat_map(|mut a| {
                        if matches!(
                            shuffle_mode,
                            ShuffleMode::TracksOnly | ShuffleMode::CollectionsAndTracks
                        ) {
                            a.tracks.shuffle(&mut rng());
                        }

                        a.tracks
                    }));

                    if matches!(
                        shuffle_mode,
                        ShuffleMode::TracksOnly | ShuffleMode::CollectionsAndTracks
                    ) {
                        tracks.shuffle(&mut rng());
                    }

                    buf.extend(tracks);
                }
                Playable::Collection { mut playables, .. } => {
                    if matches!(
                        shuffle_mode,
                        ShuffleMode::Full | ShuffleMode::CollectionsAndTracks
                    ) {
                        playables.shuffle(&mut rng());
                    }

                    stack.extend(playables);
                }
            }
        }

        if matches!(shuffle_mode, ShuffleMode::Full) {
            buf.shuffle(&mut rng());
        }

        buf
    }

    #[must_use]
    pub fn flatten(self) -> Vec<PlayableTrack> {
        let mut buf = Vec::new();
        let mut stack = vec![self];

        while let Some(last) = stack.pop() {
            match last {
                Playable::Track { track } => buf.push(*track),
                Playable::Album { album } => buf.extend(album.tracks),
                Playable::Artist { tracks, albums, .. } => {
                    buf.extend(albums.into_iter().flat_map(|a| a.tracks));
                    buf.extend(tracks);
                }
                Playable::Collection { playables, .. } => stack.extend(playables),
            }
        }

        buf
    }

    pub fn from_collectable(
        collectable: Collectable,
        db: &LibraryDb,
    ) -> Result<Playable, DatabaseError> {
        let playable = match collectable {
            Collectable::Track(track_id) => {
                let track = Track::db_get_from(track_id, db)?.ok_or(DatabaseError::MissingEntry)?;
                Playable::Track {
                    track: Box::new(PlayableTrack::from_track(&track, false)),
                }
            }
            Collectable::Artist(artist_id) => {
                let artist =
                    Artist::db_get_from(artist_id, db)?.ok_or(DatabaseError::MissingEntry)?;

                let tracks = artist
                    .all_tracks(db)?
                    .iter()
                    .map(|t| PlayableTrack::from_track(t, false))
                    .collect();

                let albums: Vec<PlayableAlbum> = artist
                    .albums(db)?
                    .into_iter()
                    .map(|a| PlayableAlbum::from_album(a, db))
                    .collect::<Result<_, _>>()?;

                Playable::Artist {
                    artist: artist_id,
                    tracks,
                    albums,
                }
            }
            Collectable::Album(album_id) => {
                let album = Album::db_get_from(album_id, db)?.ok_or(DatabaseError::MissingEntry)?;

                Playable::Album {
                    album: Box::new(PlayableAlbum::from_album(album, db)?),
                }
            }
            Collectable::Collection(collection_id) => {
                struct Frame<I: Iterator<Item = Collectable>> {
                    collection_id: CollectionId,
                    remaining: I,
                    playables: Vec<Playable>,
                    ancestors: HashSet<CollectionId>,
                }

                let root = Collection::db_get_from(collection_id, db)?
                    .ok_or(DatabaseError::MissingEntry)?;
                let mut frames = vec![Frame {
                    collection_id,
                    remaining: root.collectables(db)?.into_iter(),
                    playables: Vec::new(),
                    ancestors: HashSet::from([collection_id]),
                }];

                loop {
                    let frame = frames.last_mut().unwrap();
                    if let Some(item) = frame.remaining.next() {
                        match item {
                            Collectable::Collection(inner_id) => {
                                assert!(
                                    !frame.ancestors.contains(&inner_id),
                                    "Invalid collection: Cyclical reference"
                                );

                                let mut child_ancestors = frame.ancestors.clone();
                                child_ancestors.insert(inner_id);

                                let inner = Collection::db_get_from(inner_id, db)?
                                    .ok_or(DatabaseError::MissingEntry)?;
                                frames.push(Frame {
                                    collection_id: inner_id,
                                    remaining: inner.collectables(db)?.into_iter(),
                                    playables: Vec::new(),
                                    ancestors: child_ancestors,
                                });
                            }
                            other => {
                                frame.playables.push(Playable::from_collectable(other, db)?);
                            }
                        }
                    } else {
                        let completed = frames.pop().unwrap();
                        let result = Playable::Collection {
                            collection: completed.collection_id,
                            playables: completed.playables,
                        };
                        match frames.last_mut() {
                            Some(parent) => parent.playables.push(result),
                            None => return Ok(result),
                        }
                    }
                }
            }
        };
        Ok(playable)
    }

    #[must_use]
    pub fn to_collectable(&self) -> Collectable {
        match self {
            Playable::Track { track } => Collectable::Track(track.id()),
            Playable::Album { album } => Collectable::Album(album.album.id()),
            Playable::Artist { artist, .. } => Collectable::Artist(*artist),
            Playable::Collection { collection, .. } => Collectable::Collection(*collection),
        }
    }

    fn id_as_bytes(&self) -> [u8; 32] {
        match self {
            Playable::Track { track } => *track.track,
            Playable::Album { album, .. } => *album.album.id(),
            Playable::Artist { artist, .. } => **artist,
            Playable::Collection { collection, .. } => **collection,
        }
    }

    pub fn display(&self) -> Result<String, DatabaseError> {
        match self {
            Playable::Track { track } => Ok(format!("{} (Track)", track.metadata.safe_title())),
            Playable::Album { album, .. } => Ok(format!("{} (Album)", album.album.name())),
            Playable::Artist { artist, .. } => {
                let artist = Artist::db_get(*artist)?.ok_or(DatabaseError::MissingEntry)?;
                Ok(format!("{} (Artist)", artist.name()))
            }
            Playable::Collection { collection, .. } => {
                let collection =
                    Collection::db_get(*collection)?.ok_or(DatabaseError::MissingEntry)?;
                Ok(format!("{} (Collection)", collection.name))
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum ShuffleMode {
    /// Tracks are not shuffled, they are played as is
    None,

    /// Only collections are shuffled, meaning the collections are shuffled, but not the contents
    CollectionsOnly,

    /// Randomize tracks only, meaning the contents of collections are shuffled, but not the collections themselves
    TracksOnly,

    /// Randomize collection order and the tracks inside the collection
    CollectionsAndTracks,

    /// Randomizes the order of everything
    Full,
}

impl Display for ShuffleMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ShuffleMode::None => f.write_str("None"),
            ShuffleMode::CollectionsOnly => f.write_str("Collections Only"),
            ShuffleMode::TracksOnly => f.write_str("Tracks Only"),
            ShuffleMode::CollectionsAndTracks => f.write_str("Collections And Tracks"),
            ShuffleMode::Full => f.write_str("Full"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum LoopMode {
    /// Disables looping
    None,

    /// When the end of the tracklist is reached, loop back to the beginning
    Loop,

    /// When the end of the tracklist is reached, reshuffle the tracklist using the shuffle mode and loop
    LoopAndReshuffle,
    RepeatTrack,
}

impl Display for LoopMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LoopMode::None => f.write_str("None"),
            LoopMode::Loop => f.write_str("Loop"),
            LoopMode::LoopAndReshuffle => f.write_str("Loop And Reshuffle"),
            LoopMode::RepeatTrack => f.write_str("Repeat Track"),
        }
    }
}

#[repr(u8)]
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum PlaybackStatus {
    Playing,
    Paused,
    Stopped,
}

impl Display for PlaybackStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PlaybackStatus::Playing => f.write_str("Playing"),
            PlaybackStatus::Paused => f.write_str("Paused"),
            PlaybackStatus::Stopped => f.write_str("Stopped"),
        }
    }
}

pub struct AtomicPlaybackStatus(AtomicU8);

impl AtomicPlaybackStatus {
    #[must_use]
    pub fn new(state: PlaybackStatus) -> Self {
        Self(AtomicU8::new(state as u8))
    }

    pub fn load(&self, order: Ordering) -> PlaybackStatus {
        match self.0.load(order) {
            0 => PlaybackStatus::Playing,
            1 => PlaybackStatus::Paused,
            2 => PlaybackStatus::Stopped,
            _ => unreachable!(),
        }
    }

    pub fn store(&self, state: PlaybackStatus, order: Ordering) {
        self.0.store(state as u8, order);
    }
}