From 269c60fde0c1c09fbdf50d65d7bf0d3a4e8d217c Mon Sep 17 00:00:00 2001 From: Alex Moon Date: Mon, 14 Dec 2020 10:56:14 -0700 Subject: [PATCH 1/2] Add an Android example and enhance the other examples with CLI argument parsing. --- .github/workflows/cpal.yml | 4 ++- Cargo.toml | 14 +++++--- examples/android.rs | 65 ++++++++++++++++++++++++++++++++++++++ examples/beep.rs | 49 ++++++++++++++++++++-------- examples/enumerate.rs | 24 +++++++------- examples/feedback.rs | 61 +++++++++++++++++++++++++---------- examples/record_wav.rs | 58 ++++++++++++++++++++++++++++++---- 7 files changed, 222 insertions(+), 53 deletions(-) create mode 100644 examples/android.rs diff --git a/.github/workflows/cpal.yml b/.github/workflows/cpal.yml index 2b18968..783f95e 100644 --- a/.github/workflows/cpal.yml +++ b/.github/workflows/cpal.yml @@ -262,6 +262,8 @@ jobs: toolchain: stable override: true target: armv7-linux-androideabi + - name: Check android + run: cargo check --example android --target armv7-linux-androideabi --verbose - name: Check beep run: cargo check --example beep --target armv7-linux-androideabi --verbose - name: Check enumerate @@ -284,4 +286,4 @@ jobs: - name: Install Cargo APK run: cargo install cargo-apk - name: Build APK - run: cargo apk build --example beep + run: cargo apk build --example android diff --git a/Cargo.toml b/Cargo.toml index b5daa78..f7ce079 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ thiserror = "1.0.2" anyhow = "1.0.12" hound = "3.4" ringbuf = "0.2" +structopt = "0.3.21" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3", features = ["audiosessiontypes", "audioclient", "coml2api", "combaseapi", "debug", "devpkey", "handleapi", "ksmedia", "mmdeviceapi", "objbase", "profileapi", "std", "synchapi", "winbase", "winuser"] } @@ -52,22 +53,27 @@ ndk = "0.2" ndk-glue = "0.2" jni = "0.17" +[[example]] +name = "android" +path = "examples/android.rs" +crate-type = ["cdylib"] + [[example]] name = "beep" path = "examples/beep.rs" -crate-type = ["cdylib"] +crate-type = ["bin"] [[example]] name = "enumerate" path = "examples/enumerate.rs" -crate-type = ["cdylib"] +crate-type = ["bin"] [[example]] name = "feedback" path = "examples/feedback.rs" -crate-type = ["cdylib"] +crate-type = ["bin"] [[example]] name = "record_wav" path = "examples/record_wav.rs" -crate-type = ["cdylib"] +crate-type = ["bin"] diff --git a/examples/android.rs b/examples/android.rs new file mode 100644 index 0000000..7ca17da --- /dev/null +++ b/examples/android.rs @@ -0,0 +1,65 @@ +#![allow(dead_code)] + +extern crate anyhow; +extern crate cpal; + +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + +#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))] +fn main() { + let host = cpal::default_host(); + + let device = host + .default_output_device() + .expect("failed to find output device"); + + let config = device.default_output_config().unwrap(); + + match config.sample_format() { + cpal::SampleFormat::F32 => run::(&device, &config.into()).unwrap(), + cpal::SampleFormat::I16 => run::(&device, &config.into()).unwrap(), + cpal::SampleFormat::U16 => run::(&device, &config.into()).unwrap(), + } +} + +fn run(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error> +where + T: cpal::Sample, +{ + let sample_rate = config.sample_rate.0 as f32; + let channels = config.channels as usize; + + // Produce a sinusoid of maximum amplitude. + let mut sample_clock = 0f32; + let mut next_value = move || { + sample_clock = (sample_clock + 1.0) % sample_rate; + (sample_clock * 440.0 * 2.0 * std::f32::consts::PI / sample_rate).sin() + }; + + let err_fn = |err| eprintln!("an error occurred on stream: {}", err); + + let stream = device.build_output_stream( + config, + move |data: &mut [T], _: &cpal::OutputCallbackInfo| { + write_data(data, channels, &mut next_value) + }, + err_fn, + )?; + stream.play()?; + + std::thread::sleep(std::time::Duration::from_millis(1000)); + + Ok(()) +} + +fn write_data(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32) +where + T: cpal::Sample, +{ + for frame in output.chunks_mut(channels) { + let value: T = cpal::Sample::from::(&next_sample()); + for sample in frame.iter_mut() { + *sample = value; + } + } +} diff --git a/examples/beep.rs b/examples/beep.rs index 696f3f0..80920fd 100644 --- a/examples/beep.rs +++ b/examples/beep.rs @@ -1,10 +1,27 @@ extern crate anyhow; extern crate cpal; +extern crate structopt; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt(name = "beep", about = "Simple example of audio playback.")] +struct Opt { + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + #[structopt(short, long)] + jack: bool, + + #[structopt(default_value = "default")] + device: String, +} + +fn main() -> anyhow::Result<()> { + let opt = Opt::from_args(); -#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))] -fn main() { // Conditionally compile with jack if the feature is specified. #[cfg(all( any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), @@ -12,10 +29,7 @@ fn main() { ))] // Manually check for flags. Can be passed through cargo with -- e.g. // cargo run --release --example beep --features jack -- --jack - let host = if std::env::args() - .collect::() - .contains(&String::from("--jack")) - { + let host = if opt.jack { cpal::host_from_id(cpal::available_hosts() .into_iter() .find(|id| *id == cpal::HostId::Jack) @@ -32,19 +46,26 @@ fn main() { ))] let host = cpal::default_host(); - let device = host - .default_output_device() - .expect("failed to find a default output device"); + let device = if opt.device == "default" { + host.default_output_device() + } else { + host.output_devices()? + .find(|x| x.name().map(|y| y == opt.device).unwrap_or(false)) + } + .expect("failed to find output device"); + println!("Output device: {}", device.name()?); + let config = device.default_output_config().unwrap(); + println!("Default output config: {:?}", config); match config.sample_format() { - cpal::SampleFormat::F32 => run::(&device, &config.into()).unwrap(), - cpal::SampleFormat::I16 => run::(&device, &config.into()).unwrap(), - cpal::SampleFormat::U16 => run::(&device, &config.into()).unwrap(), + cpal::SampleFormat::F32 => run::(&device, &config.into()), + cpal::SampleFormat::I16 => run::(&device, &config.into()), + cpal::SampleFormat::U16 => run::(&device, &config.into()), } } -fn run(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error> +pub fn run(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error> where T: cpal::Sample, { @@ -55,7 +76,7 @@ where let mut sample_clock = 0f32; let mut next_value = move || { sample_clock = (sample_clock + 1.0) % sample_rate; - (sample_clock * 440.0 * 2.0 * 3.141592 / sample_rate).sin() + (sample_clock * 440.0 * 2.0 * std::f32::consts::PI / sample_rate).sin() }; let err_fn = |err| eprintln!("an error occurred on stream: {}", err); diff --git a/examples/enumerate.rs b/examples/enumerate.rs index 911c646..ccba0eb 100644 --- a/examples/enumerate.rs +++ b/examples/enumerate.rs @@ -26,16 +26,16 @@ fn main() -> Result<(), anyhow::Error> { if let Ok(conf) = device.default_input_config() { println!(" Default input stream config:\n {:?}", conf); } - let mut input_configs = match device.supported_input_configs() { - Ok(f) => f.peekable(), + let input_configs = match device.supported_input_configs() { + Ok(f) => f.collect(), Err(e) => { - println!("Error: {:?}", e); - continue; + println!(" Error getting supported input configs: {:?}", e); + Vec::new() } }; - if input_configs.peek().is_some() { + if !input_configs.is_empty() { println!(" All supported input stream configs:"); - for (config_index, config) in input_configs.enumerate() { + for (config_index, config) in input_configs.into_iter().enumerate() { println!( " {}.{}. {:?}", device_index + 1, @@ -49,16 +49,16 @@ fn main() -> Result<(), anyhow::Error> { if let Ok(conf) = device.default_output_config() { println!(" Default output stream config:\n {:?}", conf); } - let mut output_configs = match device.supported_output_configs() { - Ok(f) => f.peekable(), + let output_configs = match device.supported_output_configs() { + Ok(f) => f.collect(), Err(e) => { - println!("Error: {:?}", e); - continue; + println!(" Error getting supported output configs: {:?}", e); + Vec::new() } }; - if output_configs.peek().is_some() { + if !output_configs.is_empty() { println!(" All supported output stream configs:"); - for (config_index, config) in output_configs.enumerate() { + for (config_index, config) in output_configs.into_iter().enumerate() { println!( " {}.{}. {:?}", device_index + 1, diff --git a/examples/feedback.rs b/examples/feedback.rs index ba38fdd..cb4cac5 100644 --- a/examples/feedback.rs +++ b/examples/feedback.rs @@ -9,13 +9,35 @@ extern crate anyhow; extern crate cpal; extern crate ringbuf; +extern crate structopt; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use ringbuf::RingBuffer; +use structopt::StructOpt; -const LATENCY_MS: f32 = 150.0; +#[derive(Debug, StructOpt)] +#[structopt(name = "beep", about = "Simple example of audio playback.")] +struct Opt { + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + #[structopt(short, long)] + jack: bool, + + #[structopt(short, long, default_value = "150.0")] + latency: f32, + + #[structopt(default_value = "default")] + input_device: String, + + #[structopt(default_value = "default")] + output_device: String, +} fn main() -> Result<(), anyhow::Error> { + let opt = Opt::from_args(); + // Conditionally compile with jack if the feature is specified. #[cfg(all( any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), @@ -23,10 +45,7 @@ fn main() -> Result<(), anyhow::Error> { ))] // Manually check for flags. Can be passed through cargo with -- e.g. // cargo run --release --example beep --features jack -- --jack - let host = if std::env::args() - .collect::() - .contains(&String::from("--jack")) - { + let host = if opt.jack { cpal::host_from_id(cpal::available_hosts() .into_iter() .find(|id| *id == cpal::HostId::Jack) @@ -43,21 +62,31 @@ fn main() -> Result<(), anyhow::Error> { ))] let host = cpal::default_host(); - // Default devices. - let input_device = host - .default_input_device() - .expect("failed to get default input device"); - let output_device = host - .default_output_device() - .expect("failed to get default output device"); - println!("Using default input device: \"{}\"", input_device.name()?); - println!("Using default output device: \"{}\"", output_device.name()?); + // Find devices. + let input_device = if opt.input_device == "default" { + host.default_input_device() + } else { + host.input_devices()? + .find(|x| x.name().map(|y| y == opt.input_device).unwrap_or(false)) + } + .expect("failed to find input device"); + + let output_device = if opt.output_device == "default" { + host.default_output_device() + } else { + host.output_devices()? + .find(|x| x.name().map(|y| y == opt.output_device).unwrap_or(false)) + } + .expect("failed to find output device"); + + println!("Using input device: \"{}\"", input_device.name()?); + println!("Using output device: \"{}\"", output_device.name()?); // We'll try and use the same configuration between streams to keep it simple. let config: cpal::StreamConfig = input_device.default_input_config()?.into(); // Create a delay in case the input and output devices aren't synced. - let latency_frames = (LATENCY_MS / 1_000.0) * config.sample_rate.0 as f32; + let latency_frames = (opt.latency / 1_000.0) * config.sample_rate.0 as f32; let latency_samples = latency_frames as usize * config.channels as usize; // The buffer to share samples @@ -111,7 +140,7 @@ fn main() -> Result<(), anyhow::Error> { // Play the streams. println!( "Starting the input and output streams with `{}` milliseconds of latency.", - LATENCY_MS + opt.latency ); input_stream.play()?; output_stream.play()?; diff --git a/examples/record_wav.rs b/examples/record_wav.rs index ac6d237..e4c9090 100644 --- a/examples/record_wav.rs +++ b/examples/record_wav.rs @@ -5,25 +5,71 @@ extern crate anyhow; extern crate cpal; extern crate hound; +extern crate structopt; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::fs::File; use std::io::BufWriter; use std::sync::{Arc, Mutex}; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt(name = "beep", about = "Simple example of audio playback.")] +struct Opt { + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + #[structopt(short, long)] + jack: bool, + + #[structopt(default_value = "default")] + device: String, +} fn main() -> Result<(), anyhow::Error> { - // Use the default host for working with audio devices. + let opt = Opt::from_args(); + + // Conditionally compile with jack if the feature is specified. + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + // Manually check for flags. Can be passed through cargo with -- e.g. + // cargo run --release --example beep --features jack -- --jack + let host = if opt.jack { + cpal::host_from_id(cpal::available_hosts() + .into_iter() + .find(|id| *id == cpal::HostId::Jack) + .expect( + "make sure --features jack is specified. only works on OSes where jack is available", + )).expect("jack host unavailable") + } else { + cpal::default_host() + }; + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] let host = cpal::default_host(); - // Setup the default input device and stream with the default input config. - let device = host - .default_input_device() - .expect("Failed to get default input device"); - println!("Default input device: {}", device.name()?); + // Setup the input device and stream with the default input config. + let device = if opt.device == "default" { + host.default_input_device() + } else { + host.input_devices()? + .find(|x| x.name().map(|y| y == opt.device).unwrap_or(false)) + } + .expect("failed to find input device"); + + println!("Input device: {}", device.name()?); + let config = device .default_input_config() .expect("Failed to get default input config"); println!("Default input config: {:?}", config); + // The WAV file we're recording to. const PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav"); let spec = wav_spec_from_config(&config); From e76e1de3a3ded101a011677c8d206aa6587c5e47 Mon Sep 17 00:00:00 2001 From: Alex Moon Date: Tue, 22 Dec 2020 09:25:36 -0700 Subject: [PATCH 2/2] Switch from `structopt` to `clap` to reduce dependencies. --- Cargo.toml | 10 +------ examples/beep.rs | 36 ++++++++++++++++++++---- examples/feedback.rs | 63 ++++++++++++++++++++++++++++++++++-------- examples/record_wav.rs | 36 ++++++++++++++++++++---- 4 files changed, 112 insertions(+), 33 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f7ce079..0e8f68c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ thiserror = "1.0.2" anyhow = "1.0.12" hound = "3.4" ringbuf = "0.2" -structopt = "0.3.21" +clap = { version = "2.33.3", default-features = false } [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3", features = ["audiosessiontypes", "audioclient", "coml2api", "combaseapi", "debug", "devpkey", "handleapi", "ksmedia", "mmdeviceapi", "objbase", "profileapi", "std", "synchapi", "winbase", "winuser"] } @@ -60,20 +60,12 @@ crate-type = ["cdylib"] [[example]] name = "beep" -path = "examples/beep.rs" -crate-type = ["bin"] [[example]] name = "enumerate" -path = "examples/enumerate.rs" -crate-type = ["bin"] [[example]] name = "feedback" -path = "examples/feedback.rs" -crate-type = ["bin"] [[example]] name = "record_wav" -path = "examples/record_wav.rs" -crate-type = ["bin"] diff --git a/examples/beep.rs b/examples/beep.rs index 80920fd..ed15204 100644 --- a/examples/beep.rs +++ b/examples/beep.rs @@ -1,24 +1,48 @@ extern crate anyhow; +extern crate clap; extern crate cpal; -extern crate structopt; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] -#[structopt(name = "beep", about = "Simple example of audio playback.")] +#[derive(Debug)] struct Opt { #[cfg(all( any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), feature = "jack" ))] - #[structopt(short, long)] jack: bool, - #[structopt(default_value = "default")] device: String, } +impl Opt { + fn from_args() -> Self { + let app = clap::App::new("beep").arg_from_usage("[DEVICE] 'The audio device to use'"); + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + let app = app.arg_from_usage("-j, --jack 'Use the JACK host"); + let matches = app.get_matches(); + let device = matches.value_of("DEVICE").unwrap_or("default").to_string(); + + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + return Opt { + jack: matches.is_present("jack"), + device, + }; + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] + Opt { device } + } +} + fn main() -> anyhow::Result<()> { let opt = Opt::from_args(); diff --git a/examples/feedback.rs b/examples/feedback.rs index cb4cac5..f0656b6 100644 --- a/examples/feedback.rs +++ b/examples/feedback.rs @@ -7,36 +7,75 @@ //! precisely synchronised. extern crate anyhow; +extern crate clap; extern crate cpal; extern crate ringbuf; -extern crate structopt; +use anyhow::Context; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use ringbuf::RingBuffer; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] -#[structopt(name = "beep", about = "Simple example of audio playback.")] +#[derive(Debug)] struct Opt { #[cfg(all( any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), feature = "jack" ))] - #[structopt(short, long)] jack: bool, - #[structopt(short, long, default_value = "150.0")] latency: f32, - - #[structopt(default_value = "default")] input_device: String, - - #[structopt(default_value = "default")] output_device: String, } -fn main() -> Result<(), anyhow::Error> { - let opt = Opt::from_args(); +impl Opt { + fn from_args() -> anyhow::Result { + let app = clap::App::new("beep") + .arg_from_usage( + "-l, --latency [DELAY_MS] 'Specify the delay between input and output [default: 150]'", + ) + .arg_from_usage("[IN] 'The input audio device to use'") + .arg_from_usage("[OUT] 'The output audio device to use'"); + + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + let app = app.arg_from_usage("-j, --jack 'Use the JACK host"); + let matches = app.get_matches(); + let latency: f32 = matches + .value_of("latency") + .unwrap_or("150") + .parse() + .context("parsing latency option")?; + let input_device = matches.value_of("IN").unwrap_or("default").to_string(); + let output_device = matches.value_of("OUT").unwrap_or("default").to_string(); + + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + return Ok(Opt { + jack: matches.is_present("jack"), + latency, + input_device, + output_device, + }); + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] + Ok(Opt { + latency, + input_device, + output_device, + }) + } +} + +fn main() -> anyhow::Result<()> { + let opt = Opt::from_args()?; // Conditionally compile with jack if the feature is specified. #[cfg(all( diff --git a/examples/record_wav.rs b/examples/record_wav.rs index e4c9090..7746f56 100644 --- a/examples/record_wav.rs +++ b/examples/record_wav.rs @@ -3,30 +3,54 @@ //! The input data is recorded to "$CARGO_MANIFEST_DIR/recorded.wav". extern crate anyhow; +extern crate clap; extern crate cpal; extern crate hound; -extern crate structopt; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use std::fs::File; use std::io::BufWriter; use std::sync::{Arc, Mutex}; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] -#[structopt(name = "beep", about = "Simple example of audio playback.")] +#[derive(Debug)] struct Opt { #[cfg(all( any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), feature = "jack" ))] - #[structopt(short, long)] jack: bool, - #[structopt(default_value = "default")] device: String, } +impl Opt { + fn from_args() -> Self { + let app = clap::App::new("beep").arg_from_usage("[DEVICE] 'The audio device to use'"); + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + let app = app.arg_from_usage("-j, --jack 'Use the JACK host"); + let matches = app.get_matches(); + let device = matches.value_of("DEVICE").unwrap_or("default").to_string(); + + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + return Opt { + jack: matches.is_present("jack"), + device, + }; + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] + Opt { device } + } +} + fn main() -> Result<(), anyhow::Error> { let opt = Opt::from_args();