RFC: Rework the API [WIP] (#165)
* Rework the API to not use futures anymore * Add some comments * Update the MacOS backend * Restore the null implementation * Add an emscripten backend * Remove erroneously added feature * Fix to_f32 formula * [WIP] Alsa backend * Alsa backend compiling * Working ALSA backend * Fix tests * Move WASAPI endpoint to endpoint module * Fix WASAPI warnings * Rework the WASAPI backend * Check overflows for voice ID * Add comments and minor fixes to WASAPI backend * Add a changelog
This commit is contained in:
parent
4b019243c2
commit
6ae01f437c
13 changed files with 1472 additions and 1447 deletions
269
src/lib.rs
269
src/lib.rs
|
|
@ -1,65 +1,33 @@
|
|||
/*!
|
||||
# How to use cpal
|
||||
|
||||
In order to play a sound, first you need to create an `EventLoop` and a `Voice`.
|
||||
In order to play a sound, first you need to create an `EventLoop` and a voice.
|
||||
|
||||
```no_run
|
||||
// getting the default sound output of the system (can return `None` if nothing is supported)
|
||||
let endpoint = cpal::get_default_endpoint().unwrap();
|
||||
let endpoint = cpal::default_endpoint().unwrap();
|
||||
|
||||
// note that the user can at any moment disconnect the device, therefore all operations return
|
||||
// a `Result` to handle this situation
|
||||
|
||||
// getting a format for the PCM
|
||||
let format = endpoint.get_supported_formats_list().unwrap().next().unwrap();
|
||||
let format = endpoint.supported_formats().unwrap().next().unwrap();
|
||||
|
||||
let event_loop = cpal::EventLoop::new();
|
||||
|
||||
let (voice, mut samples_stream) = cpal::Voice::new(&endpoint, &format, &event_loop).unwrap();
|
||||
let voice_id = event_loop.build_voice(&endpoint, &format).unwrap();
|
||||
event_loop.play(voice_id);
|
||||
```
|
||||
|
||||
The `voice` can be used to control the play/pause of the output, while the `samples_stream` can
|
||||
be used to register a callback that will be called whenever the backend is ready to get data.
|
||||
See the documentation of `futures-rs` for more info about how to use streams.
|
||||
`voice_id` is an identifier for the voice can be used to control the play/pause of the output.
|
||||
|
||||
Once that's done, you can call `run()` on the `event_loop`.
|
||||
|
||||
```no_run
|
||||
# extern crate futures;
|
||||
# extern crate cpal;
|
||||
# use std::sync::Arc;
|
||||
use futures::stream::Stream;
|
||||
use futures::task;
|
||||
# struct MyExecutor;
|
||||
# impl task::Executor for MyExecutor {
|
||||
# fn execute(&self, r: task::Run) {
|
||||
# r.run();
|
||||
# }
|
||||
# }
|
||||
# fn main() {
|
||||
# let mut samples_stream: cpal::SamplesStream = unsafe { std::mem::uninitialized() };
|
||||
# let my_executor = Arc::new(MyExecutor);
|
||||
|
||||
task::spawn(samples_stream.for_each(move |buffer| -> Result<_, ()> {
|
||||
# let event_loop = cpal::EventLoop::new();
|
||||
event_loop.run(move |_voice_id, _buffer| {
|
||||
// write data to `buffer` here
|
||||
|
||||
Ok(())
|
||||
})).execute(my_executor);
|
||||
# }
|
||||
```
|
||||
|
||||
TODO: add example
|
||||
|
||||
After you have registered a callback, call `play`:
|
||||
|
||||
```no_run
|
||||
# let mut voice: cpal::Voice = unsafe { std::mem::uninitialized() };
|
||||
voice.play();
|
||||
```
|
||||
|
||||
And finally, run the event loop:
|
||||
|
||||
```no_run
|
||||
# let mut event_loop: cpal::EventLoop = unsafe { std::mem::uninitialized() };
|
||||
event_loop.run();
|
||||
});
|
||||
```
|
||||
|
||||
Calling `run()` will block the thread forever, so it's usually best done in a separate thread.
|
||||
|
|
@ -69,7 +37,6 @@ from time to time.
|
|||
|
||||
*/
|
||||
|
||||
extern crate futures;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
extern crate libc;
|
||||
|
|
@ -77,16 +44,13 @@ extern crate libc;
|
|||
pub use samples_formats::{Sample, SampleFormat};
|
||||
|
||||
#[cfg(all(not(windows), not(target_os = "linux"), not(target_os = "freebsd"),
|
||||
not(target_os = "macos"), not(target_os = "ios")))]
|
||||
not(target_os = "macos"), not(target_os = "ios"), not(target_os = "emscripten")))]
|
||||
use null as cpal_impl;
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
use futures::Poll;
|
||||
use futures::stream::Stream;
|
||||
|
||||
mod null;
|
||||
mod samples_formats;
|
||||
|
||||
|
|
@ -102,6 +66,10 @@ mod cpal_impl;
|
|||
#[path = "coreaudio/mod.rs"]
|
||||
mod cpal_impl;
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
#[path = "emscripten/mod.rs"]
|
||||
mod cpal_impl;
|
||||
|
||||
/// An iterator for the list of formats that are supported by the backend.
|
||||
pub struct EndpointsIterator(cpal_impl::EndpointsIterator);
|
||||
|
||||
|
|
@ -237,42 +205,94 @@ impl Iterator for SupportedFormatsIterator {
|
|||
pub struct EventLoop(cpal_impl::EventLoop);
|
||||
|
||||
impl EventLoop {
|
||||
/// Initializes a new events loop.
|
||||
#[inline]
|
||||
pub fn new() -> EventLoop {
|
||||
EventLoop(cpal_impl::EventLoop::new())
|
||||
}
|
||||
|
||||
/// Creates a new voice that will play on the given endpoint and with the given format.
|
||||
///
|
||||
/// On success, returns an identifier for the voice.
|
||||
#[inline]
|
||||
pub fn run(&self) {
|
||||
self.0.run()
|
||||
pub fn build_voice(&self, endpoint: &Endpoint, format: &Format)
|
||||
-> Result<VoiceId, CreationError>
|
||||
{
|
||||
self.0.build_voice(&endpoint.0, format).map(VoiceId)
|
||||
}
|
||||
|
||||
/// Destroys an existing voice.
|
||||
///
|
||||
/// # Panic
|
||||
///
|
||||
/// If the voice doesn't exist, this function can either panic or be a no-op.
|
||||
///
|
||||
#[inline]
|
||||
pub fn destroy_voice(&self, voice_id: VoiceId) {
|
||||
self.0.destroy_voice(voice_id.0)
|
||||
}
|
||||
|
||||
/// Takes control of the current thread and processes the sounds.
|
||||
///
|
||||
/// Whenever a voice needs to be fed some data, the closure passed as parameter is called.
|
||||
/// **Note**: Calling other methods of the events loop from the callback will most likely
|
||||
/// deadlock. Don't do that. Maybe this will change in the future.
|
||||
#[inline]
|
||||
pub fn run<F>(&self, mut callback: F) -> !
|
||||
where F: FnMut(VoiceId, UnknownTypeBuffer)
|
||||
{
|
||||
self.0.run(move |id, buf| callback(VoiceId(id), buf))
|
||||
}
|
||||
|
||||
/// Sends a command to the audio device that it should start playing.
|
||||
///
|
||||
/// Has no effect is the voice was already playing.
|
||||
///
|
||||
/// Only call this after you have submitted some data, otherwise you may hear
|
||||
/// some glitches.
|
||||
///
|
||||
/// # Panic
|
||||
///
|
||||
/// If the voice doesn't exist, this function can either panic or be a no-op.
|
||||
///
|
||||
#[inline]
|
||||
pub fn play(&self, voice: VoiceId) {
|
||||
self.0.play(voice.0)
|
||||
}
|
||||
|
||||
/// Sends a command to the audio device that it should stop playing.
|
||||
///
|
||||
/// Has no effect is the voice was already paused.
|
||||
///
|
||||
/// If you call `play` afterwards, the playback will resume exactly where it was.
|
||||
///
|
||||
/// # Panic
|
||||
///
|
||||
/// If the voice doesn't exist, this function can either panic or be a no-op.
|
||||
///
|
||||
#[inline]
|
||||
pub fn pause(&self, voice: VoiceId) {
|
||||
self.0.pause(voice.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a buffer that must be filled with audio data.
|
||||
///
|
||||
/// You should destroy this object as soon as possible. Data is only committed when it
|
||||
/// is destroyed.
|
||||
#[must_use]
|
||||
pub struct Buffer<T>
|
||||
where T: Sample
|
||||
{
|
||||
// also contains something, taken by `Drop`
|
||||
target: Option<cpal_impl::Buffer<T>>,
|
||||
}
|
||||
/// Identifier of a voice in an events loop.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct VoiceId(cpal_impl::VoiceId);
|
||||
|
||||
/// This is the struct that is provided to you by cpal when you want to write samples to a buffer.
|
||||
///
|
||||
/// Since the type of data is only known at runtime, you have to fill the right buffer.
|
||||
pub enum UnknownTypeBuffer {
|
||||
pub enum UnknownTypeBuffer<'a> {
|
||||
/// Samples whose format is `u16`.
|
||||
U16(Buffer<u16>),
|
||||
U16(Buffer<'a, u16>),
|
||||
/// Samples whose format is `i16`.
|
||||
I16(Buffer<i16>),
|
||||
I16(Buffer<'a, i16>),
|
||||
/// Samples whose format is `f32`.
|
||||
F32(Buffer<f32>),
|
||||
F32(Buffer<'a, f32>),
|
||||
}
|
||||
|
||||
impl UnknownTypeBuffer {
|
||||
impl<'a> UnknownTypeBuffer<'a> {
|
||||
/// Returns the length of the buffer in number of samples.
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
|
|
@ -343,111 +363,20 @@ impl Error for CreationError {
|
|||
}
|
||||
}
|
||||
|
||||
/// Controls a sound output. A typical application has one `Voice` for each sound
|
||||
/// it wants to output.
|
||||
/// Represents a buffer that must be filled with audio data.
|
||||
///
|
||||
/// A voice must be periodically filled with new data by calling `append_data`, or the sound
|
||||
/// will stop playing.
|
||||
///
|
||||
/// Each `Voice` is bound to a specific number of channels, samples rate, and samples format,
|
||||
/// which can be retreived by calling `get_channels`, `get_samples_rate` and `get_samples_format`.
|
||||
/// If you call `append_data` with values different than these, then cpal will automatically
|
||||
/// perform a conversion on your data.
|
||||
///
|
||||
/// If you have the possibility, you should try to match the format of the voice.
|
||||
pub struct Voice {
|
||||
voice: cpal_impl::Voice,
|
||||
format: Format,
|
||||
/// You should destroy this object as soon as possible. Data is only committed when it
|
||||
/// is destroyed.
|
||||
#[must_use]
|
||||
pub struct Buffer<'a, T: 'a>
|
||||
where T: Sample
|
||||
{
|
||||
// Always contains something, taken by `Drop`
|
||||
// TODO: change that
|
||||
target: Option<cpal_impl::Buffer<'a, T>>,
|
||||
}
|
||||
|
||||
impl Voice {
|
||||
/// Builds a new channel.
|
||||
#[inline]
|
||||
pub fn new(endpoint: &Endpoint, format: &Format, event_loop: &EventLoop)
|
||||
-> Result<(Voice, SamplesStream), CreationError> {
|
||||
let (voice, stream) = cpal_impl::Voice::new(&endpoint.0, format, &event_loop.0)?;
|
||||
|
||||
let voice = Voice {
|
||||
voice: voice,
|
||||
format: format.clone(),
|
||||
};
|
||||
|
||||
let stream = SamplesStream(stream);
|
||||
|
||||
Ok((voice, stream))
|
||||
}
|
||||
|
||||
/// Returns the format used by the voice.
|
||||
#[inline]
|
||||
pub fn format(&self) -> &Format {
|
||||
&self.format
|
||||
}
|
||||
|
||||
/// DEPRECATED: use `format` instead. Returns the number of channels.
|
||||
///
|
||||
/// You can add data with any number of channels, but matching the voice's native format
|
||||
/// will lead to better performances.
|
||||
#[deprecated]
|
||||
#[inline]
|
||||
pub fn get_channels(&self) -> ChannelsCount {
|
||||
self.format().channels.len() as ChannelsCount
|
||||
}
|
||||
|
||||
/// DEPRECATED: use `format` instead. Returns the number of samples that are played per second.
|
||||
///
|
||||
/// You can add data with any samples rate, but matching the voice's native format
|
||||
/// will lead to better performances.
|
||||
#[deprecated]
|
||||
#[inline]
|
||||
pub fn get_samples_rate(&self) -> SamplesRate {
|
||||
self.format().samples_rate
|
||||
}
|
||||
|
||||
/// DEPRECATED: use `format` instead. Returns the format of the samples that are accepted by the backend.
|
||||
///
|
||||
/// You can add data of any format, but matching the voice's native format
|
||||
/// will lead to better performances.
|
||||
#[deprecated]
|
||||
#[inline]
|
||||
pub fn get_samples_format(&self) -> SampleFormat {
|
||||
self.format().data_type
|
||||
}
|
||||
|
||||
/// Sends a command to the audio device that it should start playing.
|
||||
///
|
||||
/// Has no effect is the voice was already playing.
|
||||
///
|
||||
/// Only call this after you have submitted some data, otherwise you may hear
|
||||
/// some glitches.
|
||||
#[inline]
|
||||
pub fn play(&mut self) {
|
||||
self.voice.play()
|
||||
}
|
||||
|
||||
/// Sends a command to the audio device that it should stop playing.
|
||||
///
|
||||
/// Has no effect is the voice was already paused.
|
||||
///
|
||||
/// If you call `play` afterwards, the playback will resume exactly where it was.
|
||||
#[inline]
|
||||
pub fn pause(&mut self) {
|
||||
self.voice.pause()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SamplesStream(cpal_impl::SamplesStream);
|
||||
|
||||
impl Stream for SamplesStream {
|
||||
type Item = UnknownTypeBuffer;
|
||||
type Error = ();
|
||||
|
||||
#[inline]
|
||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||
self.0.poll()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Buffer<T>
|
||||
impl<'a, T> Deref for Buffer<'a, T>
|
||||
where T: Sample
|
||||
{
|
||||
type Target = [T];
|
||||
|
|
@ -458,7 +387,7 @@ impl<T> Deref for Buffer<T>
|
|||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for Buffer<T>
|
||||
impl<'a, T> DerefMut for Buffer<'a, T>
|
||||
where T: Sample
|
||||
{
|
||||
#[inline]
|
||||
|
|
@ -467,7 +396,7 @@ impl<T> DerefMut for Buffer<T>
|
|||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Buffer<T>
|
||||
impl<'a, T> Drop for Buffer<'a, T>
|
||||
where T: Sample
|
||||
{
|
||||
#[inline]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue