aboutsummaryrefslogtreecommitdiffstats
path: root/src/queue.rs
blob: 17f21436f40d77fc005396bb70dd3ba5b3ba663e (plain) (blame)
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
/*
 * This file is a part of RSPlayer
 * Licensed under the GPL-3.0 License
 * Copyright (C) 2026 Salmonik @ salmonik@tuta.io
 * https://codeberg.org/salmonik/RSPlayer
*/

use rand::SeedableRng;
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, PartialEq)]
pub enum ShuffleMode {
    None,
    All,
    Album,
    Albums,
}

#[derive(Debug, Default, Clone)]
pub struct AudioMetadata {
    pub title: Option<String>,
    pub artist: Option<String>,
    pub album: Option<String>,
    pub track_number: Option<i32>,
    pub duration_secs: Option<f64>,
}

pub fn extract_metadata(path: &Path) -> Option<AudioMetadata> {
    use symphonia::core::formats::probe::Hint;
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::StandardTag;

    let file = std::fs::File::open(path).ok()?;
    let mss = MediaSourceStream::new(Box::new(file), Default::default());

    let hint = Hint::new();
    let mut probed = symphonia::default::get_probe()
        .probe(&hint, mss, Default::default(), Default::default())
        .ok()?;

    // Extract duration from track's num_frames and time_base
    let duration_secs = probed
        .tracks()
        .iter()
        .find(|t| t.num_frames.is_some() && t.time_base.is_some())
        .and_then(|t| {
            let n_frames = t.num_frames?;
            let tb = t.time_base?;
            Some(n_frames as f64 * tb.numer.get() as f64 / tb.denom.get() as f64)
        });

    let mut metadata = AudioMetadata {
        duration_secs,
        ..Default::default()
    };

    {
        let mut meta = probed.metadata();
        if let Some(rev) = meta.skip_to_latest() {
            for tag in &rev.media.tags {
                match &tag.std {
                    Some(StandardTag::TrackTitle(value)) => {
                        metadata.title = Some(value.to_string());
                    }
                    Some(StandardTag::Artist(value)) => {
                        metadata.artist = Some(value.to_string());
                    }
                    Some(StandardTag::AlbumArtist(value)) => {
                        metadata.artist = Some(value.to_string());
                    }
                    Some(StandardTag::Album(value)) => {
                        metadata.album = Some(value.to_string());
                    }
                    Some(StandardTag::TrackNumber(value)) => {
                        metadata.track_number = value.to_string().parse().ok();
                    }
                    _ => {}
                }
            }
        }
    }

    if metadata.title.is_some()
        || metadata.artist.is_some()
        || metadata.album.is_some()
        || metadata.track_number.is_some()
        || metadata.duration_secs.is_some()
    {
        Some(metadata)
    } else {
        None
    }
}

#[derive(Debug, Clone)]
pub struct Track {
    pub path: PathBuf,
    pub title: Option<String>,
    pub artist: Option<String>,
    pub album: Option<String>,
    pub track_number: Option<i32>,
    pub duration_secs: Option<f64>,
    pub is_stream: bool,
}

impl Track {
    pub fn from_path(path: PathBuf) -> Self {
        let path_str = path.to_string_lossy();
        if path_str.starts_with("http://") || path_str.starts_with("https://") {
            return Track::from_url(&path_str);
        }
        let metadata = extract_metadata(&path);
        let metadata = metadata.as_ref();
        Track {
            path,
            title: metadata.and_then(|m| m.title.clone()),
            artist: metadata.and_then(|m| m.artist.clone()),
            album: metadata.and_then(|m| m.album.clone()),
            track_number: metadata.and_then(|m| m.track_number),
            duration_secs: metadata.and_then(|m| m.duration_secs),
            is_stream: false,
        }
    }

    pub fn from_url(url: &str) -> Self {
        let clean_url = url.split('?').next().unwrap_or(url);
        let url_path = Path::new(clean_url);
        let title = url_path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(|s| s.to_string())
            .or_else(|| {
                url_path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .map(|s| s.to_string())
            })
            .unwrap_or_else(|| url.to_string());
        Track {
            path: PathBuf::from(url),
            title: Some(title),
            artist: None,
            album: None,
            track_number: None,
            duration_secs: None,
            is_stream: true,
        }
    }

    pub fn display_string(&self, index: usize, total: usize) -> String {
        let album_artist = self
            .artist
            .clone()
            .or_else(|| self.album.clone())
            .unwrap_or_default();
        let title = self.title.clone().unwrap_or_else(|| {
            self.path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Unknown")
                .to_string()
        });
        let width = total.to_string().len();

        if album_artist.is_empty() {
            format!("{:0width$}. {}", index + 1, title)
        } else {
            format!("{:0width$}. {} - {}", index + 1, album_artist, title)
        }
    }

    pub fn format(&self, format_str: &str) -> String {
        let has_metadata = self.artist.as_ref().is_some_and(|a| !a.is_empty())
            || self.album.as_ref().is_some_and(|a| !a.is_empty());
        if !has_metadata {
            return self.title.clone().unwrap_or_else(|| {
                self.path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("Unknown")
                    .to_string()
            });
        }
        let artist = self.artist.clone().unwrap_or_default();
        let album = self.album.clone().unwrap_or_default();
        let title = self.title.clone().unwrap_or_else(|| {
            self.path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Unknown")
                .to_string()
        });
        format_str
            .replace("$ARTIST", &artist)
            .replace("$ALBUM", &album)
            .replace("$TRACK", &title)
    }
}

pub struct Queue {
    tracks: Vec<Track>,
    position: usize,
    shuffle: ShuffleMode,
    shuffled_indices: Vec<usize>,
    rng: StdRng,
}

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

impl Queue {
    pub fn new() -> Self {
        Queue {
            tracks: Vec::new(),
            position: 0,
            shuffle: ShuffleMode::None,
            shuffled_indices: Vec::new(),
            rng: rand::make_rng(),
        }
    }

    /// Construct a queue with a fixed RNG seed, making shuffle order fully
    /// reproducible. Used by tests and handy for debugging a specific order.
    #[allow(dead_code)] // used only by integration tests (bin crate does not link the lib)
    pub fn with_seed(seed: u64) -> Self {
        Queue {
            tracks: Vec::new(),
            position: 0,
            shuffle: ShuffleMode::None,
            shuffled_indices: Vec::new(),
            rng: StdRng::seed_from_u64(seed),
        }
    }

    pub fn add_track(&mut self, path: PathBuf) {
        self.tracks.push(Track::from_path(path));
        self.update_shuffle_indices();
    }

    pub fn push_track(&mut self, track: Track) {
        self.tracks.push(track);
        self.update_shuffle_indices();
    }

    pub fn insert_after_current(&mut self, path: PathBuf) {
        if self.tracks.is_empty() {
            self.tracks.push(Track::from_path(path));
            self.update_shuffle_indices();
            return;
        }
        let insert_idx = self.position + 1;
        self.tracks.insert(insert_idx, Track::from_path(path));
        if self.shuffle == ShuffleMode::None {
            self.update_shuffle_indices();
            return;
        }
        // Under shuffle, splice the new entry into the play order right after
        // the current slot instead of re-shuffling the tail: the inserted
        // track deterministically occupies slot `position + 1`, so "play
        // now/next" is meaningful and `current()` agrees with what the daemon
        // starts playing. The remaining play order is preserved (indices that
        // shifted right in `tracks` are bumped), not re-randomized.
        for v in self.shuffled_indices.iter_mut() {
            if *v >= insert_idx {
                *v += 1;
            }
        }
        self.shuffled_indices.insert(self.position + 1, insert_idx);
    }

    pub fn track_at(&self, idx: usize) -> Option<&Track> {
        self.tracks.get(idx)
    }

    pub fn set_shuffle(&mut self, mode: ShuffleMode) {
        self.shuffle = mode;
        match self.shuffle {
            ShuffleMode::None => {
                self.restore_from_original();
            }
            ShuffleMode::All => {
                self.update_shuffle_indices();
            }
            ShuffleMode::Album => {
                self.update_shuffle_indices_album();
            }
            ShuffleMode::Albums => {
                self.update_shuffle_indices_albums();
            }
        }
    }

    fn restore_from_original(&mut self) {
        // Restore linear (unshuffled) order. `tracks` is never reordered by
        // shuffle — only `shuffled_indices` is a permutation — so the live
        // list already carries the original insertion order. Keep the played
        // segment (positions 0..=current in shuffled order) in the order it
        // was played, then append the unplayed entries in original order.
        // Entries are tracked by identity, so duplicate paths are preserved
        // and entries added during shuffle survive.
        if self.tracks.is_empty() {
            self.position = 0;
            self.shuffled_indices.clear();
            return;
        }

        let current_pos = self.position.min(self.tracks.len().saturating_sub(1));

        // Played entries, in played order (positions 0..=current_pos in shuffled order).
        let mut played: Vec<Track> = Vec::new();
        let mut played_idx: Vec<usize> = Vec::new();
        for i in 0..=current_pos {
            if let Some(&idx) = self.shuffled_indices.get(i)
                && let Some(track) = self.tracks.get(idx)
            {
                played.push(track.clone());
                played_idx.push(idx);
            }
        }

        // Unplayed entries keep their original (insertion) order.
        let mut new_tracks = played;
        for (idx, track) in self.tracks.iter().enumerate() {
            if !played_idx.contains(&idx) {
                new_tracks.push(track.clone());
            }
        }

        self.tracks = new_tracks;
        self.position = current_pos;
        self.shuffled_indices.clear();
    }

    fn update_shuffle_indices(&mut self) {
        let len = self.tracks.len();
        self.shuffled_indices = (0..len).collect();
        match self.shuffle {
            ShuffleMode::All => {
                let pos = self.position.min(len.saturating_sub(1));
                if pos + 1 < len {
                    self.shuffled_indices[pos + 1..].shuffle(&mut self.rng);
                }
            }
            ShuffleMode::Album => {
                self.update_shuffle_indices_album();
            }
            ShuffleMode::Albums => {
                self.update_shuffle_indices_albums();
            }
            ShuffleMode::None => {}
        }
    }

    fn update_shuffle_indices_album(&mut self) {
        let len = self.tracks.len();
        self.shuffled_indices = (0..len).collect();

        if len > 1 {
            let pos = self.position.min(len.saturating_sub(1));
            if pos + 1 < len {
                Self::shuffle_album_range(
                    &self.tracks,
                    &mut self.shuffled_indices,
                    pos + 1..len,
                    &mut self.rng,
                );
            }
        }
    }

    fn update_shuffle_indices_albums(&mut self) {
        let len = self.tracks.len();
        self.shuffled_indices = (0..len).collect();

        if len <= 1 {
            return;
        }

        let pos = self.position.min(len.saturating_sub(1));
        if pos + 1 >= len {
            return;
        }

        let range_start = pos + 1;

        // Build album groups within the range, shuffling tracks within each group
        let mut groups: Vec<Vec<usize>> = Vec::new();
        let mut current_group: Vec<usize> = Vec::new();
        let mut current_album: Option<&str> = None;

        for i in range_start..len {
            let album = self.tracks.get(i).and_then(|t| t.album.as_deref());

            if current_group.is_empty() {
                current_group.push(i);
                current_album = album;
            } else if album != current_album {
                // Shuffle tracks within this album group before adding it
                if current_group.len() > 1 {
                    current_group.shuffle(&mut self.rng);
                }
                groups.push(std::mem::take(&mut current_group));
                current_group.push(i);
                current_album = album;
            } else {
                current_group.push(i);
            }
        }
        if !current_group.is_empty() {
            if current_group.len() > 1 {
                current_group.shuffle(&mut self.rng);
            }
            groups.push(current_group);
        }

        // Shuffle the album group order
        groups.shuffle(&mut self.rng);

        let mut new_indices: Vec<usize> = self.shuffled_indices[..=pos].to_vec();
        for group in &groups {
            new_indices.extend(group);
        }
        self.shuffled_indices = new_indices;
    }

    fn shuffle_album_range(
        tracks: &[Track],
        indices: &mut [usize],
        range: std::ops::Range<usize>,
        rng: &mut impl rand::Rng,
    ) {
        if range.start >= range.end {
            return;
        }

        let mut album_ranges: Vec<(usize, usize)> = Vec::new();
        let mut current_album: Option<&str> = None;
        let mut range_start: Option<usize> = None;

        for i in range.clone() {
            let album = tracks.get(i).and_then(|t| t.album.as_deref());
            match (current_album, range_start) {
                (None, None) => {
                    current_album = album;
                    range_start = Some(i);
                }
                (Some(_), Some(start)) if album != current_album => {
                    album_ranges.push((start, i));
                    current_album = album;
                    range_start = Some(i);
                }
                _ => {}
            }
        }
        if let Some(start) = range_start {
            album_ranges.push((start, range.end));
        }

        for (start, end) in album_ranges {
            if start + 1 < end {
                indices[start..end].shuffle(rng);
            }
        }
    }

    pub fn current(&self) -> Option<&Track> {
        if self.tracks.is_empty() {
            None
        } else if self.shuffle == ShuffleMode::All {
            self.shuffled_indices
                .get(self.position)
                .and_then(|&idx| self.tracks.get(idx))
        } else if self.shuffle == ShuffleMode::Album || self.shuffle == ShuffleMode::Albums {
            self.shuffled_indices
                .get(self.position)
                .and_then(|&idx| self.tracks.get(idx))
        } else {
            self.tracks.get(self.position)
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Option<PathBuf> {
        let max_pos = self.tracks.len().saturating_sub(1);
        if self.position < max_pos {
            self.position += 1;
            self.current().map(|t| t.path.clone())
        } else {
            None
        }
    }

    pub fn previous(&mut self) -> Option<PathBuf> {
        if self.position > 0 {
            self.position -= 1;
            self.current().map(|t| t.path.clone())
        } else {
            None
        }
    }

    pub fn is_empty(&self) -> bool {
        self.tracks.is_empty()
    }

    pub fn len(&self) -> usize {
        self.tracks.len()
    }

    pub fn position(&self) -> usize {
        self.position
    }

    pub fn set_position(&mut self, pos: usize) {
        self.position = pos;
    }

    #[allow(dead_code)]
    pub fn tracks(&self) -> &[Track] {
        &self.tracks
    }

    pub fn shuffle_mode(&self) -> &ShuffleMode {
        &self.shuffle
    }

    pub fn shuffled_indices(&self) -> &[usize] {
        &self.shuffled_indices
    }

    pub fn shuffle_initial(&mut self) {
        if self.position != 0 || self.tracks.len() <= 1 {
            return;
        }
        match self.shuffle {
            ShuffleMode::All => {
                self.shuffled_indices.shuffle(&mut self.rng);
            }
            ShuffleMode::Album => {
                Self::shuffle_album_range(
                    &self.tracks,
                    &mut self.shuffled_indices,
                    0..self.tracks.len(),
                    &mut self.rng,
                );
            }
            ShuffleMode::Albums => {
                let mut groups: Vec<Vec<usize>> = Vec::new();
                let mut current_group: Vec<usize> = Vec::new();
                let mut current_album: Option<&str> = None;

                for i in 0..self.tracks.len() {
                    let album = self.tracks.get(i).and_then(|t| t.album.as_deref());

                    if current_group.is_empty() {
                        current_group.push(i);
                        current_album = album;
                    } else if album != current_album {
                        if current_group.len() > 1 {
                            current_group.shuffle(&mut self.rng);
                        }
                        groups.push(std::mem::take(&mut current_group));
                        current_group.push(i);
                        current_album = album;
                    } else {
                        current_group.push(i);
                    }
                }
                if !current_group.is_empty() {
                    if current_group.len() > 1 {
                        current_group.shuffle(&mut self.rng);
                    }
                    groups.push(current_group);
                }

                groups.shuffle(&mut self.rng);

                self.shuffled_indices = groups.concat();
            }
            ShuffleMode::None => {}
        }
    }

    pub fn clear(&mut self) {
        self.tracks.clear();
        self.position = 0;
        self.shuffled_indices.clear();
    }
}