diff --git a/Cargo.lock b/Cargo.lock index 06fef501..c4bc7be0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7419,6 +7419,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424" dependencies = [ "lazy_static", + "symphonia-bundle-flac", "symphonia-codec-pcm", "symphonia-codec-vorbis", "symphonia-core", @@ -7427,6 +7428,18 @@ dependencies = [ "symphonia-metadata", ] +[[package]] +name = "symphonia-bundle-flac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6405d5c34ff6f8f7ca08a4101efe66d21e180f7322ef9359900a0e55698a7892" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "symphonia-codec-pcm" version = "0.6.1" diff --git a/assets/audio/pluck.wav b/assets/audio/pluck.wav new file mode 100644 index 00000000..f3cad683 Binary files /dev/null and b/assets/audio/pluck.wav differ diff --git a/crates/processing_audio/Cargo.toml b/crates/processing_audio/Cargo.toml index 48ad5a4a..9efbb0e0 100644 --- a/crates/processing_audio/Cargo.toml +++ b/crates/processing_audio/Cargo.toml @@ -9,6 +9,7 @@ bevy = { workspace = true } processing_core = { workspace = true } bevy_seedling = { git = "https://github.com/catilac/bevy_seedling", branch = "processing-dev", features = [ "effects", + "flac", ] } [dev-dependencies] diff --git a/crates/processing_audio/src/lib.rs b/crates/processing_audio/src/lib.rs index 3642889c..a6bf6ec6 100644 --- a/crates/processing_audio/src/lib.rs +++ b/crates/processing_audio/src/lib.rs @@ -24,6 +24,8 @@ //! `(source_port, destination_port)` pairs. There is no implicit //! up/down-mixing, limiter, DC blocking or input gate anywhere, so //! DC-coupled CV passes through untouched. +//! - **Samples.** [`audio_sample_load`], [`audio_sampler_create`] and +//! [`audio_sample_play`]; each sampler has its own outputs to route. //! //! Graph changes are applied on the next frame update; device changes apply //! immediately. @@ -34,6 +36,8 @@ use bevy::prelude::*; mod device; #[cfg(not(target_arch = "wasm32"))] mod graph; +#[cfg(not(target_arch = "wasm32"))] +mod sample; #[cfg(not(target_arch = "wasm32"))] pub use native::*; @@ -67,6 +71,7 @@ impl Plugin for AudioPlugin { #[cfg(not(target_arch = "wasm32"))] mod native { + use std::path::PathBuf; use std::time::Duration; use bevy::prelude::*; @@ -83,7 +88,7 @@ mod native { pub use crate::graph::{AudioNodeKind, AudioPorts}; use crate::device::{self, AudioDeviceState}; - use crate::graph; + use crate::{graph, sample}; /// What opens the stream at startup. #[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)] @@ -123,7 +128,8 @@ mod native { // Send parameter changes every update, not every 10 ms. .insert_resource(DiffRate(Duration::ZERO)) .insert_resource(state) - .insert_resource(backend); + .insert_resource(backend) + .init_resource::(); // We open and manage the stream ourselves (see `device`). app.add_plugins(SeedlingPlugins.build().disable::()); @@ -313,6 +319,31 @@ mod native { pub fn audio_disconnect(src: Entity, dst: Entity, ports: &[(u32, u32)]) -> Result<()> { with_audio(|world| graph::disconnect(In((src, dst, ports.to_vec())), world)) } + + // --- samples --- + + /// Load and decode a sound file (wav, ogg, flac), blocking until it is + /// ready. + pub fn audio_sample_load(path: impl Into) -> Result { + let path = path.into(); + with_audio(|world| sample::sample_load(In(path), world)) + } + + /// Create a sampler with `channels` outputs that plays up to `voices` + /// samples at once. Connect its outputs like any node. + pub fn audio_sampler_create(channels: u32, voices: usize) -> Result { + with_audio(|world| sample::sampler_create(In((channels, voices)), world)) + } + + /// Play a sample on a sampler at linear `volume`. Returns the playback. + pub fn audio_sample_play(sampler: Entity, sample: Entity, volume: f32) -> Result { + with_audio(|world| sample::sample_play(In((sampler, sample, volume)), world)) + } + + /// Stop a playback early. + pub fn audio_sample_stop(playback: Entity) -> Result<()> { + with_audio(|world| sample::sample_stop(In(playback), world)) + } } #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/processing_audio/src/sample.rs b/crates/processing_audio/src/sample.rs new file mode 100644 index 00000000..47c6f4db --- /dev/null +++ b/crates/processing_audio/src/sample.rs @@ -0,0 +1,130 @@ +//! Sample loading and playback. +//! +//! A *sampler* is a pool of voices with its own output, so each sampler can +//! be routed to any graph ports, e.g. one sampler per pair of synth inputs. + +use std::path::PathBuf; + +use bevy::asset::{AssetPath, LoadState, handle_internal_asset_events, io::AssetSourceId}; +use bevy::ecs::system::RunSystemOnce; +use bevy::prelude::*; +use bevy_seedling::prelude::*; + +use processing_core::config::{Config, ConfigKey}; +use processing_core::error::{ProcessingError, Result}; + +use crate::graph::AudioPorts; + +/// A loaded audio file. +#[derive(Component, Clone)] +pub struct AudioSampleHandle(pub Handle); + +/// Each sampler is its own seedling pool, told apart by this label's value. +#[derive(PoolLabel, Debug, Clone, PartialEq, Eq, Hash)] +struct SketchPool(u64); + +#[derive(Component, Clone, Copy)] +struct Sampler(u64); + +#[derive(Resource, Default)] +pub(crate) struct NextSamplerId(u64); + +/// Load a sample, blocking until it is decoded. Relative paths resolve +/// against the sketch's asset folder when one is configured. +pub(crate) fn sample_load(In(path): In, world: &mut World) -> Result { + let has_root = world + .get_resource::() + .is_some_and(|c| c.get(ConfigKey::AssetRootPath).is_some()); + let asset_path = if has_root { + AssetPath::from_path_buf(path).with_source(AssetSourceId::from("assets_directory")) + } else { + AssetPath::from_path_buf(path) + }; + + let handle: Handle = world.resource::().load(asset_path); + loop { + match world.resource::().load_state(&handle) { + LoadState::Loaded => break, + LoadState::Failed(err) => { + return Err(ProcessingError::AudioSampleLoad(err.to_string())); + } + _ => { + world + .run_system_once(handle_internal_asset_events) + .map_err(|e| ProcessingError::AudioSampleLoad(e.to_string()))?; + } + } + } + Ok(world.spawn(AudioSampleHandle(handle)).id()) +} + +/// Create a sampler with `channels` outputs and up to `voices` samples +/// playing at once. Its outputs start unconnected. +pub(crate) fn sampler_create( + In((channels, voices)): In<(u32, usize)>, + world: &mut World, +) -> Result { + let ch = NonZeroChannelCount::new(channels) + .filter(|_| channels <= 32) + .ok_or_else(|| { + ProcessingError::InvalidArgument(format!( + "samplers have 1 to 32 channels, got {channels}" + )) + })?; + let voices = voices.max(1); + let id = { + let mut next = world.get_resource_or_init::(); + next.0 += 1; + next.0 + }; + let entity = world + .spawn(( + SamplerPool(SketchPool(id)), + SamplerConfig { + channels: ch, + ..default() + }, + // The pool's output bus; must match the voices' width. + VolumeNodeConfig { channels: ch }, + PoolSize(voices..=voices), + ChannelMapping::Discrete, + // Only edges the sketch makes exist; nothing is routed to `MainBus`. + NoAutoConnect, + AudioPorts { + inputs: 0, + outputs: channels, + }, + Sampler(id), + )) + .id(); + Ok(entity) +} + +/// Play a loaded sample on a sampler. Returns the playback, which removes +/// itself when the sample ends. +pub(crate) fn sample_play( + In((sampler, sample, volume)): In<(Entity, Entity, f32)>, + world: &mut World, +) -> Result { + let Sampler(id) = *world + .get::(sampler) + .ok_or(ProcessingError::AudioNodeNotFound)?; + let handle = world + .get::(sample) + .ok_or_else(|| ProcessingError::InvalidArgument("not an audio sample".into()))? + .0 + .clone(); + let player = SamplePlayer { + volume: Volume::Linear(volume), + ..SamplePlayer::new(handle) + }; + Ok(world.spawn((SketchPool(id), player)).id()) +} + +/// Stop a playback. Stopping one that already finished is not an error. +pub(crate) fn sample_stop(In(playback): In, world: &mut World) -> Result<()> { + if world.get::(playback).is_some() { + world.despawn(playback); + } + Ok(()) +} diff --git a/crates/processing_audio/src/tests.rs b/crates/processing_audio/src/tests.rs index 7bce6f83..f80d7068 100644 --- a/crates/processing_audio/src/tests.rs +++ b/crates/processing_audio/src/tests.rs @@ -18,6 +18,7 @@ use processing_core::config::{Config, ConfigKey}; use crate::device::{self, AudioDeviceState, AudioStatus}; use crate::graph::{self, AudioNodeKind, AudioPorts}; use crate::native::{self, AudioBackend}; +use crate::sample; const MOCK_RATE: NonZeroU32 = NonZeroU32::new(48_000).unwrap(); const MOCK_CHANNELS: usize = 2; @@ -237,6 +238,65 @@ fn set_param_by_name() { ); } +#[test] +fn samplers_are_separate_pools_with_their_own_outputs() { + let mut app = test_app(8); + let world = app.world_mut(); + let output = graph::graph_output(world).unwrap(); + let a = sample::sampler_create(In((1, 2)), world).unwrap(); + let b = sample::sampler_create(In((2, 2)), world).unwrap(); + graph::connect(In((a, output, vec![(0, 6)])), world).unwrap(); + graph::connect(In((b, output, vec![(0, 0), (1, 1)])), world).unwrap(); + app.update(); + app.update(); + + let (na, nb, o) = (node_id(&app, a), node_id(&app, b), node_id(&app, output)); + assert_ne!(na, nb); + let to_output: Vec<_> = edges(&mut app).into_iter().filter(|e| e.2 == o).collect(); + assert_eq!(to_output, vec![(nb, 0, o, 0), (na, 0, o, 6), (nb, 1, o, 1)]); +} + +#[test] +fn sample_plays_through_a_sampler_to_completion() { + let mut app = test_app(2); + let world = app.world_mut(); + let output = graph::graph_output(world).unwrap(); + let pluck = sample::sample_load(In("audio/pluck.wav".into()), world).unwrap(); + let sampler = sample::sampler_create(In((2, 2)), world).unwrap(); + graph::connect(In((sampler, output, vec![(0, 0), (1, 1)])), world).unwrap(); + app.update(); + + let world = app.world_mut(); + let playback = sample::sample_play(In((sampler, pluck, 0.8)), world).unwrap(); + + // a voice picks it up... + let mut assigned = false; + for _ in 0..50 { + app.update(); + if app + .world() + .get::(playback) + .is_some() + { + assigned = true; + break; + } + } + assert!(assigned, "no sampler voice took the sample"); + + // ...and the audio thread plays it to the end (0.8 s), which despawns it + let began = std::time::Instant::now(); + while app.world().get_entity(playback).is_ok() { + assert!( + began.elapsed() < std::time::Duration::from_secs(5), + "playback never finished" + ); + app.update(); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(began.elapsed() > std::time::Duration::from_millis(500)); +} + #[test] fn unwired_nodes_are_not_auto_connected() { let mut app = test_app(2); @@ -249,12 +309,16 @@ fn unwired_nodes_are_not_auto_connected() { world.commands().entity(bus).connect(output); world.flush(); let noise = graph::node_create(In((AudioNodeKind::WhiteNoise, 1)), world).unwrap(); + let sampler = sample::sampler_create(In((2, 1)), world).unwrap(); for _ in 0..3 { app.update(); } - let n = node_id(&app, noise); - let leaks: Vec<_> = edges(&mut app).into_iter().filter(|e| e.0 == n).collect(); + let (n, s) = (node_id(&app, noise), node_id(&app, sampler)); + let leaks: Vec<_> = edges(&mut app) + .into_iter() + .filter(|e| e.0 == n || e.0 == s) + .collect(); assert!(leaks.is_empty(), "unwired nodes got edges: {leaks:?}"); } diff --git a/crates/processing_core/src/error.rs b/crates/processing_core/src/error.rs index e626cc6f..5de0e093 100644 --- a/crates/processing_core/src/error.rs +++ b/crates/processing_core/src/error.rs @@ -96,4 +96,6 @@ pub enum ProcessingError { }, #[error("Audio node has no parameter {0:?}")] AudioParamNotFound(String), + #[error("Audio sample load error: {0}")] + AudioSampleLoad(String), } diff --git a/src/prelude.rs b/src/prelude.rs index 8540f7b0..8f39da70 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -8,7 +8,8 @@ pub use processing_audio::{ audio_connect_channel, audio_disconnect, audio_events, audio_info, audio_input, audio_list_input_devices, audio_list_output_devices, audio_node_create, audio_node_destroy, audio_node_get, audio_node_ports, audio_node_set, audio_node_set_variant, audio_output, - audio_restart, audio_set_block_frames, audio_set_input_device, audio_set_input_device_index, + audio_restart, audio_sample_load, audio_sample_play, audio_sample_stop, audio_sampler_create, + audio_set_block_frames, audio_set_input_device, audio_set_input_device_index, audio_set_output_device, audio_set_output_device_index, audio_set_sample_rate, audio_status, parse_device, };