djs_voice/track.rs
1//! Tracks (D-323, D-339, D-352–D-361): what a call plays, their handles, state and events.
2//!
3//! A track's state is shared between its handles and its call's task (C-126): atomics for
4//! what [`TrackHandle::info`] reads, and its event streams. Whoever ends a track (a handle
5//! stopping, replacing or skipping it, or the task when it played to its end) sets the
6//! reason once, the first wins, and sends it to the streams.
7
8use core::{
9 fmt,
10 pin::Pin,
11 sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
12 task::{Context, Poll},
13 time::Duration,
14};
15use std::sync::{Arc, Mutex, Weak};
16
17use futures_util::Stream;
18use tokio::sync::{mpsc, oneshot};
19
20use crate::{
21 InputError, TrackError,
22 call::{CallCommand, lock},
23 queue::Shared,
24};
25
26/// `samples` per channel at 48 kHz as a duration: 62 500 / 3 ns each.
27pub(crate) fn duration(samples: u64) -> Duration {
28 Duration::from_nanos(samples.saturating_mul(62_500) / 3)
29}
30
31/// `duration` as samples per channel at 48 kHz.
32pub(crate) fn samples(duration: Duration) -> u64 {
33 u64::try_from(duration.as_nanos() * 3 / 62_500).unwrap_or(u64::MAX)
34}
35
36/// A track, shared by its handles, its call's queue and its task.
37pub(crate) struct Track {
38 pub(crate) id: u64,
39 /// Its input can be opened again: it loops and seeks (D-360).
40 seekable: bool,
41 /// The call's task took its input: it is playing or paused (or ended).
42 started: AtomicBool,
43 paused: AtomicBool,
44 ended: AtomicBool,
45 /// Samples per channel at 48 kHz played; for a waiting track, where it will start.
46 position: AtomicU64,
47 /// The volume's bits (an `f32`).
48 volume: AtomicU32,
49 looping: Mutex<Loop>,
50 subscribers: Mutex<Subscribers>,
51 call: Weak<Shared>,
52}
53
54#[derive(Default)]
55struct Subscribers {
56 senders: Vec<mpsc::UnboundedSender<TrackEvent>>,
57 /// The track ended: new streams end at once.
58 closed: bool,
59}
60
61impl Track {
62 pub(crate) fn new(id: u64, seekable: bool, call: Weak<Shared>) -> Arc<Self> {
63 Arc::new(Self {
64 id,
65 seekable,
66 started: AtomicBool::new(false),
67 paused: AtomicBool::new(false),
68 ended: AtomicBool::new(false),
69 position: AtomicU64::new(0),
70 volume: AtomicU32::new(1.0_f32.to_bits()),
71 looping: Mutex::new(Loop::Off),
72 subscribers: Mutex::new(Subscribers::default()),
73 call,
74 })
75 }
76
77 /// Ends the track for `reason`, unless it already ended; whether it did now. The
78 /// streams get [`TrackEvent::Ended`] and end.
79 pub(crate) fn end(&self, reason: TrackEnd) -> bool {
80 let mut subscribers = lock(&self.subscribers);
81 if subscribers.closed {
82 return false;
83 }
84 self.ended.store(true, Ordering::Release);
85 let event = TrackEvent::Ended(reason);
86 for subscriber in &subscribers.senders {
87 let _ = subscriber.send(event.clone());
88 }
89 subscribers.senders.clear();
90 subscribers.closed = true;
91 true
92 }
93
94 /// Sends `event` to the track's streams.
95 pub(crate) fn emit(&self, event: &TrackEvent) {
96 lock(&self.subscribers)
97 .senders
98 .retain(|subscriber| subscriber.send(event.clone()).is_ok());
99 }
100
101 pub(crate) fn ended(&self) -> bool {
102 self.ended.load(Ordering::Acquire)
103 }
104
105 pub(crate) fn started(&self) -> bool {
106 self.started.load(Ordering::Acquire)
107 }
108
109 /// The call's task took the input (under the queue's lock).
110 pub(crate) fn start(&self) {
111 self.started.store(true, Ordering::Release);
112 }
113
114 pub(crate) fn paused(&self) -> bool {
115 self.paused.load(Ordering::Acquire)
116 }
117
118 pub(crate) fn position(&self) -> u64 {
119 self.position.load(Ordering::Acquire)
120 }
121
122 pub(crate) fn set_position(&self, samples: u64) {
123 self.position.store(samples, Ordering::Release);
124 }
125
126 pub(crate) fn advance(&self, samples: u32) {
127 self.position
128 .fetch_add(u64::from(samples), Ordering::AcqRel);
129 }
130
131 pub(crate) fn volume(&self) -> f32 {
132 f32::from_bits(self.volume.load(Ordering::Acquire))
133 }
134
135 /// At the end of the input: whether the track plays again, counting a repeat down.
136 pub(crate) fn repeat(&self) -> bool {
137 let mut looping = lock(&self.looping);
138 match *looping {
139 Loop::Forever => true,
140 Loop::Times(left @ 1..) => {
141 *looping = Loop::Times(left - 1);
142 true
143 }
144 Loop::Times(0) | Loop::Off => false,
145 }
146 }
147
148 fn info(&self) -> TrackInfo {
149 let state = if self.ended() {
150 PlayState::Ended
151 } else if !self.started() {
152 PlayState::Queued
153 } else if self.paused() {
154 PlayState::Paused
155 } else {
156 PlayState::Playing
157 };
158 TrackInfo {
159 state,
160 position: duration(self.position()),
161 volume: self.volume(),
162 looping: *lock(&self.looping),
163 }
164 }
165}
166
167/// Controls a track that [`Call::play`](crate::Call::play) or
168/// [`Call::enqueue`](crate::Call::enqueue) gave the call: pause it, play it again, stop it,
169/// change its volume, loop it, seek in it, read its state, follow its events.
170///
171/// A cheap-clone handle: clones control the same track. The controls only ask the call to
172/// act, so they return at once ([`seek`](Self::seek) waits for it); they fail with
173/// [`TrackError::Ended`] once the track has ended (played to its end, stopped, replaced,
174/// skipped, its input failed, or its call ended). Dropping every handle does not stop the
175/// track.
176///
177/// discord.js counterpart: `AudioPlayer#pause`, `unpause` and `stop`, and
178/// `AudioResource#volume` of `@discordjs/voice` (a player plays one resource); songbird:
179/// `TrackHandle`.
180///
181/// # Examples
182///
183/// ```no_run
184/// # async fn run(call: djs_voice::Call) -> Result<(), Box<dyn std::error::Error>> {
185/// use std::time::Duration;
186///
187/// use djs_voice::{Input, Loop};
188///
189/// let track = call.play(Input::ffmpeg("song.mp3"));
190/// track.set_volume(0.5)?;
191/// track.set_loop(Loop::Times(2))?;
192/// track.seek(Duration::from_secs(30)).await?;
193/// track.pause()?;
194/// track.play()?;
195/// println!("at {:?}", track.info().position);
196/// track.stop()?;
197/// assert!(track.play().is_err(), "a stopped track has ended");
198/// # Ok(()) }
199/// ```
200#[derive(Clone)]
201pub struct TrackHandle {
202 track: Arc<Track>,
203}
204
205impl fmt::Debug for TrackHandle {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207 f.debug_struct("TrackHandle")
208 .field("id", &self.track.id)
209 .field("info", &self.track.info())
210 .finish()
211 }
212}
213
214impl PartialEq for TrackHandle {
215 /// Whether both handles control the same track.
216 fn eq(&self, other: &Self) -> bool {
217 Arc::ptr_eq(&self.track, &other.track)
218 }
219}
220
221impl Eq for TrackHandle {}
222
223impl TrackHandle {
224 pub(crate) fn new(track: Arc<Track>) -> Self {
225 Self { track }
226 }
227
228 /// Plays the track again after [`pause`](Self::pause), from where it paused; does
229 /// nothing to a track that is playing. A waiting track that was paused starts playing
230 /// when its turn comes.
231 ///
232 /// discord.js counterpart: `AudioPlayer#unpause`.
233 ///
234 /// # Errors
235 ///
236 /// [`TrackError::Ended`] when the track has ended.
237 pub fn play(&self) -> Result<(), TrackError> {
238 self.set_paused(false)
239 }
240
241 /// Pauses the track: it stops sending audio (after a few frames of silence, as Discord
242 /// asks) and keeps its place; [`play`](Self::play) goes on from there. A waiting track
243 /// starts paused when its turn comes (D-361).
244 ///
245 /// discord.js counterpart: `AudioPlayer#pause`.
246 ///
247 /// # Errors
248 ///
249 /// [`TrackError::Ended`] when the track has ended.
250 pub fn pause(&self) -> Result<(), TrackError> {
251 self.set_paused(true)
252 }
253
254 fn set_paused(&self, paused: bool) -> Result<(), TrackError> {
255 self.alive()?;
256 self.track.paused.store(paused, Ordering::Release);
257 self.wake();
258 Ok(())
259 }
260
261 /// Stops the track for good ([`TrackEnd::Stopped`]): its input is no longer read. The
262 /// call's queue goes on with the next track; a waiting track is removed from the queue.
263 ///
264 /// discord.js counterpart: `AudioPlayer#stop`.
265 ///
266 /// # Errors
267 ///
268 /// [`TrackError::Ended`] when the track has already ended.
269 pub fn stop(&self) -> Result<(), TrackError> {
270 self.alive()?;
271 if let Some(call) = self.track.call.upgrade() {
272 lock(&call.queue).remove(self.track.id, TrackEnd::Stopped);
273 call.wake();
274 }
275 // Not in the queue: the call ended, or it is ending the track now.
276 self.track.end(TrackEnd::Stopped);
277 Ok(())
278 }
279
280 /// Sets the track's volume (D-353): linear, 1.0 the original, 0.5 half as loud, 0.0
281 /// silent, up to 2.0 (louder, with a soft clip against distortion); values outside
282 /// `0.0..=2.0` are clamped, NaN counts as 0.0. Heard from the next frame.
283 ///
284 /// At 1.0 an Ogg/Opus track is sent as it is; at any other volume it is decoded and
285 /// encoded again, which costs some CPU.
286 ///
287 /// discord.js counterpart: `AudioResource#volume.setVolume` (with `inlineVolume`);
288 /// songbird: `TrackHandle::set_volume`.
289 ///
290 /// # Errors
291 ///
292 /// [`TrackError::Ended`] when the track has ended.
293 pub fn set_volume(&self, volume: f32) -> Result<(), TrackError> {
294 self.alive()?;
295 let volume = if volume.is_nan() {
296 0.0
297 } else {
298 volume.clamp(0.0, 2.0)
299 };
300 self.track.volume.store(volume.to_bits(), Ordering::Release);
301 Ok(())
302 }
303
304 /// Sets whether the track plays again when it reaches its end (D-358): never, forever,
305 /// or a number of times more. Each repeat sends [`TrackEvent::Looped`];
306 /// [`TrackInfo::looping`] shows the repeats left.
307 ///
308 /// discord.js counterpart: none (a bot plays the resource again); songbird:
309 /// `TrackHandle::enable_loop`, `disable_loop` and `loop_for`.
310 ///
311 /// # Errors
312 ///
313 /// [`TrackError::Ended`] when the track has ended, [`TrackError::Unsupported`] when its
314 /// input is a reader, which cannot be opened again (D-360).
315 pub fn set_loop(&self, looping: Loop) -> Result<(), TrackError> {
316 self.alive()?;
317 if !self.track.seekable {
318 return Err(TrackError::Unsupported);
319 }
320 *lock(&self.track.looping) = looping;
321 Ok(())
322 }
323
324 /// Plays the track from `position` (D-359); returns once it plays from there, with the
325 /// position it actually plays from: the start of the Opus packet holding `position` for
326 /// an Ogg/Opus file, `position` itself with FFmpeg. A waiting track will start there
327 /// (the result comes at once). Seeking past the end ends the track
328 /// ([`TrackEnd::Finished`]), unless it loops.
329 ///
330 /// The file is opened again (its packets skipped up to `position`, without decoding), or
331 /// FFmpeg run again with `-ss`.
332 ///
333 /// discord.js counterpart: none (a resource is played again with FFmpeg's `-ss`);
334 /// songbird: `TrackHandle::seek`.
335 ///
336 /// # Errors
337 ///
338 /// [`TrackError::Ended`] when the track has ended (or ends while seeking: past its end,
339 /// or its input failed), [`TrackError::Unsupported`] when its input is a reader, which
340 /// cannot be opened again (D-360).
341 pub async fn seek(&self, position: Duration) -> Result<Duration, TrackError> {
342 self.alive()?;
343 if !self.track.seekable {
344 return Err(TrackError::Unsupported);
345 }
346 let target = samples(position);
347 let call = self.track.call.upgrade().ok_or(TrackError::Ended)?;
348 let (done, result) = oneshot::channel();
349 {
350 // Under the lock the call's task starts tracks with.
351 let queue = lock(&call.queue);
352 if !self.track.started() {
353 self.track.set_position(target);
354 return Ok(duration(target));
355 }
356 drop(queue);
357 }
358 let command = CallCommand::Seek {
359 id: self.track.id,
360 samples: target,
361 done,
362 };
363 if call.commands.send(command).is_err() {
364 return Err(TrackError::Ended);
365 }
366 drop(call);
367 result.await.unwrap_or(Err(TrackError::Ended))
368 }
369
370 /// The track's state now: playing, paused, waiting or ended, where it is, its volume
371 /// and loop (D-356). Read at once, without asking the call.
372 ///
373 /// discord.js counterpart: `AudioPlayer#state` and `AudioResource#playbackDuration`;
374 /// songbird: `TrackHandle::get_info`.
375 #[must_use]
376 pub fn info(&self) -> TrackInfo {
377 self.track.info()
378 }
379
380 /// Returns a stream of the track's events (D-355): it plays, pauses, loops, and ends,
381 /// with why. Each stream gets every event from its creation on, and ends after
382 /// [`TrackEvent::Ended`]; a stream of a track that already ended ends at once.
383 ///
384 /// discord.js counterpart: `AudioPlayer#on('stateChange')`; songbird:
385 /// `TrackHandle::add_event`.
386 ///
387 /// # Examples
388 ///
389 /// ```no_run
390 /// # async fn run(call: djs_voice::Call) {
391 /// use djs_voice::{Input, TrackEnd, TrackEvent};
392 ///
393 /// let track = call.enqueue(Input::ffmpeg("song.mp3"));
394 /// let mut events = track.events();
395 /// while let Some(event) = events.next().await {
396 /// match event {
397 /// TrackEvent::Playing => println!("now playing"),
398 /// TrackEvent::Ended(TrackEnd::Failed(error)) => println!("failed: {error}"),
399 /// TrackEvent::Ended(reason) => println!("ended: {reason}"),
400 /// _ => {}
401 /// }
402 /// }
403 /// # }
404 /// ```
405 #[must_use]
406 pub fn events(&self) -> TrackEvents {
407 let (tx, rx) = mpsc::unbounded_channel();
408 let mut subscribers = lock(&self.track.subscribers);
409 if !subscribers.closed {
410 subscribers.senders.push(tx);
411 }
412 TrackEvents { rx }
413 }
414
415 fn alive(&self) -> Result<(), TrackError> {
416 if self.track.ended() {
417 Err(TrackError::Ended)
418 } else {
419 Ok(())
420 }
421 }
422
423 fn wake(&self) {
424 if let Some(call) = self.track.call.upgrade() {
425 call.wake();
426 }
427 }
428}
429
430/// Whether a track plays again at its end (D-358), for [`TrackHandle::set_loop`].
431///
432/// songbird counterpart: `LoopState`.
433///
434/// discord.js counterpart: none (`@discordjs/voice` has no looping).
435#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
436#[non_exhaustive]
437pub enum Loop {
438 /// It ends at its end.
439 #[default]
440 Off,
441 /// It plays again, every time.
442 Forever,
443 /// It plays again this many more times; [`TrackInfo::looping`] counts down.
444 Times(u32),
445}
446
447/// Where a track is (D-361), in [`TrackInfo::state`].
448///
449/// discord.js counterpart: `AudioPlayerStatus`.
450#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
451#[non_exhaustive]
452pub enum PlayState {
453 /// Waiting in the call's queue.
454 Queued,
455 /// Playing (or about to: its input is being read).
456 Playing,
457 /// Paused with [`TrackHandle::pause`].
458 Paused,
459 /// Ended; [`TrackEvent::Ended`] said why.
460 Ended,
461}
462
463/// A track's state, from [`TrackHandle::info`] (D-356).
464///
465/// songbird counterpart: `TrackState`.
466///
467/// discord.js counterpart: `AudioPlayer#state` (`@discordjs/voice`).
468#[derive(Clone, Copy, Debug, PartialEq)]
469#[non_exhaustive]
470pub struct TrackInfo {
471 /// Playing, paused, waiting or ended.
472 pub state: PlayState,
473 /// How much of it has played (from where a seek put it, rewound by a loop); for a
474 /// waiting track, where it will start.
475 pub position: Duration,
476 /// Its volume, 1.0 the original ([`TrackHandle::set_volume`]).
477 pub volume: f32,
478 /// Whether it plays again at its end, and how many more times
479 /// ([`TrackHandle::set_loop`]).
480 pub looping: Loop,
481}
482
483/// An event of a track, from [`TrackHandle::events`] (D-355).
484///
485/// discord.js counterpart: the state changes of `AudioPlayer`; songbird: `TrackEvent`.
486#[derive(Clone, Debug)]
487#[non_exhaustive]
488pub enum TrackEvent {
489 /// Its audio goes out: it started, or plays again after a pause.
490 Playing,
491 /// It was paused ([`TrackHandle::pause`]) while it played.
492 Paused,
493 /// It reached its end and plays again ([`TrackHandle::set_loop`]).
494 Looped,
495 /// It ended, for this reason; the stream ends after it.
496 Ended(TrackEnd),
497}
498
499/// Why a track ended (D-355), in [`TrackEvent::Ended`].
500///
501/// songbird counterpart: `PlayMode::End`, `Stop` and `Errored`.
502///
503/// discord.js counterpart: none (`@discordjs/voice` reports only the player's state changes).
504#[derive(Clone, Debug)]
505#[non_exhaustive]
506pub enum TrackEnd {
507 /// It played to its end (or was sought past it).
508 Finished,
509 /// [`TrackHandle::stop`], or [`TrackQueue::clear`](crate::TrackQueue::clear) while it
510 /// waited.
511 Stopped,
512 /// [`Call::play`](crate::Call::play) played another track instead.
513 Replaced,
514 /// [`TrackQueue::skip`](crate::TrackQueue::skip).
515 Skipped,
516 /// Its input failed: it could not be read or decoded, or FFmpeg failed.
517 Failed(Arc<InputError>),
518 /// Its call ended.
519 CallEnded,
520}
521
522impl fmt::Display for TrackEnd {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 match self {
525 Self::Finished => f.write_str("the track played to its end"),
526 Self::Stopped => f.write_str("the track was stopped"),
527 Self::Replaced => f.write_str("another track replaced it"),
528 Self::Skipped => f.write_str("the track was skipped"),
529 Self::Failed(error) => write!(f, "the track's input failed: {error}"),
530 Self::CallEnded => f.write_str("its call ended"),
531 }
532 }
533}
534
535/// The stream of a track's events. Created by [`TrackHandle::events`].
536///
537/// Implements [`Stream`]; [`next`](Self::next) is provided so no extension trait is needed.
538///
539/// discord.js counterpart: `AudioPlayer#on` (`@discordjs/voice`).
540#[derive(Debug)]
541pub struct TrackEvents {
542 rx: mpsc::UnboundedReceiver<TrackEvent>,
543}
544
545impl TrackEvents {
546 /// Waits for the next event. Returns `None` once the track has ended (after
547 /// [`TrackEvent::Ended`]).
548 ///
549 /// discord.js counterpart: `AudioPlayer#on` (`@discordjs/voice`).
550 pub async fn next(&mut self) -> Option<TrackEvent> {
551 self.rx.recv().await
552 }
553}
554
555impl Stream for TrackEvents {
556 type Item = TrackEvent;
557
558 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<TrackEvent>> {
559 self.rx.poll_recv(cx)
560 }
561}
562
563#[cfg(test)]
564mod tests {
565 use core::time::Duration;
566
567 use super::{duration, samples};
568
569 #[test]
570 fn samples_and_durations_convert() {
571 assert_eq!(duration(48_000), Duration::from_secs(1));
572 assert_eq!(duration(960), Duration::from_millis(20));
573 assert_eq!(samples(Duration::from_millis(500)), 24_000);
574 assert_eq!(samples(Duration::from_secs(90)), 4_320_000);
575 assert_eq!(samples(duration(123_456)), 123_456);
576 assert_eq!(samples(Duration::MAX), u64::MAX);
577 }
578}