Skip to content
Merged
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
221 changes: 190 additions & 31 deletions Engine/crates/engine-play/src/audio_output.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,211 @@
//! Device output is isolated from the scene and script locks.
//! Native device handles and streams stay on the audio thread, outside scene locks.
#[derive(Default)]
pub(crate) struct AudioOutput {
#[cfg(windows)]
sender: Option<std::sync::mpsc::SyncSender<Vec<f32>>>,
sender: Option<std::sync::mpsc::SyncSender<Command>>,
}

#[cfg(windows)]
#[cfg_attr(test, allow(dead_code))]
enum Command {
Samples(Vec<f32>),
Devices {
input: bool,
reply: std::sync::mpsc::Sender<Result<serde_json::Value, String>>,
},
Select {
input: bool,
id: Option<String>,
reply: std::sync::mpsc::Sender<Result<serde_json::Value, String>>,
},
}

impl AudioOutput {
pub fn new() -> Self {
// Unit tests exercise the mixer without opening native audio devices.
// Hosted Windows runners have no reliable playback device, and parallel
// scene fixtures must not initialize device drivers for each test.
// Tests must not initialize native device drivers for each scene fixture.
#[cfg(all(windows, not(test)))]
{
let (sender, receiver) = std::sync::mpsc::sync_channel::<Vec<f32>>(4);
let _ = std::thread::Builder::new()
let (sender, receiver) = std::sync::mpsc::sync_channel(8);
if std::thread::Builder::new()
.name("rustic-audio".into())
.spawn(move || {
let Ok(stream) = rodio::OutputStreamBuilder::open_default_stream() else {
return;
};
let sink = rodio::Sink::connect_new(stream.mixer());
while let Ok(samples) = receiver.recv() {
if !samples.is_empty() && sink.len() < 4 {
sink.append(rodio::buffer::SamplesBuffer::new(2, 48_000, samples));
}
}
});
Self {
sender: Some(sender),
.spawn(move || native::run(&receiver))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Build the required Windows installer

This new Windows-only audio path has not completed the repository-required packaging validation: the commit’s validation notes explicitly leave the installer build pending in CI. Before treating the feature as complete, run tools/build-windows-installer.ps1 and confirm that it produces a fresh dist\RusticGameEngine-Setup-*.exe; otherwise failures in the Windows integration or installer packaging remain unverified.

AGENTS.md reference: Engine/AGENTS.md:L3-L9

Useful? React with 👍 / 👎.

.is_ok()
{
return Self {
sender: Some(sender),
};
}
}
#[cfg(any(not(windows), test))]
{
Self::default()
Self::default()
}

#[allow(clippy::unused_self)]
#[cfg_attr(not(windows), allow(clippy::unnecessary_wraps))]
pub fn devices(&self, input: bool) -> Result<serde_json::Value, String> {
#[cfg(windows)]
if self.sender.is_some() {
return self.request(|reply| Command::Devices { input, reply });
}
let _ = input;
Ok(serde_json::json!([]))
}

#[allow(clippy::unused_self)]
pub fn select(&self, input: bool, id: Option<&str>) -> Result<(), String> {
#[cfg(windows)]
if self.sender.is_some() {
self.request(|reply| Command::Select {
input,
id: id.map(str::to_owned),
reply,
})?;
return Ok(());
}
let _ = (input, id);
Err("native audio device selection is unavailable on this host".into())
}

#[cfg(windows)]
fn request(
&self,
command: impl FnOnce(std::sync::mpsc::Sender<Result<serde_json::Value, String>>) -> Command,
) -> Result<serde_json::Value, String> {
let (reply, response) = std::sync::mpsc::channel();
self.sender
.as_ref()
.ok_or("audio worker unavailable")?
.try_send(command(reply))
.map_err(|e| format!("audio worker unavailable or busy: {e}"))?;
response
.recv()
.map_err(|e| format!("audio worker stopped: {e}"))?
}
#[cfg_attr(
not(windows),
allow(
clippy::unused_self,
reason = "the Windows audio backend retains instance state; other hosts consume samples without output"
)
)]

#[allow(clippy::unused_self)]
pub fn submit(&self, samples: Vec<f32>) {
#[cfg(windows)]
if let Some(sender) = &self.sender {
let _ = sender.try_send(samples);
let _ = sender.try_send(Command::Samples(samples));
}
#[cfg(not(windows))]
drop(samples);
}
}

#[cfg(all(windows, not(test)))]
mod native {
use super::Command;
use rodio::cpal::{
Device, Host,
traits::{DeviceTrait, HostTrait},
};
use std::collections::BTreeMap;

struct NativeAudio {
host: Host,
output: Option<(rodio::OutputStream, rodio::Sink)>,
input: Option<Device>,
outputs: BTreeMap<String, Device>,
inputs: BTreeMap<String, Device>,
serial: u64,
}

fn open(device: Device) -> Result<(rodio::OutputStream, rodio::Sink), String> {
let stream = rodio::OutputStreamBuilder::from_device(device)
.map_err(|e| e.to_string())?
.open_stream()
.map_err(|e| e.to_string())?;
let sink = rodio::Sink::connect_new(stream.mixer());
Ok((stream, sink))
}

impl NativeAudio {
fn new() -> Self {
let host = rodio::cpal::default_host();
let output = host.default_output_device().and_then(|d| open(d).ok());
Self {
host,
output,
input: None,
outputs: BTreeMap::new(),
inputs: BTreeMap::new(),
serial: 0,
}
}

fn devices(&mut self, input: bool) -> Result<serde_json::Value, String> {
let devices = if input {
self.host.input_devices()
} else {
self.host.output_devices()
}
.map_err(|e| e.to_string())?;
let mut cache = BTreeMap::new();
let mut list = Vec::new();
for device in devices {
let name = device.name().map_err(|e| e.to_string())?;
self.serial += 1;
let direction = if input { "input" } else { "output" };
let id = format!("{direction}:{}", self.serial);
list.push(serde_json::json!({"id":id,"name":name}));
cache.insert(id, device);
}
if input {
self.inputs = cache;
} else {
self.outputs = cache;
}
Ok(serde_json::json!(list))
}

fn select(&mut self, input: bool, id: Option<&str>) -> Result<serde_json::Value, String> {
let device = if let Some(id) = id {
let cache = if input { &self.inputs } else { &self.outputs };
cache
.get(id)
.cloned()
.ok_or("unknown audio device ID; list devices again")?
} else {
(if input {
self.host.default_input_device()
} else {
self.host.default_output_device()
})
.ok_or("no default audio device available")?
};
if input {
device.default_input_config().map_err(|e| e.to_string())?;
self.input = Some(device);
} else {
// Open first: failure preserves the current stream and voices.
let replacement = open(device)?;
self.output = Some(replacement);
}
Ok(serde_json::Value::Null)
}

fn submit(&self, samples: Vec<f32>) {
if let Some((_, sink)) = &self.output
&& !samples.is_empty()
&& sink.len() < 4
{
sink.append(rodio::buffer::SamplesBuffer::new(2, 48_000, samples));
}
}
}

pub(super) fn run(receiver: &std::sync::mpsc::Receiver<Command>) {
let mut audio = NativeAudio::new();
while let Ok(command) = receiver.recv() {
match command {
Command::Samples(samples) => audio.submit(samples),
Command::Devices { input, reply } => {
let _ = reply.send(audio.devices(input));
}
Command::Select { input, id, reply } => {
let _ = reply.send(audio.select(input, id.as_deref()));
}
}
}
}
}
48 changes: 48 additions & 0 deletions Engine/crates/engine-play/src/script_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,6 +1096,27 @@ impl GameplayHost for RuntimeHost {
}
if op.starts_with("audio_") {
let mut context = self.gameplay.lock().map_err(|_| "gameplay lock poisoned")?;
match op {
"audio_get_output_devices" | "audio_get_input_devices" => {
return context
.audio_output
.devices(op == "audio_get_input_devices");
}
"audio_set_output_device" | "audio_set_input_device" => {
let device = query.get("device").filter(|v| !v.is_null());
let id = device
.map(|v| {
v.as_str()
.ok_or("audio device must be an ID string or null")
})
.transpose()?;
context
.audio_output
.select(op == "audio_set_input_device", id)?;
return Ok(serde_json::Value::Null);
}
_ => {}
}
let owner = Owner {
entity_bound: self.entity_bound,
scene: context.scene,
Expand Down Expand Up @@ -2528,6 +2549,33 @@ mod tests {
}
}

#[test]
fn audio_device_queries_validate_ids_and_report_headless_hosts() {
let world = Arc::new(Mutex::new(SceneWorld::new()));
let mut host = environment_host(&world);
for direction in ["input", "output"] {
assert_eq!(
host.gameplay_query(
serde_json::json!({"op":format!("audio_get_{direction}_devices")})
)
.unwrap(),
serde_json::json!([])
);
for invalid in [
serde_json::json!(42),
serde_json::json!({"id":"device"}),
serde_json::json!([]),
] {
let error = host.gameplay_query(serde_json::json!({"op":format!("audio_set_{direction}_device"),"device":invalid})).unwrap_err();
assert!(error.contains("ID string or null"), "{error}");
}
for id in [serde_json::Value::Null, serde_json::json!("missing")] {
let error = host.gameplay_query(serde_json::json!({"op":format!("audio_set_{direction}_device"),"device":id})).unwrap_err();
assert!(error.contains("unavailable"), "{error}");
}
}
}

#[test]
fn environment_patches_validate_atomically_and_preserve_other_settings() {
let world = Arc::new(Mutex::new(SceneWorld::new()));
Expand Down
4 changes: 4 additions & 0 deletions Engine/crates/engine-scripting/src/cpp_sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,10 @@ inline auto followSpeed(const std::string&e,const Curve&path,double speed,const
}
namespace Timer{inline auto every(double interval,std::function<void()> fn,std::optional<int> count={}){if(interval<=0||(count&&*count<1))throw std::invalid_argument("positive interval/count required");auto token=Gameplay::callback([fn=std::move(fn)](auto&){fn();});return Gameplay::start(rustic_detail::object({{"kind","sequence"},{"actions",RusticValue::Array{rustic_detail::object({{"kind","wait"},{"duration",interval}}),rustic_detail::object({{"kind","callback"},{"token",token}})}}}),!count,count?*count-1:0);}}
namespace Audio{
inline RusticValue get_output_devices(){return rustic.query(rustic_detail::object({{"op","audio_get_output_devices"}}));}
inline RusticValue get_input_devices(){return rustic.query(rustic_detail::object({{"op","audio_get_input_devices"}}));}
inline void set_output_device(const RusticValue& device=nullptr){rustic.query(rustic_detail::object({{"op","audio_set_output_device"},{"device",device}}));}
inline void set_input_device(const RusticValue& device=nullptr){rustic.query(rustic_detail::object({{"op","audio_set_input_device"},{"device",device}}));}
struct Voice{std::string id;void stop(){rustic.query(rustic_detail::object({{"op","audio_stop"},{"entity",id}}));}void pause(){rustic.query(rustic_detail::object({{"op","audio_pause"},{"entity",id}}));}void resume(){rustic.query(rustic_detail::object({{"op","audio_resume"},{"entity",id}}));}};
inline Voice play(const std::string&source,double volume=1,double pitch=1,bool loop=false){return {rustic.query(rustic_detail::object({{"op","audio_play"},{"source",source},{"volume",volume},{"pitch",pitch},{"loop",loop}})).string()};}
inline Voice playAt(const std::string&source,RusticVector3 position,double volume=1,double pitch=1,bool loop=false){return {rustic.query(rustic_detail::object({{"op","audio_play"},{"source",source},{"position",Physics::vec(position)},{"volume",volume},{"pitch",pitch},{"loop",loop}})).string()};}
Expand Down
Loading
Loading