rich_sdl2_rust/audio/
queue.rs

1//! Structures to use an audio device by pushing methods.
2
3use std::io;
4
5use super::{MicrophoneDevice, SpeakerDevice};
6use crate::{bind, Result, Sdl, SdlError};
7
8/// A queue to push data to play the sound with [`SpeakerDevice`].
9#[derive(Debug)]
10pub struct QueuedAudio<'device> {
11    device: &'device mut SpeakerDevice,
12}
13
14impl<'device> QueuedAudio<'device> {
15    /// Constructs a queue from a [`SpeakerDevice`].
16    pub fn new(device: &'device mut SpeakerDevice) -> Self {
17        Self { device }
18    }
19
20    /// Queues the `data` to play.
21    ///
22    /// # Errors
23    ///
24    /// Returns `Err` if failed to queue `data`.
25    pub fn queue<T>(&self, data: &[T]) -> Result<()> {
26        let size = std::mem::size_of_val(data);
27        let ret =
28            unsafe { bind::SDL_QueueAudio(self.device.id, data.as_ptr().cast(), size as u32) };
29        if ret < 0 {
30            Err(SdlError::Others { msg: Sdl::error() })
31        } else {
32            Ok(())
33        }
34    }
35
36    /// Clears all audio data in the queue to stop to play, but it does not stop immediately because of drivers' implementation.
37    pub fn clear(&self) {
38        unsafe { bind::SDL_ClearQueuedAudio(self.device.id) }
39    }
40
41    /// Returns the size of the queue in bytes.
42    #[must_use]
43    pub fn queue_bytes_size(&self) -> usize {
44        unsafe { bind::SDL_GetQueuedAudioSize(self.device.id) as usize }
45    }
46}
47
48impl Drop for QueuedAudio<'_> {
49    fn drop(&mut self) {
50        unsafe { bind::SDL_ClearQueuedAudio(self.device.id) }
51    }
52}
53
54/// A queue to read data to record the sound with [`MicrophoneDevice`]. To dequeue from this, `use` the implementation of [`std::io::Read`] for this.
55#[derive(Debug)]
56pub struct DequeueAudio<'device> {
57    device: &'device mut MicrophoneDevice,
58}
59
60impl<'device> DequeueAudio<'device> {
61    /// Constructs a queue from [`MicrophoneDevice`].
62    pub fn new(device: &'device mut MicrophoneDevice) -> Self {
63        Self { device }
64    }
65
66    /// Clears all audio data in the queue to prevent queue from unnecessary data.
67    pub fn clear(&self) {
68        unsafe { bind::SDL_ClearQueuedAudio(self.device.id) }
69    }
70}
71
72impl Drop for DequeueAudio<'_> {
73    fn drop(&mut self) {
74        unsafe { bind::SDL_ClearQueuedAudio(self.device.id) }
75    }
76}
77
78impl io::Read for DequeueAudio<'_> {
79    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
80        let bytes = unsafe {
81            bind::SDL_DequeueAudio(self.device.id, buf.as_mut_ptr().cast(), buf.len() as u32)
82        };
83        Ok(bytes as usize)
84    }
85}