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
use std::{
collections::VecDeque,
ops::Deref,
sync::{Arc, atomic::AtomicBool},
};
use lunar_lib::{
database::{Db, Entry, TransactionError, caching::IdCacheIterExt},
id::Id,
iterator_ext::IteratorExtensions,
};
use rand::{rngs::StdRng, seq::SliceRandom};
use selene_core::{
database::Library,
library::{album::Album, artist::Artist, collectable::Collectable, track::Track},
};
mod playlist_rng;
pub(crate) use playlist_rng::*;
use crate::{LoopMode, ShuffleMode};
mod core_impls;
#[derive(Clone)]
pub(crate) struct PlayingTrack {
pub source: Arc<Entry<Track>>,
pub position: Option<u32>,
}
impl PlayingTrack {
fn new(track: Arc<Entry<Track>>, position: Option<u32>) -> Self {
Self {
source: track,
position,
}
}
fn from_queue(track: Arc<Entry<Track>>) -> Self {
Self::new(track, None)
}
fn from_tracklist(track: Arc<Entry<Track>>, id: u32) -> Self {
Self::new(track, Some(id))
}
}
impl Deref for PlayingTrack {
type Target = Track;
fn deref(&self) -> &Self::Target {
&self.source
}
}
pub(crate) struct Playlist {
rng: PlaylistRng,
queue: VecDeque<Arc<Entry<Track>>>,
playlist: Vec<Playable>,
tracklist: Vec<Arc<Entry<Track>>>,
tracklist_index: Option<u32>,
shuffle_mode: ShuffleMode,
loop_mode: LoopMode,
looping: Arc<AtomicBool>,
}
impl Playlist {
/// Clears the playlist and the tracklist
pub(crate) fn clear(&mut self) {
self.playlist.clear();
self.tracklist.clear();
self.tracklist_index = None;
}
// Rebuilds the tracklist with new rng, moving whatever was currently playing to the front
fn rebuild_tracklist(&mut self) {
self.rng = PlaylistRng::new();
let mut rng = self.rng.current_rng();
let mut tracklist = self.build_tracklist(&mut rng);
if let Some(current) = self
.tracklist_index
.and_then(|i| self.tracklist.get(i as usize))
&& let Some(new_pos) = tracklist.iter().position(|t| Arc::ptr_eq(t, current))
{
tracklist.swap(0, new_pos);
self.tracklist_index = Some(0);
} else {
self.tracklist_index = None;
}
self.tracklist = tracklist;
}
pub fn reshuffle_tracklist(&mut self) {
self.rng = PlaylistRng::new();
let mut rng = self.rng.current_rng();
let mut tracklist = self.build_tracklist(&mut rng);
if let Some(current) = self
.tracklist_index
.and_then(|i| self.tracklist.get(i as usize))
&& let Some(new_pos) = tracklist.iter().position(|t| Arc::ptr_eq(t, current))
{
tracklist.swap(0, new_pos);
self.tracklist_index = Some(0);
} else {
self.tracklist_index = None;
}
}
fn shuffle_tracklist(&mut self, rng: &mut StdRng) {
self.tracklist = self.build_tracklist(rng);
}
fn build_tracklist(&self, rng: &mut StdRng) -> Vec<Arc<Entry<Track>>> {
let mut tracklist = self
.playlist
.iter()
.flat_map(|p| p.flatten_shuffle(self.shuffle_mode, rng))
.to_vec();
if matches!(self.shuffle_mode, ShuffleMode::Full) {
tracklist.shuffle(rng);
}
tracklist
}
}
#[derive(Clone)]
pub(crate) struct PlayableAlbum {
pub album: Arc<Entry<Album>>,
pub tracks: Vec<Arc<Entry<Track>>>,
}
impl PlayableAlbum {
fn from_album(
album: Arc<Entry<Album>>,
db: &Db<Library>,
) -> Result<PlayableAlbum, TransactionError> {
let tracks = album.tracks().cache_get(db)?;
Ok(Self { album, tracks })
}
}
#[derive(Clone)]
pub(crate) enum Playable {
Track {
track: Arc<Entry<Track>>,
},
Album {
album: PlayableAlbum,
},
Artist {
artist: Id<Artist>,
singles: Vec<Arc<Entry<Track>>>,
albums: Vec<PlayableAlbum>,
},
// Collection {
// items: CollectionItems,
// playables: Vec<Playable>,
// },
}
impl Playable {
#[must_use]
pub(crate) fn flatten(&self) -> Vec<Arc<Entry<Track>>> {
let mut buf: Vec<Arc<Entry<Track>>> = Vec::new();
let mut stack = vec![self];
while let Some(last) = stack.pop() {
match last {
Playable::Track { track } => buf.push(track.clone()),
Playable::Album { album } => buf.extend(album.tracks.iter().map(Arc::clone)),
Playable::Artist {
singles: tracks,
albums,
..
} => {
buf.extend(albums.iter().flat_map(|a| a.tracks.iter().map(Arc::clone)));
buf.extend(tracks.iter().map(Arc::clone));
} // Playable::Collection { playables, .. } => stack.extend(playables),
}
}
buf
}
#[must_use]
pub(crate) fn flatten_shuffle(
&self,
shuffle_mode: ShuffleMode,
rng: &mut StdRng,
) -> Vec<Arc<Entry<Track>>> {
let mut buf = Vec::new();
let mut stack = vec![self];
while let Some(last) = stack.pop() {
match last {
Playable::Track { track } => buf.push(track.clone()),
Playable::Album { album, .. } => {
let mut album = album.tracks.iter().map(Arc::clone).collect::<Vec<_>>();
if matches!(
shuffle_mode,
ShuffleMode::TracksOnly | ShuffleMode::CollectionsAndTracks
) {
album.shuffle(rng);
}
buf.extend(album);
}
Playable::Artist {
singles: tracks,
albums,
..
} => {
let mut items: Vec<_> = albums
.iter()
.map(|a| a.tracks.iter().map(Arc::clone).collect::<Vec<_>>())
.chain(tracks.iter().map(|t| vec![t.clone()]))
.collect();
if matches!(
shuffle_mode,
ShuffleMode::Full | ShuffleMode::CollectionsAndTracks
) {
items.shuffle(rng);
}
buf.extend(items.into_iter().flat_map(|mut tracks| {
if matches!(
shuffle_mode,
ShuffleMode::TracksOnly | ShuffleMode::CollectionsAndTracks
) {
tracks.shuffle(rng);
}
tracks
}));
} // Playable::Collection { playables, .. } => {
// let mut playables = playables.iter().collect::<Vec<_>>();
// if matches!(
// shuffle_mode,
// ShuffleMode::Full | ShuffleMode::CollectionsAndTracks
// ) {
// playables.shuffle(rng);
// }
// stack.extend(playables.into_iter().rev());
// }
}
}
buf
}
pub(crate) fn from_collectable(
collectable: Collectable,
db: &Db<Library>,
) -> Result<Playable, TransactionError> {
let playable = match collectable {
Collectable::Track(track_id) => {
let track = track_id
.cache_get(db)?
.ok_or(TransactionError::MissingEntry)?;
Playable::Track { track }
}
Collectable::Artist(artist_id) => {
let artist = artist_id
.cache_get(db)?
.ok_or(TransactionError::MissingEntry)?;
let mut singles = artist.tracks().cache_get(db)?;
singles.retain(|t| t.is_single());
let albums: Vec<PlayableAlbum> = artist
.albums()
.cache_get(db)?
.into_iter()
.map(|a| PlayableAlbum::from_album(a, db))
.collect::<Result<_, _>>()?;
Playable::Artist {
artist: artist_id,
singles,
albums,
}
}
Collectable::Album(album_id) => {
let album = album_id
.cache_get(db)?
.ok_or(TransactionError::MissingEntry)?;
Playable::Album {
album: PlayableAlbum::from_album(album, db)?,
}
} // Collectable::Collection(collection) => {
// todo!()
// struct Frame<I: Iterator<Item = Collectable>> {
// collection_id: Id<Collection>,
// remaining: I,
// playables: Vec<Playable>,
// ancestors: HashSet<Id<Collection>>,
// }
// let root = collection
// .db_get(db)?
// .ok_or(TransactionError::MissingEntry)?;
// let mut frames = vec![Frame {
// collection,
// remaining: root.collectables(db)?.into_iter(),
// playables: Vec::new(),
// ancestors: HashSet::from([collection]),
// }];
// 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 = inner_id
// .cache_get(db)?
// .ok_or(TransactionError::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(crate) 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),
}
}
}