selene-daemon 0.1.0

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
use std::{
    collections::{HashSet, VecDeque},
    fmt::Display,
};

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracklistTrack {
    pub playable: Box<PlayableTrack>,
    pub id: usize,
}

impl TracklistTrack {
    pub fn can_play(&self) -> bool {
        self.playable.container.is_some()
    }

    #[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.id))
            .into()
    }
}

#[derive(Debug)]
pub struct Playlist {
    pub queue: VecDeque<PlayableTrack>,
    playlist: Vec<Playable>,
    tracklist: Vec<TracklistTrack>,
    tracklist_index: Option<usize>,

    pub shuffle_mode: ShuffleMode,
    pub loop_mode: LoopMode,
}

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

impl Playlist {
    pub fn new() -> Self {
        Self {
            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;
    }

    /// 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) -> Option<&TracklistTrack> {
        if let Some(tracklist_index) = self.tracklist_index {
            self.tracklist.get(tracklist_index + 1)
        } else {
            self.tracklist.first()
        }
    }

    /// Returns the item at the current index
    pub fn current(&mut self) -> Option<&TracklistTrack> {
        let i = self.tracklist_index?;
        self.tracklist.get(i)
    }

    /// 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) -> Option<&TracklistTrack> {
        if self.tracklist.is_empty() {
            return None;
        }

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

                for i in start..self.tracklist.len() {
                    if self.tracklist[i].can_play() {
                        self.tracklist_index = Some(i);
                        return Some(&self.tracklist[i]);
                    }
                }

                None
            }
            LoopMode::Loop => {
                let start = self.tracklist_index.map(|i| i + 1).unwrap_or(0);

                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);
                        return Some(&self.tracklist[i]);
                    }
                }

                None
            }
            LoopMode::LoopAndReshuffle => {
                let start = self.tracklist_index.map(|i| i + 1).unwrap_or(0);

                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);
                        return Some(&self.tracklist[i]);
                    }
                }

                None
            }
            LoopMode::RepeatTrack => {
                let i = self.tracklist_index?;
                self.tracklist[i].can_play().then_some(&self.tracklist[i])
            }
        }
    }

    /// 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
            .into_iter()
            .enumerate()
            .map(|(i, t)| TracklistTrack {
                playable: Box::new(t),
                id: i,
            })
            .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 | LoopMode::RepeatTrack => {
                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);
            }
        }
        self.tracklist_index.unwrap()
    }

    /// Gets the current state of the playlist
    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)),
        );
    }

    pub fn tracklist(&self) -> &[TracklistTrack] {
        &self.tracklist
    }

    // Returns the hash of the queue
    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.as_bytes());
        }
        blake3::hash(&hash_seed)
    }

    // Returns the hash of the playlist
    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.hash().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))
                .enumerate()
                .map(|(i, p)| TracklistTrack {
                    playable: Box::new(p),
                    id: i,
                }),
        );
        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 {
    pub fn container(&self) -> Option<&MediaContainer> {
        self.container.as_ref()
    }

    pub fn metadata(&self) -> &TrackMeta {
        &self.metadata
    }

    pub fn id(&self) -> TrackId {
        self.track
    }

    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) -> Result<PlayableAlbum, DatabaseError> {
        let tracks = album
            .tracks()?
            .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 {
    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
    }

    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) -> Result<Playable, DatabaseError> {
        let playable = match collectable {
            Collectable::Track(track_id) => {
                let track = Track::db_get(track_id)?.ok_or(DatabaseError::MissingEntry)?;
                Playable::Track {
                    track: Box::new(PlayableTrack::from_track(&track, false)),
                }
            }
            Collectable::Artist(artist_id) => {
                let artist = Artist::db_get(artist_id)?.ok_or(DatabaseError::MissingEntry)?;

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

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

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

                Playable::Album {
                    album: Box::new(PlayableAlbum::from_album(album)?),
                }
            }
            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(collection_id)?.ok_or(DatabaseError::MissingEntry)?;
                let mut frames = vec![Frame {
                    collection_id,
                    remaining: root.collectables.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) => {
                                if frame.ancestors.contains(&inner_id) {
                                    panic!("Invalid collection: Cyclical reference")
                                }

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

                                let inner = Collection::db_get(inner_id)?
                                    .ok_or(DatabaseError::MissingEntry)?;
                                frames.push(Frame {
                                    collection_id: inner_id,
                                    remaining: inner.collectables.into_iter(),
                                    playables: Vec::new(),
                                    ancestors: child_ancestors,
                                });
                            }
                            other => {
                                frame.playables.push(Playable::from_collectable(other)?);
                            }
                        }
                    } 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)
    }

    fn hash(&self) -> Hash {
        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))
            }
        }
    }
}

#[cfg(feature = "clap")]
use clap::ValueEnum;

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(feature = "clap", derive(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("RandomizeCollectionsOnly"),
            ShuffleMode::TracksOnly => f.write_str("RandomizeTracksOnly"),
            ShuffleMode::CollectionsAndTracks => f.write_str("RandomizeCollectionsAndTracks"),
            ShuffleMode::Full => f.write_str("RandomizeFull"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(feature = "clap", derive(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("LoopAndReshuffle"),
            LoopMode::RepeatTrack => f.write_str("RepeatTrack"),
        }
    }
}