Skip to main content

djs_voice/
queue.rs

1//! A call's queue of tracks (D-352, C-126): the current track and the waiting ones, with
2//! their inputs, shared by the call's handles and its task under one lock (never held across
3//! an `await`). The handles change it at once; the task starts whatever is current, and
4//! moves on when a track ends.
5
6use core::fmt;
7use std::{
8    collections::VecDeque,
9    sync::{Arc, Mutex},
10};
11
12use tokio::sync::mpsc;
13
14use crate::{
15    Input, TrackHandle,
16    call::{CallCommand, lock},
17    track::{Track, TrackEnd},
18};
19
20/// What a call's handles share with its task.
21pub(crate) struct Shared {
22    pub(crate) commands: mpsc::UnboundedSender<CallCommand>,
23    pub(crate) queue: Mutex<Queue>,
24}
25
26impl Shared {
27    /// Tells the task the queue or a track changed.
28    pub(crate) fn wake(&self) {
29        // The task may be gone: the call ended, and its tracks with it.
30        let _ = self.commands.send(CallCommand::Wake);
31    }
32}
33
34/// A track in the queue, and its input until the call's task starts it.
35pub(crate) struct Slot {
36    pub(crate) track: Arc<Track>,
37    pub(crate) input: Option<Input>,
38}
39
40/// The tracks of a call.
41#[derive(Default)]
42pub(crate) struct Queue {
43    /// The track playing (or paused), or about to be started by the task.
44    pub(crate) current: Option<Slot>,
45    pub(crate) waiting: VecDeque<Slot>,
46    /// The call ended: tracks given to it end at once.
47    pub(crate) closed: bool,
48}
49
50impl Queue {
51    /// The next waiting track becomes the current one.
52    pub(crate) fn advance(&mut self) {
53        self.current = self.waiting.pop_front();
54    }
55
56    /// Ends the track `id` for `reason` and takes it out of the queue: the next one plays if
57    /// it was the current one. Whether it was in the queue.
58    pub(crate) fn remove(&mut self, id: u64, reason: TrackEnd) -> bool {
59        if self
60            .current
61            .as_ref()
62            .is_some_and(|slot| slot.track.id == id)
63        {
64            if let Some(slot) = self.current.take() {
65                slot.track.end(reason);
66            }
67            self.advance();
68            return true;
69        }
70        if let Some(index) = self.waiting.iter().position(|slot| slot.track.id == id) {
71            if let Some(slot) = self.waiting.remove(index) {
72                slot.track.end(reason);
73            }
74            return true;
75        }
76        false
77    }
78
79    /// The call ended: so do its tracks.
80    pub(crate) fn close(&mut self) {
81        self.closed = true;
82        for slot in self
83            .current
84            .take()
85            .into_iter()
86            .chain(self.waiting.drain(..))
87        {
88            slot.track.end(TrackEnd::CallEnded);
89        }
90    }
91}
92
93/// The queue of a [`Call`](crate::Call), from [`Call::queue`](crate::Call::queue): skip the
94/// current track, clear the waiting ones, see what plays (D-352).
95///
96/// [`Call::enqueue`](crate::Call::enqueue) adds tracks to it; each plays when the one
97/// before it ends. [`Call::play`](crate::Call::play) replaces the current track, and the
98/// waiting ones play after it. A cheap-clone handle; its methods act at once.
99///
100/// discord.js counterpart: none (a bot keeps its own queue and plays the next resource on
101/// `AudioPlayerStatus.Idle`); songbird: `TrackQueue`.
102///
103/// # Examples
104///
105/// ```no_run
106/// # fn run(call: djs_voice::Call) {
107/// use djs_voice::Input;
108///
109/// call.enqueue(Input::ffmpeg("one.mp3"));
110/// call.enqueue(Input::ffmpeg("two.mp3"));
111/// let queue = call.queue();
112/// assert_eq!(queue.len(), 2);
113/// queue.skip(); // "two.mp3" plays.
114/// queue.clear(); // Nothing waits any more; "two.mp3" goes on.
115/// # }
116/// ```
117#[derive(Clone)]
118pub struct TrackQueue {
119    pub(crate) shared: Arc<Shared>,
120}
121
122impl fmt::Debug for TrackQueue {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("TrackQueue")
125            .field("len", &self.len())
126            .finish()
127    }
128}
129
130impl TrackQueue {
131    /// Ends the current track ([`TrackEnd::Skipped`]) and plays the next one; whether there
132    /// was a current track.
133    ///
134    /// songbird counterpart: `TrackQueue::skip`.
135    #[allow(
136        clippy::must_use_candidate,
137        reason = "skipping without looking at the result is fine"
138    )]
139    pub fn skip(&self) -> bool {
140        let mut queue = lock(&self.shared.queue);
141        let Some(id) = queue.current.as_ref().map(|slot| slot.track.id) else {
142            return false;
143        };
144        queue.remove(id, TrackEnd::Skipped);
145        drop(queue);
146        self.shared.wake();
147        true
148    }
149
150    /// Removes the waiting tracks ([`TrackEnd::Stopped`]); the current one goes on.
151    ///
152    /// songbird counterpart: `TrackQueue::stop` (which stops the current one too).
153    ///
154    /// discord.js counterpart: none (`@discordjs/voice` has no queue).
155    pub fn clear(&self) {
156        let waiting: Vec<Slot> = lock(&self.shared.queue).waiting.drain(..).collect();
157        for slot in waiting {
158            slot.track.end(TrackEnd::Stopped);
159        }
160    }
161
162    /// The tracks in the queue: the current one and the waiting ones.
163    ///
164    /// songbird counterpart: `TrackQueue::len`.
165    ///
166    /// discord.js counterpart: none (`@discordjs/voice` has no queue).
167    #[must_use]
168    pub fn len(&self) -> usize {
169        let queue = lock(&self.shared.queue);
170        usize::from(queue.current.is_some()) + queue.waiting.len()
171    }
172
173    /// Whether nothing plays and nothing waits.
174    ///
175    /// discord.js counterpart: none (`@discordjs/voice` has no queue).
176    #[must_use]
177    pub fn is_empty(&self) -> bool {
178        self.len() == 0
179    }
180
181    /// The track playing (or paused), if any.
182    ///
183    /// songbird counterpart: `TrackQueue::current`.
184    ///
185    /// discord.js counterpart: the resource of `AudioPlayer#state` (`@discordjs/voice`).
186    #[must_use]
187    pub fn current(&self) -> Option<TrackHandle> {
188        lock(&self.shared.queue)
189            .current
190            .as_ref()
191            .map(|slot| TrackHandle::new(Arc::clone(&slot.track)))
192    }
193}