2017-10-23 14:41:38 +00:00
|
|
|
//! # How to use cpal
|
|
|
|
//!
|
|
|
|
//! Here are some concepts cpal exposes:
|
|
|
|
//!
|
2019-12-23 03:22:35 +00:00
|
|
|
//! - A [**Host**](./struct.Host.html) provides access to the available audio devices on the system.
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! Some platforms have more than one host available, but every platform supported by CPAL has at
|
2019-12-23 03:22:35 +00:00
|
|
|
//! least one [**DefaultHost**](./struct.Host.html) that is guaranteed to be available.
|
|
|
|
//! - A [**Device**](./struct.Device.html) is an audio device that may have any number of input and
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! output streams.
|
2019-12-14 16:30:25 +00:00
|
|
|
//! - A [**Stream**](./trait.Stream.html) is an open flow of audio data. Input streams allow you to
|
|
|
|
//! receive audio data, output streams allow you to play audio data. You must choose which
|
|
|
|
//! **Device** will run your stream before you can create one. Often, a default device can be
|
|
|
|
//! retrieved via the **Host**.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! The first step is to initialise the `Host`:
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
|
|
|
//! ```
|
2019-06-28 21:42:07 +00:00
|
|
|
//! use cpal::traits::HostTrait;
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! let host = cpal::default_host();
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! Then choose an available `Device`. The easiest way is to use the default input or output
|
|
|
|
//! `Device` via the `default_input_device()` or `default_output_device()` functions. Alternatively
|
|
|
|
//! you can enumerate all the available devices with the `devices()` function. Beware that the
|
2018-02-12 13:10:24 +00:00
|
|
|
//! `default_*_device()` functions return an `Option` in case no device is available for that
|
|
|
|
//! stream type on the system.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
2019-06-21 13:57:15 +00:00
|
|
|
//! ```no_run
|
2019-06-28 21:42:07 +00:00
|
|
|
//! # use cpal::traits::HostTrait;
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
|
|
|
//! let device = host.default_output_device().expect("no output device available");
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2020-01-27 20:28:07 +00:00
|
|
|
//! Before we can create a stream, we must decide what the configuration of the audio stream is
|
|
|
|
//! going to be. You can query all the supported configurations with the
|
|
|
|
//! `supported_input_configs()` and `supported_output_configs()` methods. These produce a list of
|
|
|
|
//! `SupportedStreamConfigRange` structs which can later be turned into actual
|
|
|
|
//! `SupportedStreamConfig` structs. If you don't want to query the list of configs, you can also
|
|
|
|
//! build your own `StreamConfig` manually, but doing so could lead to an error when building the
|
|
|
|
//! stream if the config is not supported by the device.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
2020-01-27 20:28:07 +00:00
|
|
|
//! > **Note**: the `supported_input/output_configs()` methods could return an error for example if
|
|
|
|
//! > the device has been disconnected.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
|
|
|
//! ```no_run
|
2019-06-28 21:42:07 +00:00
|
|
|
//! use cpal::traits::{DeviceTrait, HostTrait};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
|
|
|
//! # let device = host.default_output_device().unwrap();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! let mut supported_configs_range = device.supported_output_configs()
|
|
|
|
//! .expect("error while querying configs");
|
|
|
|
//! let supported_config = supported_configs_range.next()
|
|
|
|
//! .expect("no supported config?!")
|
2018-02-12 13:10:24 +00:00
|
|
|
//! .with_max_sample_rate();
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! Now that we have everything for the stream, we are ready to create it from our selected device:
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
|
|
|
//! ```no_run
|
2020-01-19 15:16:09 +00:00
|
|
|
//! use cpal::Data;
|
2019-12-14 16:30:25 +00:00
|
|
|
//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
|
|
|
//! # let device = host.default_output_device().unwrap();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let config = device.default_output_config().unwrap().into();
|
2020-01-22 06:01:49 +00:00
|
|
|
//! let stream = device.build_output_stream(
|
2020-01-27 20:28:07 +00:00
|
|
|
//! &config,
|
2020-04-16 12:50:36 +00:00
|
|
|
//! move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
|
2019-12-14 16:30:25 +00:00
|
|
|
//! // react to stream events and read or write stream data here.
|
|
|
|
//! },
|
|
|
|
//! move |err| {
|
|
|
|
//! // react to errors here.
|
|
|
|
//! },
|
|
|
|
//! );
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! While the stream is running, the selected audio device will periodically call the data callback
|
2020-01-19 15:16:09 +00:00
|
|
|
//! that was passed to the function. The callback is passed an instance of either `&Data` or
|
|
|
|
//! `&mut Data` depending on whether the stream is an input stream or output stream respectively.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! > **Note**: Creating and running a stream will *not* block the thread. On modern platforms, the
|
|
|
|
//! > given callback is called by a dedicated, high-priority thread responsible for delivering
|
|
|
|
//! > audio data to the system's audio device in a timely manner. On older platforms that only
|
|
|
|
//! > provide a blocking API (e.g. ALSA), CPAL will create a thread in order to consistently
|
2019-12-31 15:02:08 +00:00
|
|
|
//! > provide non-blocking behaviour (currently this is a thread per stream, but this may change to
|
|
|
|
//! > use a single thread for all streams). *If this is an issue for your platform or design,
|
|
|
|
//! > please share your issue and use-case with the CPAL team on the github issue tracker for
|
2019-12-14 16:30:25 +00:00
|
|
|
//! > consideration.*
|
|
|
|
//!
|
2020-01-19 15:16:09 +00:00
|
|
|
//! In this example, we simply fill the given output buffer with silence.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
2019-06-21 13:57:15 +00:00
|
|
|
//! ```no_run
|
2020-01-19 15:16:09 +00:00
|
|
|
//! use cpal::{Data, Sample, SampleFormat};
|
2019-12-14 16:30:25 +00:00
|
|
|
//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
2019-12-14 16:30:25 +00:00
|
|
|
//! # let device = host.default_output_device().unwrap();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let supported_config = device.default_output_config().unwrap();
|
2020-01-19 15:16:09 +00:00
|
|
|
//! let err_fn = |err| eprintln!("an error occurred on the output audio stream: {}", err);
|
2020-02-02 17:28:38 +00:00
|
|
|
//! let sample_format = supported_config.sample_format();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! let config = supported_config.into();
|
|
|
|
//! let stream = match sample_format {
|
|
|
|
//! SampleFormat::F32 => device.build_output_stream(&config, write_silence::<f32>, err_fn),
|
|
|
|
//! SampleFormat::I16 => device.build_output_stream(&config, write_silence::<i16>, err_fn),
|
|
|
|
//! SampleFormat::U16 => device.build_output_stream(&config, write_silence::<u16>, err_fn),
|
2020-01-22 06:01:49 +00:00
|
|
|
//! }.unwrap();
|
|
|
|
//!
|
2020-04-16 12:50:36 +00:00
|
|
|
//! fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) {
|
2020-01-14 21:41:44 +00:00
|
|
|
//! for sample in data.iter_mut() {
|
|
|
|
//! *sample = Sample::from(&0.0);
|
|
|
|
//! }
|
|
|
|
//! }
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! Not all platforms automatically run the stream upon creation. To ensure the stream has started,
|
|
|
|
//! we can use `Stream::play`.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
|
|
|
//! ```no_run
|
2019-12-14 16:30:25 +00:00
|
|
|
//! # use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
2019-12-14 16:30:25 +00:00
|
|
|
//! # let device = host.default_output_device().unwrap();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let supported_config = device.default_output_config().unwrap();
|
2020-02-02 17:28:38 +00:00
|
|
|
//! # let sample_format = supported_config.sample_format();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let config = supported_config.into();
|
2020-04-16 12:50:36 +00:00
|
|
|
//! # let data_fn = move |_data: &mut cpal::Data, _: &cpal::OutputCallbackInfo| {};
|
2020-01-14 21:41:44 +00:00
|
|
|
//! # let err_fn = move |_err| {};
|
2020-02-02 17:28:38 +00:00
|
|
|
//! # let stream = device.build_output_stream_raw(&config, sample_format, data_fn, err_fn).unwrap();
|
2019-12-14 16:30:25 +00:00
|
|
|
//! stream.play().unwrap();
|
2017-10-23 14:41:38 +00:00
|
|
|
//! ```
|
|
|
|
//!
|
2019-12-14 16:30:25 +00:00
|
|
|
//! Some devices support pausing the audio stream. This can be useful for saving energy in moments
|
|
|
|
//! of silence.
|
2017-10-23 14:41:38 +00:00
|
|
|
//!
|
|
|
|
//! ```no_run
|
2019-12-14 16:30:25 +00:00
|
|
|
//! # use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
//! # let host = cpal::default_host();
|
2019-12-14 16:30:25 +00:00
|
|
|
//! # let device = host.default_output_device().unwrap();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let supported_config = device.default_output_config().unwrap();
|
2020-02-02 17:28:38 +00:00
|
|
|
//! # let sample_format = supported_config.sample_format();
|
2020-01-27 20:28:07 +00:00
|
|
|
//! # let config = supported_config.into();
|
2020-04-16 12:50:36 +00:00
|
|
|
//! # let data_fn = move |_data: &mut cpal::Data, _: &cpal::OutputCallbackInfo| {};
|
2020-01-14 21:41:44 +00:00
|
|
|
//! # let err_fn = move |_err| {};
|
2020-02-02 17:28:38 +00:00
|
|
|
//! # let stream = device.build_output_stream_raw(&config, sample_format, data_fn, err_fn).unwrap();
|
2019-12-14 16:30:25 +00:00
|
|
|
//! stream.pause().unwrap();
|
2020-01-13 14:27:41 +00:00
|
|
|
//! ```
|
2016-08-02 14:13:59 +00:00
|
|
|
|
2017-10-22 12:17:25 +00:00
|
|
|
#![recursion_limit = "512"]
|
|
|
|
|
2017-11-03 09:51:02 +00:00
|
|
|
#[cfg(target_os = "windows")]
|
2015-09-01 09:23:41 +00:00
|
|
|
#[macro_use]
|
|
|
|
extern crate lazy_static;
|
2017-10-22 12:17:25 +00:00
|
|
|
// Extern crate declarations with `#[macro_use]` must unfortunately be at crate root.
|
|
|
|
#[cfg(target_os = "emscripten")]
|
|
|
|
#[macro_use]
|
|
|
|
extern crate stdweb;
|
2019-10-13 10:07:49 +00:00
|
|
|
extern crate thiserror;
|
2017-10-22 12:17:25 +00:00
|
|
|
|
2019-09-29 12:05:06 +00:00
|
|
|
pub use error::*;
|
2019-06-28 21:42:07 +00:00
|
|
|
pub use platform::{
|
2020-01-20 19:35:23 +00:00
|
|
|
available_hosts, default_host, host_from_id, Device, Devices, Host, HostId, Stream,
|
2020-01-27 20:28:07 +00:00
|
|
|
SupportedInputConfigs, SupportedOutputConfigs, ALL_HOSTS,
|
2019-06-28 21:42:07 +00:00
|
|
|
};
|
2017-10-11 11:24:49 +00:00
|
|
|
pub use samples_formats::{Sample, SampleFormat};
|
2020-04-28 15:16:37 +00:00
|
|
|
use std::convert::TryInto;
|
2020-04-16 17:06:47 +00:00
|
|
|
use std::time::Duration;
|
2015-01-05 09:52:59 +00:00
|
|
|
|
2019-09-29 12:05:06 +00:00
|
|
|
mod error;
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
mod host;
|
|
|
|
pub mod platform;
|
2014-12-17 07:47:19 +00:00
|
|
|
mod samples_formats;
|
2019-06-28 21:42:07 +00:00
|
|
|
pub mod traits;
|
[WIP] Introduce a `Host` API
This is an implementation of the API described at #204. Please see that
issue for more details on the motivation.
-----
A **Host** provides access to the available audio devices on the system.
Some platforms have more than one host available, e.g.
wasapi/asio/dsound on windows, alsa/pulse/jack on linux and so on. As a
result, some audio devices are only available on certain hosts, while
others are only available on other hosts. Every platform supported by
CPAL has at least one **DefaultHost** that is guaranteed to be available
(alsa, wasapi and coreaudio). Currently, the default hosts are the only
hosts supported by CPAL, however this will change as of landing #221 (cc
@freesig). These changes should also accommodate support for other hosts
such as jack #250 (cc @derekdreery) and pulseaudio (cc @knappador) #259.
This introduces a suite of traits allowing for both compile time and
runtime dispatch of different hosts and their uniquely associated device
and event loop types.
A new private **host** module has been added containing the individual
host implementations, each in their own submodule gated to the platforms
on which they are available.
A new **platform** module has been added containing platform-specific
items, including a dynamically dispatched host type that allows for
easily switching between hosts at runtime.
The **ALL_HOSTS** slice contains a **HostId** for each host supported on
the current platform. The **available_hosts** function produces a
**HostId** for each host that is currently *available* on the platform.
The **host_from_id** function allows for initialising a host from its
associated ID, failing with a **HostUnavailable** error. The
**default_host** function returns the default host and should never
fail.
Please see the examples for a demonstration of the change in usage. For
the most part, things look the same at the surface level, however the
role of device enumeration and creating the event loop have been moved
from global functions to host methods. The enumerate.rs example has been
updated to enumerate all devices for each host, not just the default.
**TODO**
- [x] Add the new **Host** API
- [x] Update examples for the new API.
- [x] ALSA host
- [ ] WASAPI host
- [ ] CoreAudio host
- [ ] Emscripten host **Follow-up PR**
- [ ] ASIO host #221
cc @ishitatsuyuki more to review for you if you're interested, but it
might be easier after #288 lands and this gets rebased.
2019-06-23 13:49:48 +00:00
|
|
|
|
|
|
|
/// A host's device iterator yielding only *input* devices.
|
|
|
|
pub type InputDevices<I> = std::iter::Filter<I, fn(&<I as Iterator>::Item) -> bool>;
|
|
|
|
|
|
|
|
/// A host's device iterator yielding only *output* devices.
|
|
|
|
pub type OutputDevices<I> = std::iter::Filter<I, fn(&<I as Iterator>::Item) -> bool>;
|
2015-09-01 09:23:41 +00:00
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
/// Number of channels.
|
|
|
|
pub type ChannelCount = u16;
|
|
|
|
|
|
|
|
/// The number of samples processed per second for a single channel of audio.
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
|
|
|
pub struct SampleRate(pub u32);
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
/// The set of parameters used to describe how to open a stream.
|
|
|
|
///
|
|
|
|
/// The sample format is omitted in favour of using a sample type.
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
|
|
pub struct StreamConfig {
|
2018-02-12 13:10:24 +00:00
|
|
|
pub channels: ChannelCount,
|
|
|
|
pub sample_rate: SampleRate,
|
2020-01-22 06:01:49 +00:00
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
/// Describes a range of supported stream configurations, retrieved via the
|
|
|
|
/// `Device::supported_input/output_configs` method.
|
2020-01-22 06:01:49 +00:00
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
2020-01-27 20:28:07 +00:00
|
|
|
pub struct SupportedStreamConfigRange {
|
2020-02-02 19:08:46 +00:00
|
|
|
pub(crate) channels: ChannelCount,
|
2018-02-12 13:10:24 +00:00
|
|
|
/// Minimum value for the samples rate of the supported formats.
|
2020-02-02 19:08:46 +00:00
|
|
|
pub(crate) min_sample_rate: SampleRate,
|
2018-02-12 13:10:24 +00:00
|
|
|
/// Maximum value for the samples rate of the supported formats.
|
2020-02-02 19:08:46 +00:00
|
|
|
pub(crate) max_sample_rate: SampleRate,
|
2018-02-12 13:10:24 +00:00
|
|
|
/// Type of data expected by the device.
|
2020-02-02 19:08:46 +00:00
|
|
|
pub(crate) sample_format: SampleFormat,
|
2020-01-27 20:28:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Describes a single supported stream configuration, retrieved via either a
|
|
|
|
/// `SupportedStreamConfigRange` instance or one of the `Device::default_input/output_config` methods.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
pub struct SupportedStreamConfig {
|
2020-02-02 17:28:38 +00:00
|
|
|
channels: ChannelCount,
|
|
|
|
sample_rate: SampleRate,
|
|
|
|
sample_format: SampleFormat,
|
2015-09-01 09:23:41 +00:00
|
|
|
}
|
|
|
|
|
2020-01-22 06:01:49 +00:00
|
|
|
/// A buffer of dynamically typed audio data, passed to raw stream callbacks.
|
2017-10-23 14:41:38 +00:00
|
|
|
///
|
2020-01-22 06:01:49 +00:00
|
|
|
/// Raw input stream callbacks receive `&Data`, while raw output stream callbacks expect `&mut
|
|
|
|
/// Data`.
|
2019-10-04 16:18:18 +00:00
|
|
|
#[derive(Debug)]
|
2020-01-19 14:06:19 +00:00
|
|
|
pub struct Data {
|
|
|
|
data: *mut (),
|
|
|
|
len: usize,
|
|
|
|
sample_format: SampleFormat,
|
2017-10-11 08:39:44 +00:00
|
|
|
}
|
|
|
|
|
2020-04-16 17:06:47 +00:00
|
|
|
/// A monotonic time instance associated with a stream, retrieved from either:
|
|
|
|
///
|
|
|
|
/// 1. A timestamp provided to the stream's underlying audio data callback or
|
|
|
|
/// 2. The same time source used to generate timestamps for a stream's underlying audio data
|
|
|
|
/// callback.
|
|
|
|
///
|
|
|
|
/// **StreamInstant** represents a duration since some unspecified origin occurring either before
|
|
|
|
/// or equal to the moment the stream from which it was created begins.
|
2020-04-30 12:08:00 +00:00
|
|
|
///
|
|
|
|
/// ## Host `StreamInstant` Sources
|
|
|
|
///
|
|
|
|
/// | Host | Source |
|
|
|
|
/// | ---- | ------ |
|
|
|
|
/// | alsa | `snd_pcm_status_get_htstamp` |
|
|
|
|
/// | coreaudio | `mach_absolute_time` |
|
|
|
|
/// | wasapi | `QueryPerformanceCounter` |
|
|
|
|
/// | asio | `timeGetTime` |
|
|
|
|
/// | emscripten | `AudioContext.getOutputTimestamp` |
|
2020-04-16 17:06:47 +00:00
|
|
|
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
|
|
|
|
pub struct StreamInstant {
|
2020-04-28 15:16:37 +00:00
|
|
|
secs: i64,
|
2020-04-16 17:06:47 +00:00
|
|
|
nanos: u32,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A timestamp associated with a call to an input stream's data callback.
|
|
|
|
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
|
|
|
|
pub struct InputStreamTimestamp {
|
|
|
|
/// The instant the stream's data callback was invoked.
|
|
|
|
pub callback: StreamInstant,
|
|
|
|
/// The instant that data was captured from the device.
|
|
|
|
///
|
|
|
|
/// E.g. The instant data was read from an ADC.
|
|
|
|
pub capture: StreamInstant,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A timestamp associated with a call to an output stream's data callback.
|
|
|
|
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
|
|
|
|
pub struct OutputStreamTimestamp {
|
|
|
|
/// The instant the stream's data callback was invoked.
|
|
|
|
pub callback: StreamInstant,
|
|
|
|
/// The predicted instant that data written will be delivered to the device for playback.
|
|
|
|
///
|
|
|
|
/// E.g. The instant data will be played by a DAC.
|
|
|
|
pub playback: StreamInstant,
|
|
|
|
}
|
2020-04-16 12:50:36 +00:00
|
|
|
|
|
|
|
/// Information relevant to a single call to the user's input stream data callback.
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
2020-04-16 17:06:47 +00:00
|
|
|
pub struct InputCallbackInfo {
|
|
|
|
timestamp: InputStreamTimestamp,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Information relevant to a single call to the user's output stream data callback.
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
|
|
pub struct OutputCallbackInfo {
|
|
|
|
timestamp: OutputStreamTimestamp,
|
|
|
|
}
|
2020-04-16 12:50:36 +00:00
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
impl SupportedStreamConfig {
|
2020-02-02 17:28:38 +00:00
|
|
|
pub fn channels(&self) -> ChannelCount {
|
|
|
|
self.channels
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn sample_rate(&self) -> SampleRate {
|
|
|
|
self.sample_rate
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn sample_format(&self) -> SampleFormat {
|
|
|
|
self.sample_format
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn config(&self) -> StreamConfig {
|
|
|
|
StreamConfig {
|
|
|
|
channels: self.channels,
|
|
|
|
sample_rate: self.sample_rate,
|
2020-01-27 20:28:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-16 17:06:47 +00:00
|
|
|
impl StreamInstant {
|
|
|
|
/// The amount of time elapsed from another instant to this one.
|
|
|
|
///
|
|
|
|
/// Returns `None` if `earlier` is later than self.
|
|
|
|
pub fn duration_since(&self, earlier: &Self) -> Option<Duration> {
|
|
|
|
if self < earlier {
|
|
|
|
None
|
|
|
|
} else {
|
2020-04-28 15:16:37 +00:00
|
|
|
(self.as_nanos() - earlier.as_nanos())
|
|
|
|
.try_into()
|
|
|
|
.ok()
|
|
|
|
.map(Duration::from_nanos)
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the instant in time after the given duration has passed.
|
|
|
|
///
|
|
|
|
/// Returns `None` if the resulting instant would exceed the bounds of the underlying data
|
|
|
|
/// structure.
|
|
|
|
pub fn add(&self, duration: Duration) -> Option<Self> {
|
2020-04-28 15:16:37 +00:00
|
|
|
self.as_nanos()
|
|
|
|
.checked_add(duration.as_nanos() as i128)
|
|
|
|
.and_then(Self::from_nanos_i128)
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the instant in time one `duration` ago.
|
|
|
|
///
|
|
|
|
/// Returns `None` if the resulting instant would underflow. As a result, it is important to
|
|
|
|
/// consider that on some platforms the `StreamInstant` may begin at `0` from the moment the
|
|
|
|
/// source stream is created.
|
|
|
|
pub fn sub(&self, duration: Duration) -> Option<Self> {
|
2020-04-28 15:16:37 +00:00
|
|
|
self.as_nanos()
|
|
|
|
.checked_sub(duration.as_nanos() as i128)
|
|
|
|
.and_then(Self::from_nanos_i128)
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
|
2020-04-28 15:16:37 +00:00
|
|
|
fn as_nanos(&self) -> i128 {
|
|
|
|
(self.secs as i128 * 1_000_000_000) + self.nanos as i128
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
|
2020-04-28 15:16:37 +00:00
|
|
|
fn from_nanos(nanos: i64) -> Self {
|
|
|
|
let secs = nanos / 1_000_000_000;
|
|
|
|
let subsec_nanos = nanos - secs * 1_000_000_000;
|
|
|
|
Self::new(secs as i64, subsec_nanos as u32)
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
|
2020-04-28 15:16:37 +00:00
|
|
|
fn from_nanos_i128(nanos: i128) -> Option<Self> {
|
|
|
|
let secs = nanos / 1_000_000_000;
|
|
|
|
if secs > std::i64::MAX as i128 || secs < std::i64::MIN as i128 {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let subsec_nanos = nanos - secs * 1_000_000_000;
|
|
|
|
debug_assert!(subsec_nanos < std::u32::MAX as i128);
|
|
|
|
Some(Self::new(secs as i64, subsec_nanos as u32))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn new(secs: i64, nanos: u32) -> Self {
|
|
|
|
StreamInstant { secs, nanos }
|
2020-04-16 17:06:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl InputCallbackInfo {
|
|
|
|
/// The timestamp associated with the call to an input stream's data callback.
|
|
|
|
pub fn timestamp(&self) -> InputStreamTimestamp {
|
|
|
|
self.timestamp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl OutputCallbackInfo {
|
|
|
|
/// The timestamp associated with the call to an output stream's data callback.
|
|
|
|
pub fn timestamp(&self) -> OutputStreamTimestamp {
|
|
|
|
self.timestamp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-19 14:06:19 +00:00
|
|
|
impl Data {
|
|
|
|
// Internal constructor for host implementations to use.
|
2020-01-19 18:05:17 +00:00
|
|
|
//
|
|
|
|
// The following requirements must be met in order for the safety of `Data`'s public API.
|
|
|
|
//
|
|
|
|
// - The `data` pointer must point to the first sample in the slice containing all samples.
|
|
|
|
// - The `len` must describe the length of the buffer as a number of samples in the expected
|
|
|
|
// format specified via the `sample_format` argument.
|
|
|
|
// - The `sample_format` must correctly represent the underlying sample data delivered/expected
|
|
|
|
// by the stream.
|
2020-01-19 14:06:19 +00:00
|
|
|
pub(crate) unsafe fn from_parts(
|
|
|
|
data: *mut (),
|
|
|
|
len: usize,
|
|
|
|
sample_format: SampleFormat,
|
|
|
|
) -> Self {
|
2020-01-20 19:35:23 +00:00
|
|
|
Data {
|
|
|
|
data,
|
|
|
|
len,
|
|
|
|
sample_format,
|
|
|
|
}
|
2020-01-19 14:06:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The sample format of the internal audio data.
|
|
|
|
pub fn sample_format(&self) -> SampleFormat {
|
|
|
|
self.sample_format
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The full length of the buffer in samples.
|
|
|
|
///
|
|
|
|
/// The returned length is the same length as the slice of type `T` that would be returned via
|
|
|
|
/// `as_slice` given a sample type that matches the inner sample format.
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
self.len
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The raw slice of memory representing the underlying audio data as a slice of bytes.
|
|
|
|
///
|
2020-01-19 18:05:17 +00:00
|
|
|
/// It is up to the user to interpret the slice of memory based on `Data::sample_format`.
|
2020-01-19 14:06:19 +00:00
|
|
|
pub fn bytes(&self) -> &[u8] {
|
|
|
|
let len = self.len * self.sample_format.sample_size();
|
2020-01-19 18:05:17 +00:00
|
|
|
// The safety of this block relies on correct construction of the `Data` instance. See
|
|
|
|
// the unsafe `from_parts` constructor for these requirements.
|
2020-01-20 19:35:23 +00:00
|
|
|
unsafe { std::slice::from_raw_parts(self.data as *const u8, len) }
|
2020-01-19 14:06:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The raw slice of memory representing the underlying audio data as a slice of bytes.
|
|
|
|
///
|
2020-01-19 18:05:17 +00:00
|
|
|
/// It is up to the user to interpret the slice of memory based on `Data::sample_format`.
|
2020-01-19 14:06:19 +00:00
|
|
|
pub fn bytes_mut(&mut self) -> &mut [u8] {
|
|
|
|
let len = self.len * self.sample_format.sample_size();
|
2020-01-19 18:05:17 +00:00
|
|
|
// The safety of this block relies on correct construction of the `Data` instance. See
|
|
|
|
// the unsafe `from_parts` constructor for these requirements.
|
2020-01-20 19:35:23 +00:00
|
|
|
unsafe { std::slice::from_raw_parts_mut(self.data as *mut u8, len) }
|
2020-01-19 14:06:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Access the data as a slice of sample type `T`.
|
|
|
|
///
|
|
|
|
/// Returns `None` if the sample type does not match the expected sample format.
|
|
|
|
pub fn as_slice<T>(&self) -> Option<&[T]>
|
|
|
|
where
|
|
|
|
T: Sample,
|
|
|
|
{
|
|
|
|
if T::FORMAT == self.sample_format {
|
2020-01-19 18:05:17 +00:00
|
|
|
// The safety of this block relies on correct construction of the `Data` instance. See
|
|
|
|
// the unsafe `from_parts` constructor for these requirements.
|
2020-01-20 19:35:23 +00:00
|
|
|
unsafe { Some(std::slice::from_raw_parts(self.data as *const T, self.len)) }
|
2020-01-19 14:06:19 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Access the data as a slice of sample type `T`.
|
|
|
|
///
|
|
|
|
/// Returns `None` if the sample type does not match the expected sample format.
|
|
|
|
pub fn as_slice_mut<T>(&mut self) -> Option<&mut [T]>
|
|
|
|
where
|
|
|
|
T: Sample,
|
|
|
|
{
|
|
|
|
if T::FORMAT == self.sample_format {
|
2020-01-19 18:05:17 +00:00
|
|
|
// The safety of this block relies on correct construction of the `Data` instance. See
|
|
|
|
// the unsafe `from_parts` constructor for these requirements.
|
2020-01-19 14:06:19 +00:00
|
|
|
unsafe {
|
2020-01-20 19:35:23 +00:00
|
|
|
Some(std::slice::from_raw_parts_mut(
|
|
|
|
self.data as *mut T,
|
|
|
|
self.len,
|
|
|
|
))
|
2020-01-19 14:06:19 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
2015-09-01 09:23:41 +00:00
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
impl SupportedStreamConfigRange {
|
2020-02-02 19:08:46 +00:00
|
|
|
pub fn channels(&self) -> ChannelCount {
|
|
|
|
self.channels
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn min_sample_rate(&self) -> SampleRate {
|
|
|
|
self.min_sample_rate
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn max_sample_rate(&self) -> SampleRate {
|
|
|
|
self.max_sample_rate
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn sample_format(&self) -> SampleFormat {
|
|
|
|
self.sample_format
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieve a `SupportedStreamConfig` with the given sample rate.
|
|
|
|
///
|
|
|
|
/// **panic!**s if the given `sample_rate` is outside the range specified within this
|
|
|
|
/// `SupportedStreamConfigRange` instance.
|
|
|
|
pub fn with_sample_rate(self, sample_rate: SampleRate) -> SupportedStreamConfig {
|
2020-03-18 03:16:04 +00:00
|
|
|
assert!(self.min_sample_rate <= sample_rate && sample_rate <= self.max_sample_rate);
|
2020-02-02 19:08:46 +00:00
|
|
|
SupportedStreamConfig {
|
|
|
|
channels: self.channels,
|
|
|
|
sample_format: self.sample_format,
|
|
|
|
sample_rate,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
/// Turns this `SupportedStreamConfigRange` into a `SupportedStreamConfig` corresponding to the maximum samples rate.
|
2017-10-18 18:24:05 +00:00
|
|
|
#[inline]
|
2020-01-27 20:28:07 +00:00
|
|
|
pub fn with_max_sample_rate(self) -> SupportedStreamConfig {
|
|
|
|
SupportedStreamConfig {
|
2018-02-12 13:10:24 +00:00
|
|
|
channels: self.channels,
|
|
|
|
sample_rate: self.max_sample_rate,
|
2020-01-27 20:28:07 +00:00
|
|
|
sample_format: self.sample_format,
|
2018-02-12 13:10:24 +00:00
|
|
|
}
|
2017-10-18 18:24:05 +00:00
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
/// A comparison function which compares two `SupportedStreamConfigRange`s in terms of their priority of
|
2018-02-12 13:10:24 +00:00
|
|
|
/// use as a default stream format.
|
2017-10-18 18:24:05 +00:00
|
|
|
///
|
2018-02-12 13:10:24 +00:00
|
|
|
/// Some backends do not provide a default stream format for their audio devices. In these
|
|
|
|
/// cases, CPAL attempts to decide on a reasonable default format for the user. To do this we
|
|
|
|
/// use the "greatest" of all supported stream formats when compared with this method.
|
2017-10-18 18:24:05 +00:00
|
|
|
///
|
2020-01-27 20:28:07 +00:00
|
|
|
/// SupportedStreamConfigs are prioritised by the following heuristics:
|
2017-10-18 18:24:05 +00:00
|
|
|
///
|
2018-02-12 13:10:24 +00:00
|
|
|
/// **Channels**:
|
|
|
|
///
|
|
|
|
/// - Stereo
|
|
|
|
/// - Mono
|
|
|
|
/// - Max available channels
|
2017-10-18 18:24:05 +00:00
|
|
|
///
|
2018-02-12 13:10:24 +00:00
|
|
|
/// **Sample format**:
|
|
|
|
/// - f32
|
|
|
|
/// - i16
|
|
|
|
/// - u16
|
2017-10-18 18:24:05 +00:00
|
|
|
///
|
2018-02-12 13:10:24 +00:00
|
|
|
/// **Sample rate**:
|
|
|
|
///
|
|
|
|
/// - 44100 (cd quality)
|
|
|
|
/// - Max sample rate
|
|
|
|
pub fn cmp_default_heuristics(&self, other: &Self) -> std::cmp::Ordering {
|
|
|
|
use std::cmp::Ordering::Equal;
|
|
|
|
use SampleFormat::{F32, I16, U16};
|
|
|
|
|
|
|
|
let cmp_stereo = (self.channels == 2).cmp(&(other.channels == 2));
|
|
|
|
if cmp_stereo != Equal {
|
|
|
|
return cmp_stereo;
|
|
|
|
}
|
|
|
|
|
|
|
|
let cmp_mono = (self.channels == 1).cmp(&(other.channels == 1));
|
|
|
|
if cmp_mono != Equal {
|
|
|
|
return cmp_mono;
|
|
|
|
}
|
|
|
|
|
|
|
|
let cmp_channels = self.channels.cmp(&other.channels);
|
|
|
|
if cmp_channels != Equal {
|
|
|
|
return cmp_channels;
|
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
let cmp_f32 = (self.sample_format == F32).cmp(&(other.sample_format == F32));
|
2018-02-12 13:10:24 +00:00
|
|
|
if cmp_f32 != Equal {
|
|
|
|
return cmp_f32;
|
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
let cmp_i16 = (self.sample_format == I16).cmp(&(other.sample_format == I16));
|
2018-02-12 13:10:24 +00:00
|
|
|
if cmp_i16 != Equal {
|
|
|
|
return cmp_i16;
|
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
let cmp_u16 = (self.sample_format == U16).cmp(&(other.sample_format == U16));
|
2018-02-12 13:10:24 +00:00
|
|
|
if cmp_u16 != Equal {
|
|
|
|
return cmp_u16;
|
|
|
|
}
|
|
|
|
|
|
|
|
const HZ_44100: SampleRate = SampleRate(44_100);
|
2020-01-20 19:35:23 +00:00
|
|
|
let r44100_in_self = self.min_sample_rate <= HZ_44100 && HZ_44100 <= self.max_sample_rate;
|
|
|
|
let r44100_in_other =
|
|
|
|
other.min_sample_rate <= HZ_44100 && HZ_44100 <= other.max_sample_rate;
|
2018-02-12 13:10:24 +00:00
|
|
|
let cmp_r44100 = r44100_in_self.cmp(&r44100_in_other);
|
|
|
|
if cmp_r44100 != Equal {
|
|
|
|
return cmp_r44100;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.max_sample_rate.cmp(&other.max_sample_rate)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-27 20:28:07 +00:00
|
|
|
impl From<SupportedStreamConfig> for StreamConfig {
|
|
|
|
fn from(conf: SupportedStreamConfig) -> Self {
|
2020-02-02 17:28:38 +00:00
|
|
|
conf.config()
|
2020-01-27 20:28:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<SupportedStreamConfig> for SupportedStreamConfigRange {
|
2018-02-12 13:10:24 +00:00
|
|
|
#[inline]
|
2020-01-27 20:28:07 +00:00
|
|
|
fn from(format: SupportedStreamConfig) -> SupportedStreamConfigRange {
|
|
|
|
SupportedStreamConfigRange {
|
2018-02-12 13:10:24 +00:00
|
|
|
channels: format.channels,
|
|
|
|
min_sample_rate: format.sample_rate,
|
|
|
|
max_sample_rate: format.sample_rate,
|
2020-01-27 20:28:07 +00:00
|
|
|
sample_format: format.sample_format,
|
2018-02-12 13:10:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If a backend does not provide an API for retrieving supported formats, we query it with a bunch
|
|
|
|
// of commonly used rates. This is always the case for wasapi and is sometimes the case for alsa.
|
|
|
|
//
|
|
|
|
// If a rate you desire is missing from this list, feel free to add it!
|
|
|
|
#[cfg(target_os = "windows")]
|
|
|
|
const COMMON_SAMPLE_RATES: &'static [SampleRate] = &[
|
|
|
|
SampleRate(5512),
|
|
|
|
SampleRate(8000),
|
|
|
|
SampleRate(11025),
|
|
|
|
SampleRate(16000),
|
|
|
|
SampleRate(22050),
|
|
|
|
SampleRate(32000),
|
|
|
|
SampleRate(44100),
|
|
|
|
SampleRate(48000),
|
|
|
|
SampleRate(64000),
|
|
|
|
SampleRate(88200),
|
|
|
|
SampleRate(96000),
|
|
|
|
SampleRate(176400),
|
|
|
|
SampleRate(192000),
|
|
|
|
];
|
2020-04-28 15:16:37 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_stream_instant() {
|
|
|
|
let a = StreamInstant::new(2, 0);
|
|
|
|
let b = StreamInstant::new(-2, 0);
|
|
|
|
let min = StreamInstant::new(std::i64::MIN, 0);
|
|
|
|
let max = StreamInstant::new(std::i64::MAX, 0);
|
|
|
|
assert_eq!(
|
|
|
|
a.sub(Duration::from_secs(1)),
|
|
|
|
Some(StreamInstant::new(1, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
a.sub(Duration::from_secs(2)),
|
|
|
|
Some(StreamInstant::new(0, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
a.sub(Duration::from_secs(3)),
|
|
|
|
Some(StreamInstant::new(-1, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(min.sub(Duration::from_secs(1)), None);
|
|
|
|
assert_eq!(
|
|
|
|
b.add(Duration::from_secs(1)),
|
|
|
|
Some(StreamInstant::new(-1, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
b.add(Duration::from_secs(2)),
|
|
|
|
Some(StreamInstant::new(0, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
b.add(Duration::from_secs(3)),
|
|
|
|
Some(StreamInstant::new(1, 0))
|
|
|
|
);
|
|
|
|
assert_eq!(max.add(Duration::from_secs(1)), None);
|
|
|
|
}
|