Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added assets/audio/pluck.wav
Binary file not shown.
1 change: 1 addition & 0 deletions crates/processing_audio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
35 changes: 33 additions & 2 deletions crates/processing_audio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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::*;
Expand Down Expand Up @@ -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::*;
Expand All @@ -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)]
Expand Down Expand Up @@ -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::<sample::NextSamplerId>();

// We open and manage the stream ourselves (see `device`).
app.add_plugins(SeedlingPlugins.build().disable::<CpalPlatformPlugin>());
Expand Down Expand Up @@ -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<PathBuf>) -> Result<Entity> {
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<Entity> {
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<Entity> {
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")))]
Expand Down
130 changes: 130 additions & 0 deletions crates/processing_audio/src/sample.rs
Original file line number Diff line number Diff line change
@@ -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<AudioSample>);

/// 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<PathBuf>, world: &mut World) -> Result<Entity> {
let has_root = world
.get_resource::<Config>()
.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<AudioSample> = world.resource::<AssetServer>().load(asset_path);
loop {
match world.resource::<AssetServer>().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<Entity> {
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::<NextSamplerId>();
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<Entity> {
let Sampler(id) = *world
.get::<Sampler>(sampler)
.ok_or(ProcessingError::AudioNodeNotFound)?;
let handle = world
.get::<AudioSampleHandle>(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<Entity>, world: &mut World) -> Result<()> {
if world.get::<SamplePlayer>(playback).is_some() {
world.despawn(playback);
}
Ok(())
}
68 changes: 66 additions & 2 deletions crates/processing_audio/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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::<bevy_seedling::pool::Sampler>(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);
Expand All @@ -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:?}");
}

Expand Down
2 changes: 2 additions & 0 deletions crates/processing_core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,6 @@ pub enum ProcessingError {
},
#[error("Audio node has no parameter {0:?}")]
AudioParamNotFound(String),
#[error("Audio sample load error: {0}")]
AudioSampleLoad(String),
}
3 changes: 2 additions & 1 deletion src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
Loading