Skip to content
Open
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
27 changes: 25 additions & 2 deletions crates/processing_audio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,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 @@ -38,6 +40,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 @@ -54,7 +57,7 @@ mod native {
pub use crate::graph::{AudioNodeKind, AudioPorts};

use crate::device::{self, AudioDeviceState};
use crate::graph;
use crate::{graph, sample};

#[derive(Resource, Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AudioBackend {
Expand Down Expand Up @@ -84,7 +87,8 @@ mod native {
.insert_resource(context_config)
.insert_resource(DiffRate(Duration::ZERO))
.insert_resource(state)
.insert_resource(backend);
.insert_resource(backend)
.init_resource::<sample::NextSamplerId>();

// stream is managed in `device`
app.add_plugins(SeedlingPlugins.build().disable::<CpalPlatformPlugin>());
Expand Down Expand Up @@ -254,6 +258,25 @@ 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 ---

pub fn audio_sample_load(path: impl Into<PathBuf>) -> Result<Entity> {
let path = path.into();
with_audio(|world| sample::sample_load(In(path), world))
}

pub fn audio_sampler_create(channels: u32, voices: usize) -> Result<Entity> {
with_audio(|world| sample::sampler_create(In((channels, voices)), world))
}

pub fn audio_sample_play(sampler: Entity, sample: Entity, volume: f32) -> Result<Entity> {
with_audio(|world| sample::sample_play(In((sampler, sample, volume)), world))
}

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
116 changes: 116 additions & 0 deletions crates/processing_audio/src/sample.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//! Sample loading and playback.

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;

#[derive(Component, Clone)]
pub struct AudioSampleHandle(pub Handle<AudioSample>);

#[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);

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())
}

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()
},
VolumeNodeConfig { channels: ch },
PoolSize(voices..=voices),
ChannelMapping::Discrete,
NoAutoConnect,
AudioPorts {
inputs: 0,
outputs: channels,
},
Sampler(id),
))
.id();
Ok(entity)
}

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())
}

pub(crate) fn sample_stop(In(playback): In<Entity>, world: &mut World) -> Result<()> {
if world.get::<SamplePlayer>(playback).is_some() {
world.despawn(playback);
}
Ok(())
}
66 changes: 64 additions & 2 deletions crates/processing_audio/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,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 @@ -225,6 +226,63 @@ 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();

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");

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 @@ -237,12 +295,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