feat(audio): add guest voice controls and reliable lifecycle delivery
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

This commit is contained in:
2026-10-14 09:08:27 +01:00
parent 3899b7f12c
commit e0e01ed1de
23 changed files with 1442 additions and 482 deletions
+280 -168
View File
@@ -13,8 +13,7 @@ use prometeu_hal::sample::Sample;
/// State of a single playback voice (channel).
///
/// The Core maintains this state to provide information to the App (e.g., is_playing),
/// but the actual real-time mixing is performed by the Host using commands.
/// This state belongs exclusively to the mixer, which observes natural completion.
pub struct Channel {
/// The actual sample data being played.
pub sample: Option<Arc<Sample>>,
@@ -30,7 +29,7 @@ pub struct Channel {
pub pan: u8,
/// Loop configuration for this voice.
pub loop_mode: LoopMode,
/// Playback priority (used for voice stealing policies).
/// Internal priority metadata; the guest explicitly selects its voice.
pub priority: u8,
}
@@ -64,7 +63,7 @@ pub enum AudioCommand {
priority: u8,
loop_mode: LoopMode,
},
/// Immediately stop playback on a voice.
/// Stop playback on a voice when this command is applied.
Stop { voice_id: usize },
/// Update volume of an ongoing playback.
SetVolume { voice_id: usize, volume: u8 },
@@ -72,36 +71,65 @@ pub enum AudioCommand {
SetPan { voice_id: usize, pan: u8 },
/// Update pitch of an ongoing playback.
SetPitch { voice_id: usize, pitch: f64 },
/// Pause all audio processing.
MasterPause,
/// Resume audio processing.
MasterResume,
}
/// PROMETEU Audio Subsystem.
///
/// Models a multi-channel PCM sampler (SPU).
/// The audio system in Prometeu is **command-based**. This means the Core
/// doesn't generate raw audio samples; instead, it sends high-level commands
/// (like `Play`, `Stop`, `SetVolume`) to a queue. The physical host backend
/// (e.g., CPAL on desktop) then consumes these commands and performs the
/// actual mixing at the native hardware sample rate.
///
/// ### Key Features:
/// - **16 Simultaneous Voices**: Independent volume, pan, and pitch.
/// - **Sample-based Synthesis**: Plays PCM data stored in SoundBanks.
/// - **Stereo Output**: 48kHz output target.
mod transport;
pub use transport::{AudioDelivery, AudioTransport};
pub const MAX_COMMANDS_PER_FRAME: usize = 1024;
/// Bounded producer staging. Samples belong to staged/published commands and the
/// mixer, never to a second playback mirror that cannot observe completion.
pub struct Audio {
/// Local state of the hardware voices. This state is used for logic
/// (e.g., checking if a sound is still playing) and is synchronized with the Host.
pub voices: [Channel; MAX_CHANNELS],
/// Queue of pending commands to be processed by the Host mixer.
/// This queue is typically flushed and sent to the Host once per frame.
pub commands: Vec<AudioCommand>,
/// Interface to access sound memory banks (ARAM).
commands: Vec<AudioCommand>,
/// Admission survives an early lifecycle flush of the interrupted frame.
frame_commands_admitted: usize,
lifecycle_commands: Vec<AudioCommand>,
in_lifecycle: bool,
session: Option<u32>,
transport: AudioTransport,
pub sound_banks: Arc<dyn SoundBankPoolAccess>,
}
impl Audio {
pub fn new(sound_banks: Arc<dyn SoundBankPoolAccess>) -> Self {
Self {
commands: Vec::new(),
frame_commands_admitted: 0,
lifecycle_commands: Vec::new(),
in_lifecycle: false,
session: None,
transport: AudioTransport::default(),
sound_banks,
}
}
pub fn transport(&self) -> AudioTransport {
self.transport.clone()
}
fn enqueue(&mut self, voice: usize, command: AudioCommand) -> AudioOpStatus {
if voice >= MAX_CHANNELS {
return AudioOpStatus::VoiceInvalid;
}
let admitted = if self.in_lifecycle {
self.lifecycle_commands.len()
} else {
self.frame_commands_admitted
};
if admitted >= MAX_COMMANDS_PER_FRAME {
return AudioOpStatus::CommandLimit;
}
if self.in_lifecycle {
self.lifecycle_commands.push(command);
} else {
self.commands.push(command);
self.frame_commands_admitted += 1;
}
AudioOpStatus::Ok
}
}
impl AudioBridge for Audio {
fn play(
&mut self,
@@ -112,14 +140,23 @@ impl AudioBridge for Audio {
pan: u8,
pitch: f64,
priority: u8,
loop_mode: prometeu_hal::LoopMode,
loop_mode: LoopMode,
) -> AudioOpStatus {
let lm = match loop_mode {
prometeu_hal::LoopMode::Off => LoopMode::Off,
prometeu_hal::LoopMode::On => LoopMode::On,
if voice_id >= MAX_CHANNELS {
return AudioOpStatus::VoiceInvalid;
}
if !pitch.is_finite() || pitch <= 0.0 {
return AudioOpStatus::ArgRangeInvalid;
}
let Some(bank) = self.sound_banks.sound_bank_slot(bank_id as usize) else {
return AudioOpStatus::BankInvalid;
};
self.play(bank_id, sample_id, voice_id, volume, pan, pitch, priority, lm)
let Some(sample) = bank.samples.get(sample_id as usize).cloned() else {
return AudioOpStatus::SampleNotFound;
};
self.play_sample(sample, voice_id, volume, pan, pitch, priority, loop_mode)
}
fn play_sample(
&mut self,
sample: Arc<Sample>,
@@ -128,156 +165,84 @@ impl AudioBridge for Audio {
pan: u8,
pitch: f64,
priority: u8,
loop_mode: prometeu_hal::LoopMode,
) -> AudioOpStatus {
let lm = match loop_mode {
prometeu_hal::LoopMode::Off => LoopMode::Off,
prometeu_hal::LoopMode::On => LoopMode::On,
};
self.play_sample(sample, voice_id, volume, pan, pitch, priority, lm)
}
fn stop(&mut self, voice_id: usize) {
self.stop(voice_id)
}
fn set_volume(&mut self, voice_id: usize, volume: u8) {
self.set_volume(voice_id, volume)
}
fn set_pan(&mut self, voice_id: usize, pan: u8) {
self.set_pan(voice_id, pan)
}
fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
self.set_pitch(voice_id, pitch)
}
fn is_playing(&self, voice_id: usize) -> bool {
self.is_playing(voice_id)
}
fn clear_commands(&mut self) {
self.clear_commands()
}
}
impl Audio {
/// Initializes the audio system with empty voices and sound bank access.
pub fn new(sound_banks: Arc<dyn SoundBankPoolAccess>) -> Self {
Self {
voices: std::array::from_fn(|_| Channel::default()),
commands: Vec::new(),
sound_banks,
}
}
#[allow(clippy::too_many_arguments)]
pub fn play(
&mut self,
bank_id: u8,
sample_id: u16,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
) -> AudioOpStatus {
if voice_id >= MAX_CHANNELS {
return AudioOpStatus::VoiceInvalid;
}
// Resolve the sample from the hardware pools
let bank_slot = self.sound_banks.sound_bank_slot(bank_id as usize);
if bank_slot.is_none() {
return AudioOpStatus::BankInvalid;
if !pitch.is_finite() || pitch <= 0.0 {
return AudioOpStatus::ArgRangeInvalid;
}
let sample =
bank_slot.and_then(|bank| bank.samples.get(sample_id as usize).map(Arc::clone));
if let Some(s) = sample {
// println!(
// "[Audio] Resolved sample from bank {} sample {}. Playing on voice {}.",
// bank_id, sample_id, voice_id
// );
self.play_sample(s, voice_id, volume, pan, pitch, priority, loop_mode)
} else {
AudioOpStatus::SampleNotFound
}
}
#[allow(clippy::too_many_arguments)]
pub fn play_sample(
&mut self,
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
) -> AudioOpStatus {
if voice_id >= MAX_CHANNELS {
return AudioOpStatus::VoiceInvalid;
}
// Update local state
self.voices[voice_id] = Channel {
sample: Some(Arc::clone(&sample)),
active: true,
pos: 0.0,
pitch,
volume,
pan,
loop_mode,
priority,
};
// Push command to the host
self.commands.push(AudioCommand::Play {
sample,
self.enqueue(
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
});
AudioOpStatus::Ok
AudioCommand::Play { sample, voice_id, volume, pan, pitch, priority, loop_mode },
)
}
pub fn stop(&mut self, voice_id: usize) {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].active = false;
self.voices[voice_id].sample = None;
self.commands.push(AudioCommand::Stop { voice_id });
fn stop(&mut self, voice_id: usize) -> AudioOpStatus {
self.enqueue(voice_id, AudioCommand::Stop { voice_id })
}
fn set_volume(&mut self, voice_id: usize, volume: u8) -> AudioOpStatus {
self.enqueue(voice_id, AudioCommand::SetVolume { voice_id, volume })
}
fn set_pan(&mut self, voice_id: usize, pan: u8) -> AudioOpStatus {
self.enqueue(voice_id, AudioCommand::SetPan { voice_id, pan })
}
fn set_pitch(&mut self, voice_id: usize, pitch: f64) -> AudioOpStatus {
if voice_id >= MAX_CHANNELS {
return AudioOpStatus::VoiceInvalid;
}
}
pub fn set_volume(&mut self, voice_id: usize, volume: u8) {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].volume = volume;
self.commands.push(AudioCommand::SetVolume { voice_id, volume });
if !pitch.is_finite() || pitch <= 0.0 {
return AudioOpStatus::ArgRangeInvalid;
}
self.enqueue(voice_id, AudioCommand::SetPitch { voice_id, pitch })
}
pub fn set_pan(&mut self, voice_id: usize, pan: u8) {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].pan = pan;
self.commands.push(AudioCommand::SetPan { voice_id, pan });
}
fn ready(&self) -> bool {
self.transport.ready()
}
pub fn set_pitch(&mut self, voice_id: usize, pitch: f64) {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].pitch = pitch;
self.commands.push(AudioCommand::SetPitch { voice_id, pitch });
}
fn begin_frame(&mut self) { /* Staging may already contain debugger steps. */
}
pub fn is_playing(&self, voice_id: usize) -> bool {
if voice_id < MAX_CHANNELS { self.voices[voice_id].active } else { false }
fn finish_frame(&mut self) {
self.transport.publish(std::mem::take(&mut self.commands), false);
self.frame_commands_admitted = 0;
}
/// Clears the command queue. The Host should consume this every frame.
pub fn clear_commands(&mut self) {
fn abort_frame(&mut self) {
self.commands.clear();
self.frame_commands_admitted = 0;
}
fn lifecycle_ready(&self) -> bool {
self.transport.lifecycle_ready()
}
fn begin_lifecycle(&mut self) {
self.in_lifecycle = true;
}
fn finish_lifecycle(&mut self, success: bool) {
self.in_lifecycle = false;
if success {
// Publish the earlier frame prefix first so a callback stop cannot
// be undone by an old play on resume. Do not replenish frame quota.
let mut commands = std::mem::take(&mut self.commands);
commands.append(&mut self.lifecycle_commands);
self.transport.publish(commands, true);
} else {
self.lifecycle_commands.clear();
self.abort_frame();
}
}
fn set_session(&mut self, session: Option<u32>) {
if self.session != session {
self.reset();
self.session = session;
}
}
fn reset(&mut self) {
self.abort_frame();
self.lifecycle_commands.clear();
self.in_lifecycle = false;
self.transport.reset();
}
fn set_paused(&mut self, paused: bool) {
self.transport.set_paused(paused);
}
}
@@ -326,7 +291,154 @@ mod tests {
let status = audio.play_sample(sample(), MAX_CHANNELS, 255, 128, 1.0, 0, LoopMode::Off);
assert_eq!(status, AudioOpStatus::VoiceInvalid);
assert!(!audio.voices.iter().any(|voice| voice.active));
assert!(audio.commands.is_empty());
}
}
#[cfg(test)]
mod control_tests {
use super::*;
use crate::MemoryBanks;
fn audio() -> Audio {
Audio::new(Arc::new(MemoryBanks::new()))
}
#[test]
fn quota_is_shared_and_rejections_never_publish_partial_effects() {
let mut audio = audio();
for _ in 0..MAX_COMMANDS_PER_FRAME - 1 {
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
}
assert_eq!(audio.set_volume(15, 0), AudioOpStatus::Ok);
assert_eq!(audio.set_pan(0, 255), AudioOpStatus::CommandLimit);
assert_eq!(audio.set_pitch(16, f64::NAN), AudioOpStatus::VoiceInvalid);
assert_eq!(audio.set_pitch(0, f64::NAN), AudioOpStatus::ArgRangeInvalid);
let sample = Arc::new(Sample::new(48_000, vec![1]));
assert_eq!(
audio.play_sample(sample.clone(), 0, 255, 0, 1.0, 0, LoopMode::Off),
AudioOpStatus::CommandLimit
);
assert_eq!(Arc::strong_count(&sample), 1);
assert!(audio.transport.try_take().unwrap().frame.is_none());
audio.finish_frame();
assert!(!audio.ready());
assert_eq!(
audio.transport.try_take().unwrap().frame.unwrap().len(),
MAX_COMMANDS_PER_FRAME
);
assert!(audio.ready());
audio.begin_frame();
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
}
#[test]
fn lifecycle_and_reset_bypass_full_guest_batch_and_release_samples() {
let mut audio = audio();
audio.set_session(Some(1));
let sample = Arc::new(Sample::new(48_000, vec![1]));
let weak = Arc::downgrade(&sample);
assert_eq!(audio.play_sample(sample, 0, 255, 0, 1.0, 0, LoopMode::On), AudioOpStatus::Ok);
for _ in 1..MAX_COMMANDS_PER_FRAME {
audio.stop(1);
}
audio.finish_frame();
assert!(!audio.ready());
assert!(audio.lifecycle_ready());
audio.begin_lifecycle();
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
audio.finish_lifecycle(true);
audio.set_paused(true);
let delivery = audio.transport.try_take().unwrap();
assert!(delivery.paused);
assert_eq!(delivery.frame.as_ref().unwrap().len(), MAX_COMMANDS_PER_FRAME);
assert!(matches!(
delivery.lifecycle.as_ref().unwrap()[0],
AudioCommand::Stop { voice_id: 0 }
));
let old_epoch = delivery.epoch;
drop(delivery);
assert!(weak.upgrade().is_none(), "driver must not retain a playback mirror");
audio.stop(0);
audio.finish_frame();
audio.begin_lifecycle();
audio.stop(1);
audio.finish_lifecycle(true);
audio.set_session(Some(2));
let delivery = audio.transport.try_take().unwrap();
assert!(delivery.epoch > old_epoch);
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
assert!(audio.ready());
}
#[test]
fn lifecycle_publishes_prefix_first_and_aborted_batches_are_cancelled() {
let mut audio = audio();
audio.set_pan(0, 17);
audio.begin_lifecycle();
audio.stop(1);
audio.finish_lifecycle(true);
let delivery = audio.transport.try_take().unwrap();
assert!(delivery.frame.is_none());
let lifecycle = delivery.lifecycle.unwrap();
assert!(matches!(lifecycle[0], AudioCommand::SetPan { pan: 17, .. }));
assert!(matches!(lifecycle[1], AudioCommand::Stop { voice_id: 1 }));
audio.set_volume(0, 23);
audio.finish_frame();
let commands = audio.transport.try_take().unwrap().frame.unwrap();
assert_eq!(commands.len(), 1);
assert!(matches!(commands[0], AudioCommand::SetVolume { volume: 23, .. }));
audio.stop(0);
audio.abort_frame();
audio.finish_frame();
audio.begin_lifecycle();
audio.stop(1);
audio.finish_lifecycle(false);
let delivery = audio.transport.try_take().unwrap();
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
}
#[test]
fn prefix_flush_preserves_quota_and_combined_delivery_is_bounded() {
let mut audio = audio();
for _ in 0..MAX_COMMANDS_PER_FRAME {
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
}
audio.begin_lifecycle();
for _ in 0..MAX_COMMANDS_PER_FRAME {
assert_eq!(audio.stop(1), AudioOpStatus::Ok);
}
assert_eq!(audio.stop(1), AudioOpStatus::CommandLimit);
audio.finish_lifecycle(true);
let delivery = audio.transport.try_take().unwrap().lifecycle.unwrap();
assert_eq!(delivery.len(), 2 * MAX_COMMANDS_PER_FRAME);
assert!(matches!(delivery[0], AudioCommand::Stop { voice_id: 0 }));
assert!(matches!(delivery[MAX_COMMANDS_PER_FRAME], AudioCommand::Stop { voice_id: 1 }));
assert_eq!(audio.stop(0), AudioOpStatus::CommandLimit);
// Resume and another pause must not replenish the interrupted frame quota.
for _ in 0..2 {
audio.begin_lifecycle();
audio.stop(1);
audio.finish_lifecycle(true);
audio.transport.consume_silently();
assert_eq!(audio.stop(0), AudioOpStatus::CommandLimit);
}
audio.finish_frame();
assert!(audio.transport.try_take().unwrap().frame.is_none());
assert_eq!(audio.stop(0), AudioOpStatus::Ok);
}
#[test]
fn failed_callback_cancels_unpublished_prefix_and_its_sample_reference() {
let mut audio = audio();
let sample = Arc::new(Sample::new(48_000, vec![1]));
let weak = Arc::downgrade(&sample);
audio.play_sample(sample, 0, 255, 0, 1.0, 0, LoopMode::On);
audio.begin_lifecycle();
audio.stop(0);
audio.finish_lifecycle(false);
audio.finish_frame();
let delivery = audio.transport.try_take().unwrap();
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
assert!(weak.upgrade().is_none());
}
}
@@ -0,0 +1,86 @@
use super::AudioCommand;
use std::sync::{Arc, Mutex};
/// One pending frame plus an independent lifecycle lane. Control state never
/// competes with guest commands for capacity. The lifecycle batch can include
/// an interrupted frame prefix (at most 1024 + 1024 commands). Only one consumer
/// may drain it.
#[derive(Clone, Default)]
pub struct AudioTransport(Arc<Mutex<Mailbox>>);
#[derive(Default)]
struct Mailbox {
epoch: u64,
paused: bool,
frame: Option<Vec<AudioCommand>>,
lifecycle: Option<Vec<AudioCommand>>,
}
pub struct AudioDelivery {
pub epoch: u64,
pub paused: bool,
pub frame: Option<Vec<AudioCommand>>,
pub lifecycle: Option<Vec<AudioCommand>>,
}
impl AudioTransport {
/// The real-time consumer never waits for the producer's short critical section.
pub fn try_take(&self) -> Option<AudioDelivery> {
let mut state = self.0.try_lock().ok()?;
Some(AudioDelivery {
epoch: state.epoch,
paused: state.paused,
frame: state.frame.take(),
lifecycle: state.lifecycle.take(),
})
}
pub fn consume_silently(&self) {
let _ = self.try_take();
}
pub fn ready(&self) -> bool {
let state = self.0.lock().expect("audio mailbox");
state.frame.is_none() && state.lifecycle.is_none()
}
pub fn lifecycle_ready(&self) -> bool {
self.0.lock().expect("audio mailbox").lifecycle.is_none()
}
pub(super) fn publish(&self, commands: Vec<AudioCommand>, lifecycle: bool) {
if commands.is_empty() {
return;
}
let mut state = self.0.lock().expect("audio mailbox");
let target = if lifecycle { &mut state.lifecycle } else { &mut state.frame };
assert!(target.is_none(), "audio producer must respect backpressure");
*target = Some(commands);
}
pub(super) fn reset(&self) {
let mut state = self.0.lock().expect("audio mailbox");
state.epoch = state.epoch.checked_add(1).expect("audio epoch exhausted");
state.frame = None;
state.lifecycle = None;
state.paused = false;
}
pub(super) fn set_paused(&self, paused: bool) {
self.0.lock().expect("audio mailbox").paused = paused;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn realtime_consumer_does_not_wait_for_publication_lock() {
let transport = AudioTransport::default();
let guard = transport.0.lock().unwrap();
assert!(transport.try_take().is_none());
drop(guard);
assert!(transport.try_take().is_some());
}
}
+4 -1
View File
@@ -11,7 +11,10 @@ mod touch;
mod wall_clock;
pub use crate::asset::AssetManager;
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
pub use crate::audio::{
Audio, AudioCommand, AudioDelivery, AudioTransport, Channel, MAX_CHANNELS,
MAX_COMMANDS_PER_FRAME, OUTPUT_SAMPLE_RATE,
};
pub use crate::frame_composer::{ComposerBuffer, FrameComposer, SceneStatus, SpriteController};
pub use crate::gfx::Gfx;
pub use crate::local_render_backend::LocalFramebufferRenderBackend;
@@ -112,7 +112,7 @@ mod tests {
Game2DFramePacket::default(),
))
.expect("test platform render sink should accept local submission");
assert!(!platform.audio().is_playing(0));
assert!(platform.audio().ready());
assert!(!platform.input().pad().any());
assert!(platform.telemetry().telemetry_snapshot().is_none());
}
@@ -61,6 +61,30 @@ impl Firmware {
/// This method is called exactly once per Host frame (60Hz).
/// It updates peripheral signals and delegates the logic to the current state.
pub fn tick(&mut self, signals: &InputSignals, platform: &mut dyn RuntimePlatform) {
self.sync_audio(platform);
self.tick_inner(signals, platform);
self.sync_audio(platform);
}
fn sync_audio(&mut self, platform: &mut dyn RuntimePlatform) {
let task = self.os.lifecycle().resident_game_task().map(|task| task.0);
let suspended = matches!(
self.os.lifecycle().resident_game().map(|game| game.state),
Some(ResidentGameState::PausedSuspended)
);
let paused = self.game_lifecycle_audio_paused() || self.os.vm().paused();
platform.audio_mut().set_session(task);
platform.audio_mut().set_paused(paused);
// Without a pause hook the OS can suspend synchronously, bypassing the
// callback runner. Complete the same audio boundary before resuming.
// A real hook already published its prefix; repeating an empty flush is inert.
if suspended && platform.audio().lifecycle_ready() {
platform.audio_mut().begin_lifecycle();
platform.audio_mut().finish_lifecycle(true);
}
}
fn tick_inner(&mut self, signals: &InputSignals, platform: &mut dyn RuntimePlatform) {
self.os.poll_background_io(platform);
if self.os.memcard().host_faulted() {
// Keep the resident VM, snapshots, and worker-owned buffers alive. A
@@ -1858,6 +1882,113 @@ mod tests {
(firmware, platform, task)
}
fn check_audio_lifecycle(partial: bool, hooks: bool) {
use prometeu_bytecode::registry::LifecycleRole;
use prometeu_drivers::AudioCommand;
let mut program = TestProgram::single(
assemble("PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\nFRAME_SYNC\nJMP 0").unwrap(),
int64_signature(0, 0),
0,
8,
);
program.syscalls.push(SyscallDecl {
module: "audio".into(),
name: "stop".into(),
version: 1,
arg_slots: 1,
ret_slots: 1,
});
for (role, voice) in [(LifecycleRole::BeforePause, 1), (LifecycleRole::BeforeResume, 2)] {
if !hooks {
continue;
}
let code = assemble(&format!("PUSH_I32 {voice}\nHOSTCALL 0\nPOP_N 1\nRET")).unwrap();
program.functions.push(FunctionDecl {
lifecycle_role: role,
code_offset: program.code.len() as u32,
code_len: code.len() as u32,
max_stack_slots: 8,
..Default::default()
});
program.code.extend(code);
}
let mut cartridge = valid_cartridge(AppMode::Game);
cartridge.capabilities = caps::AUDIO;
cartridge.program = program.serialize();
let mut fw = Firmware::new(None);
let mut platform = TestPlatform::new();
let signals = InputSignals::default();
fw.load_cartridge(cartridge);
fw.tick(&signals, &mut platform);
if partial {
for _ in 0..2 {
assert!(fw.os.vm().debug_step_active_session(&mut platform).is_none());
}
} else {
fw.tick(&signals, &mut platform);
}
let task = fw.os.lifecycle().resident_game_task().unwrap();
let transport = platform.local_hardware().audio.transport();
assert_eq!(platform.audio().ready(), partial);
fw.os.lifecycle().suspend_task(task).unwrap();
fw.tick(&signals, &mut platform);
let delivery = transport.try_take().unwrap();
assert!(delivery.paused);
if partial {
assert!(delivery.frame.is_none());
} else {
assert!(matches!(delivery.frame.unwrap()[0], AudioCommand::Stop { voice_id: 0 }));
}
let lifecycle = delivery.lifecycle.unwrap_or_default();
assert_eq!(lifecycle.len(), usize::from(partial) + usize::from(hooks));
if partial {
assert!(matches!(lifecycle[0], AudioCommand::Stop { voice_id: 0 }));
}
if hooks {
assert!(matches!(lifecycle[usize::from(partial)], AudioCommand::Stop { voice_id: 1 }));
}
assert!(fw.resume_resident_game_from_home());
fw.tick(&signals, &mut platform);
let delivery = transport.try_take().unwrap();
assert!(!delivery.paused);
if hooks {
assert!(matches!(delivery.lifecycle.unwrap()[0], AudioCommand::Stop { voice_id: 2 }));
} else {
assert!(delivery.lifecycle.is_none());
assert!(delivery.frame.is_none(), "hookless resume completed the prefix-free frame");
}
let epoch = delivery.epoch;
fw.tick(&signals, &mut platform);
if partial && hooks {
assert!(
platform.audio().ready(),
"prefix must not be published again at frame completion"
);
fw.tick(&signals, &mut platform);
}
assert!(!platform.audio().ready());
fw.change_state(FirmwareState::Reset(ResetStep), &signals, &mut platform);
let delivery = transport.try_take().unwrap();
assert!(delivery.epoch > epoch);
assert!(delivery.frame.is_none() && delivery.lifecycle.is_none());
assert!(platform.audio().ready());
}
#[test]
fn audio_lifecycle_publishes_with_pending_frame_and_reset_invalidates_session() {
check_audio_lifecycle(false, true);
}
#[test]
fn audio_lifecycle_publishes_interrupted_frame_prefix_before_hook() {
check_audio_lifecycle(true, true);
}
#[test]
fn audio_lifecycle_flushes_prefix_when_optional_hooks_are_absent() {
check_audio_lifecycle(true, false);
}
#[test]
fn lifecycle_home_resume_callbacks_are_outside_frames_and_preserve_pc() {
let (mut fw, mut platform, task) = load_lifecycle("RET", "RET");
@@ -15,6 +15,8 @@ impl ResetStep {
let _ = ctx.os.lifecycle().terminate_resident_game();
ctx.os.sessions().clear_vm_sessions();
ctx.os.vm().reset_global_runtime_state();
ctx.platform.audio_mut().reset();
ctx.platform.audio_mut().set_session(None);
}
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
@@ -32,6 +32,7 @@ pub(crate) fn terminate_resident_game(
};
os.memcard().session.end_session();
platform.audio_mut().set_session(None);
os.vm().transition_render_owner(AppMode::Shell, 0);
platform.game2d_frame_composer().unbind_scene();
platform.assets_mut().shutdown();
@@ -17,6 +17,7 @@ pub enum AudioOpStatus {
AssetNotFound = 4,
NoEffect = 5,
BankInvalid = 6,
CommandLimit = 7,
}
pub trait AudioBridge {
@@ -43,10 +44,22 @@ pub trait AudioBridge {
priority: u8,
loop_mode: LoopMode,
) -> AudioOpStatus;
fn stop(&mut self, voice_id: usize);
fn set_volume(&mut self, voice_id: usize, volume: u8);
fn set_pan(&mut self, voice_id: usize, pan: u8);
fn set_pitch(&mut self, voice_id: usize, pitch: f64);
fn is_playing(&self, voice_id: usize) -> bool;
fn clear_commands(&mut self);
fn stop(&mut self, voice_id: usize) -> AudioOpStatus;
fn set_volume(&mut self, voice_id: usize, volume: u8) -> AudioOpStatus;
fn set_pan(&mut self, voice_id: usize, pan: u8) -> AudioOpStatus;
fn set_pitch(&mut self, voice_id: usize, pitch: f64) -> AudioOpStatus;
/// Pending publication must be consumed before starting another guest frame.
fn ready(&self) -> bool;
fn begin_frame(&mut self);
fn finish_frame(&mut self);
fn abort_frame(&mut self);
/// Lifecycle has independent bounded staging/publication, even with a pending frame.
fn lifecycle_ready(&self) -> bool;
fn begin_lifecycle(&mut self);
/// Success publishes the interrupted frame prefix before callback commands,
/// without replenishing frame quota. Failure cancels both unpublished parts.
fn finish_lifecycle(&mut self, success: bool);
fn set_session(&mut self, session: Option<u32>);
fn reset(&mut self);
fn set_paused(&mut self, paused: bool);
}
@@ -55,6 +55,10 @@ pub enum Syscall {
ComposerEmitSprite = 0x1104,
AudioPlaySample = 0x3001,
AudioPlay = 0x3002,
AudioStop = 0x3003,
AudioSetVolume = 0x3004,
AudioSetPan = 0x3005,
AudioSetPitch = 0x3006,
FsOpen = 0x4001,
FsRead = 0x4002,
FsWrite = 0x4003,
@@ -11,4 +11,24 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
.rets(1)
.caps(caps::AUDIO)
.cost(5),
SyscallRegistryEntry::builder(Syscall::AudioStop, "audio", "stop")
.args(1)
.rets(1)
.caps(caps::AUDIO)
.cost(5),
SyscallRegistryEntry::builder(Syscall::AudioSetVolume, "audio", "set_volume")
.args(2)
.rets(1)
.caps(caps::AUDIO)
.cost(5),
SyscallRegistryEntry::builder(Syscall::AudioSetPan, "audio", "set_pan")
.args(2)
.rets(1)
.caps(caps::AUDIO)
.cost(5),
SyscallRegistryEntry::builder(Syscall::AudioSetPitch, "audio", "set_pitch")
.args(2)
.rets(1)
.caps(caps::AUDIO)
.cost(5),
];
@@ -33,6 +33,10 @@ impl Syscall {
0x1104 => Some(Self::ComposerEmitSprite),
0x3001 => Some(Self::AudioPlaySample),
0x3002 => Some(Self::AudioPlay),
0x3003 => Some(Self::AudioStop),
0x3004 => Some(Self::AudioSetVolume),
0x3005 => Some(Self::AudioSetPan),
0x3006 => Some(Self::AudioSetPitch),
0x4001 => Some(Self::FsOpen),
0x4002 => Some(Self::FsRead),
0x4003 => Some(Self::FsWrite),
@@ -102,6 +106,10 @@ impl Syscall {
Self::ComposerEmitSprite => "ComposerEmitSprite",
Self::AudioPlaySample => "AudioPlaySample",
Self::AudioPlay => "AudioPlay",
Self::AudioStop => "AudioStop",
Self::AudioSetVolume => "AudioSetVolume",
Self::AudioSetPan => "AudioSetPan",
Self::AudioSetPitch => "AudioSetPitch",
Self::FsOpen => "FsOpen",
Self::FsRead => "FsRead",
Self::FsWrite => "FsWrite",
@@ -496,3 +496,23 @@ fn memcard_syscall_signatures_are_pinned() {
);
}
}
#[test]
fn audio_control_abi_and_capability_are_stable() {
for (name, id, args) in [
("stop", 0x3003, 1),
("set_volume", 0x3004, 2),
("set_pan", 0x3005, 2),
("set_pitch", 0x3006, 2),
] {
let entry = resolve_syscall("audio", name, 1).unwrap();
assert_eq!(entry.id, id);
assert_eq!(entry.meta.arg_slots, args);
assert_eq!(entry.meta.ret_slots, 1);
assert_eq!(entry.meta.cost_hint, 5);
assert_eq!(entry.meta.caps, caps::AUDIO);
let identities = [SyscallIdentity { module: "audio", name, version: 1 }];
assert!(resolve_program_syscalls(&identities, 0).is_err());
assert!(resolve_program_syscalls(&identities, caps::AUDIO).is_ok());
}
}
@@ -75,11 +75,19 @@ impl<'a> VmFacade<'a> {
if let Some(report) = &session.runtime.last_crash_report {
return Err(report.clone());
}
if !platform.audio().lifecycle_ready() {
return Ok(());
}
let reason = if !session.lifecycle_started {
session.lifecycle_started = true;
match session.vm.begin_lifecycle(role) {
Ok(true) => None,
Ok(false) => Some(LogicalFrameEndingReason::LifecycleComplete),
Ok(false) => {
// Optional hooks still form a successful lifecycle boundary.
platform.audio_mut().begin_lifecycle();
platform.audio_mut().finish_lifecycle(true);
Some(LogicalFrameEndingReason::LifecycleComplete)
}
Err(error) => Some(LogicalFrameEndingReason::Panic(format!("{error:?}"))),
}
} else {
@@ -3,7 +3,7 @@ use crate::fs::{FsState, VirtualFS};
use crate::services::memcard::MemcardService;
use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
use prometeu_hal::app_mode::AppMode;
use prometeu_hal::asset::{AssetId, AssetOpStatus, BankType, SlotRef};
use prometeu_hal::asset::{AssetId, AssetOpStatus, BankType};
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::log::{LogLevel, LogSource};
@@ -495,15 +495,17 @@ impl NativeInterface for VmRuntimeHost<'_> {
Ok(())
}
Syscall::AudioPlay => {
let bank_id = expect_int(args, 0)? as u8;
let bank_id_raw = expect_int(args, 0)?;
let sample_id_raw = expect_int(args, 1)?;
let voice_id_raw = expect_int(args, 2)?;
let volume_raw = expect_int(args, 3)?;
let pan_raw = expect_int(args, 4)?;
let pitch = expect_number(args, 5, "pitch")?;
let loop_mode = match expect_int(args, 6)? {
0 => prometeu_hal::LoopMode::Off,
_ => prometeu_hal::LoopMode::On,
let loop_raw = expect_int(args, 6)?;
let loop_mode = if loop_raw == 0 {
prometeu_hal::LoopMode::Off
} else {
prometeu_hal::LoopMode::On
};
if !(0..16).contains(&voice_id_raw) {
@@ -511,18 +513,18 @@ impl NativeInterface for VmRuntimeHost<'_> {
return Ok(());
}
if platform.assets().slot_info(SlotRef::audio(bank_id as usize)).asset_id.is_none()
{
if !(0..16).contains(&bank_id_raw) {
ret.push_int(AudioOpStatus::BankInvalid as i64);
return Ok(());
}
let bank_id = bank_id_raw as u8;
if sample_id_raw < 0
|| sample_id_raw > u16::MAX as i64
|| !(0..=255).contains(&volume_raw)
|| !(0..=255).contains(&pan_raw)
|| !pitch.is_finite()
|| pitch <= 0.0
|| !(0..=1).contains(&loop_raw)
{
ret.push_int(AudioOpStatus::ArgRangeInvalid as i64);
return Ok(());
@@ -541,6 +543,38 @@ impl NativeInterface for VmRuntimeHost<'_> {
ret.push_int(status as i64);
Ok(())
}
Syscall::AudioStop
| Syscall::AudioSetVolume
| Syscall::AudioSetPan
| Syscall::AudioSetPitch => {
let voice = expect_int(args, 0)?;
// Decode all types before reporting operational validation failures.
let value = match syscall {
Syscall::AudioSetVolume | Syscall::AudioSetPan => expect_int(args, 1)?,
_ => 0,
};
let pitch = if syscall == Syscall::AudioSetPitch {
expect_number(args, 1, "pitch")?
} else {
1.0
};
let status = if !(0..16).contains(&voice) {
AudioOpStatus::VoiceInvalid
} else if !(0..=255).contains(&value) || !pitch.is_finite() || pitch <= 0.0 {
AudioOpStatus::ArgRangeInvalid
} else {
let audio = platform.audio_mut();
match syscall {
Syscall::AudioStop => audio.stop(voice as usize),
Syscall::AudioSetVolume => audio.set_volume(voice as usize, value as u8),
Syscall::AudioSetPan => audio.set_pan(voice as usize, value as u8),
Syscall::AudioSetPitch => audio.set_pitch(voice as usize, pitch),
_ => unreachable!(),
}
};
ret.push_int(status as i64);
Ok(())
}
Syscall::FsOpen => {
let path = expect_string(args, 0, "path")?;
if *self.fs_state != FsState::Mounted {
@@ -1602,3 +1602,6 @@ fn tick_composer_emit_sprite_type_mismatch_surfaces_trap_not_panic() {
}
assert!(matches!(runtime.last_crash_report, Some(CrashReport::VmTrap { .. })));
}
#[path = "tests_audio.rs"]
mod audio_controls;
@@ -0,0 +1,218 @@
use super::*;
use prometeu_drivers::{AudioCommand, AudioTransport};
struct Harness {
runtime: VirtualMachineRuntime,
vm: VirtualMachine,
platform: TestPlatform,
log: LogService,
fs: VirtualFS,
fs_state: FsState,
memcard: MemcardService,
files: HashMap<u32, String>,
next: u32,
}
impl Harness {
fn new(code: &str, name: &str, args: u16) -> Self {
let mut runtime = VirtualMachineRuntime::new(None);
let mut vm = VirtualMachine::default();
let mut log = LogService::new(4096);
let program = serialized_single_function_module(
assemble(code).unwrap(),
vec![SyscallDecl {
module: "audio".into(),
name: name.into(),
version: 1,
arg_slots: args,
ret_slots: 1,
}],
);
runtime
.initialize_vm(&mut log, &mut vm, &cartridge_with_program(program, caps::AUDIO))
.unwrap();
Self {
runtime,
vm,
log,
platform: TestPlatform::new(),
fs: VirtualFS::new(),
fs_state: FsState::Unmounted,
memcard: MemcardService::new(),
files: HashMap::new(),
next: 1,
}
}
fn tick(&mut self) -> Option<CrashReport> {
self.runtime.tick(
&mut self.log,
&mut self.fs,
&mut self.fs_state,
&mut self.memcard,
&mut self.files,
&mut self.next,
&mut self.vm,
&InputSignals::default(),
&mut self.platform,
)
}
fn transport(&self) -> AudioTransport {
self.platform.local_hardware().audio.transport()
}
fn step(&mut self) -> Option<CrashReport> {
self.runtime.debug_step_instruction(
&mut self.log,
&mut self.fs,
&mut self.fs_state,
&mut self.memcard,
&mut self.files,
&mut self.next,
&mut self.vm,
&mut self.platform,
)
}
}
#[test]
fn guest_audio_status_matrix_and_type_traps() {
for (name, args, inputs, expected) in [
("stop", 1, "PUSH_I32 0", 0),
("stop", 1, "PUSH_I32 15", 0),
("stop", 1, "PUSH_I32 -1", 1),
("stop", 1, "PUSH_I32 16", 1),
("set_volume", 2, "PUSH_I32 0\nPUSH_I32 0", 0),
("set_volume", 2, "PUSH_I32 0\nPUSH_I32 255", 0),
("set_volume", 2, "PUSH_I32 0\nPUSH_I32 256", 3),
("set_pan", 2, "PUSH_I32 0\nPUSH_I32 -1", 3),
("set_pan", 2, "PUSH_I32 16\nPUSH_I32 -1", 1),
("set_pan", 2, "PUSH_I32 15\nPUSH_I32 255", 0),
("set_pitch", 2, "PUSH_I32 0\nPUSH_I32 1", 0),
("set_pitch", 2, "PUSH_I32 0\nPUSH_I32 0", 3),
("set_pitch", 2, "PUSH_I32 0\nPUSH_I32 -1", 3),
(
"play",
7,
"PUSH_I32 256\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 0\nPUSH_I32 1\nPUSH_I32 0",
6,
),
] {
let mut h = Harness::new(&format!("{inputs}\nHOSTCALL 0\nFRAME_SYNC\nHALT"), name, args);
assert!(h.tick().is_none(), "{name}: {inputs}");
assert_eq!(h.vm.operand_stack_top(1), vec![Value::Int64(expected)], "{name}: {inputs}");
let batch = h.transport().try_take().unwrap().frame;
assert_eq!(batch.map_or(0, |v| v.len()), usize::from(expected == 0));
}
for name in ["set_volume", "set_pan", "set_pitch"] {
let mut h = Harness::new("PUSH_I32 -1\nPUSH_BOOL 1\nHOSTCALL 0\nFRAME_SYNC\nHALT", name, 2);
assert!(matches!(h.tick(), Some(CrashReport::VmTrap { .. })));
assert!(h.transport().try_take().unwrap().frame.is_none());
}
}
#[test]
fn frame_publication_backpressure_abort_and_debug_steps() {
let mut h = Harness::new(
"PUSH_I32 0\nHOSTCALL 0\nFRAME_SYNC\nPUSH_I32 1\nHOSTCALL 0\nFRAME_SYNC\nHALT",
"stop",
1,
);
assert!(h.tick().is_none());
let pc = h.vm.pc();
assert!(h.tick().is_none());
assert_eq!(h.vm.pc(), pc, "pending batch stalls guest");
let batch = h.transport().try_take().unwrap().frame.unwrap();
assert!(matches!(batch[0], AudioCommand::Stop { voice_id: 0 }));
assert!(h.tick().is_none());
assert!(matches!(
h.transport().try_take().unwrap().frame.unwrap()[0],
AudioCommand::Stop { voice_id: 1 }
));
for end in ["HALT", "PUSH_BOOL 1\nHOSTCALL 0\nHALT"] {
let mut h = Harness::new(&format!("PUSH_I32 0\nHOSTCALL 0\n{end}"), "stop", 1);
let _ = h.tick();
h.platform.audio_mut().finish_frame();
assert!(h.transport().try_take().unwrap().frame.is_none(), "abort cancels admitted stop");
}
let mut h = Harness::new("PUSH_I32 0\nHOSTCALL 0\nFRAME_SYNC\nHALT", "stop", 1);
assert!(h.step().is_none());
assert!(h.step().is_none());
assert!(h.transport().try_take().unwrap().frame.is_none());
// Switching from stepping to running must preserve previously staged commands.
assert!(h.tick().is_none());
assert_eq!(h.transport().try_take().unwrap().frame.unwrap().len(), 1);
}
#[test]
fn guest_quota_is_deterministic_and_resets_on_next_frame() {
let repeated = "PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\n".repeat(1024);
let mut h = Harness::new(
&format!(
"{repeated}PUSH_I32 0\nHOSTCALL 0\nFRAME_SYNC\nPUSH_I32 0\nHOSTCALL 0\nFRAME_SYNC\nHALT"
),
"stop",
1,
);
assert!(h.tick().is_none());
assert_eq!(h.vm.operand_stack_top(1), vec![Value::Int64(7)]);
assert_eq!(h.transport().try_take().unwrap().frame.unwrap().len(), 1024);
assert!(h.tick().is_none());
assert_eq!(h.vm.operand_stack_top(1), vec![Value::Int64(0)]);
assert_eq!(h.transport().try_take().unwrap().frame.unwrap().len(), 1);
}
#[test]
fn guest_play_validates_raw_bank_loop_and_preserves_both_play_forms() {
use prometeu_drivers::SoundBankPoolInstaller;
use prometeu_hal::{sample::Sample, sound_bank::SoundBank};
for (bank, loop_mode, expected) in
[(0, 0, 0), (0, 1, 0), (0, -1, 3), (0, 2, 3), (256, 0, 6), (-256, 0, 6), (16, 0, 6)]
{
let mut h = Harness::new(
&format!(
"PUSH_I32 {bank}\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 127\nPUSH_I32 1\nPUSH_I32 {loop_mode}\nHOSTCALL 0\nFRAME_SYNC\nHALT"
),
"play",
7,
);
let banks = Arc::new(MemoryBanks::new());
banks.install_sound_bank(
0,
Arc::new(SoundBank::new(vec![Arc::new(Sample::new(48_000, vec![1, 2, 3]))])),
);
h.platform = TestPlatform::new_with_memory_banks(banks);
assert!(h.tick().is_none());
assert_eq!(h.vm.operand_stack_top(1), vec![Value::Int64(expected)]);
let batch = h.transport().try_take().unwrap().frame;
assert_eq!(batch.map_or(0, |v| v.len()), usize::from(expected == 0));
}
let mut h = Harness::new(
"PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 255\nPUSH_I32 127\nPUSH_I32 1\nHOSTCALL 0\nFRAME_SYNC\nHALT",
"play_sample",
5,
);
let banks = Arc::new(MemoryBanks::new());
banks.install_sound_bank(
0,
Arc::new(SoundBank::new(vec![Arc::new(Sample::new(48_000, vec![1]))])),
);
h.platform = TestPlatform::new_with_memory_banks(banks);
assert!(h.tick().is_none());
assert_eq!(h.vm.operand_stack_top(1), vec![Value::Int64(0)]);
assert!(matches!(
h.transport().try_take().unwrap().frame.unwrap()[0],
AudioCommand::Play { loop_mode: prometeu_hal::LoopMode::Off, .. }
));
}
#[test]
fn normal_entry_return_is_a_successful_implicit_audio_frame() {
let mut h = Harness::new("PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\nRET", "stop", 1);
for _ in 0..2 {
assert!(h.tick().is_none());
assert_eq!(h.transport().try_take().unwrap().frame.unwrap().len(), 1);
}
let mut h = Harness::new("PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\nRET", "stop", 1);
for _ in 0..4 {
assert!(h.step().is_none());
}
assert_eq!(h.transport().try_take().unwrap().frame.unwrap().len(), 1);
}
@@ -82,14 +82,21 @@ impl VirtualMachineRuntime {
vm: &mut VirtualMachine,
platform: &mut dyn RuntimePlatform,
) -> Option<CrashReport> {
if !platform.audio().ready() {
return None;
}
if vm.memcard_boot_result() == Some(0) && memcard.session.boot_pending() {
return None;
}
let was_memcard_boot = vm.memcard_boot_active();
if was_memcard_boot {
platform.audio_mut().begin_lifecycle();
}
if vm.call_stack_is_empty()
&& let Err(error) = vm.prepare_boot_call()
{
let report = CrashReport::VmInit { error };
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
@@ -106,6 +113,15 @@ impl VirtualMachineRuntime {
};
vm.step(&mut host, &mut ctx)
};
// run_budget derives these terminal reasons after executing an instruction;
// single stepping must observe the same publication/cancellation boundary.
let step_result = if step_result.is_ok() && vm.is_halted() {
Err(LogicalFrameEndingReason::Halted)
} else if step_result.is_ok() && !was_memcard_boot && vm.call_stack_is_empty() {
Err(LogicalFrameEndingReason::EndOfRom)
} else {
step_result
};
if was_memcard_boot
&& step_result == Err(LogicalFrameEndingReason::LifecycleComplete)
@@ -119,9 +135,33 @@ impl VirtualMachineRuntime {
message: format!("Memcard bootstrap failed: {error:?}: {}", memcard.diagnostic),
pc: Some(vm.pc() as u32),
};
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
if was_memcard_boot {
match &step_result {
Err(LogicalFrameEndingReason::LifecycleComplete) => {
platform.audio_mut().finish_lifecycle(true)
}
Err(
LogicalFrameEndingReason::Trap(_)
| LogicalFrameEndingReason::Panic(_)
| LogicalFrameEndingReason::Halted,
) => platform.audio_mut().finish_lifecycle(false),
_ => {}
}
}
match &step_result {
Err(LogicalFrameEndingReason::FrameSync | LogicalFrameEndingReason::EndOfRom) => {
platform.audio_mut().finish_frame()
}
Err(LogicalFrameEndingReason::Halted) => platform.audio_mut().reset(),
Err(LogicalFrameEndingReason::Trap(_) | LogicalFrameEndingReason::Panic(_)) => {
platform.audio_mut().abort_frame()
}
_ => {}
}
match step_result {
Ok(())
| Err(
@@ -141,6 +181,7 @@ impl VirtualMachineRuntime {
report.log_tag(),
format!("PVM Fault during Step: {}", report),
);
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
Some(report)
}
@@ -153,6 +194,7 @@ impl VirtualMachineRuntime {
report.log_tag(),
format!("PVM Fault during Step: {}", report),
);
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
Some(report)
}
@@ -176,6 +218,10 @@ impl VirtualMachineRuntime {
if self.paused && !single_step && !self.debug_step_request {
return LogicalFrameEndingReason::Breakpoint;
}
if !platform.audio().lifecycle_ready() {
return LogicalFrameEndingReason::BudgetExhausted;
}
platform.audio_mut().begin_lifecycle();
let result = catch_unwind(AssertUnwindSafe(|| {
let mut ctx = HostContext::new_platform(Some(platform));
let mut host = VmRuntimeHost {
@@ -200,6 +246,16 @@ impl VirtualMachineRuntime {
let reason = result.unwrap_or_else(|payload| {
LogicalFrameEndingReason::Panic(Self::host_panic_payload_to_string(payload))
});
match &reason {
LogicalFrameEndingReason::LifecycleComplete => {
platform.audio_mut().finish_lifecycle(true)
}
LogicalFrameEndingReason::BudgetExhausted | LogicalFrameEndingReason::Breakpoint => {}
_ => {
platform.audio_mut().finish_lifecycle(false);
platform.audio_mut().abort_frame();
}
}
if reason == LogicalFrameEndingReason::Breakpoint || single_step || self.debug_step_request
{
self.paused = true;
@@ -255,6 +311,7 @@ impl VirtualMachineRuntime {
}),
};
if let Some(report) = &failure {
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
}
return failure;
@@ -277,6 +334,9 @@ impl VirtualMachineRuntime {
return None;
}
if !platform.audio().ready() {
return None;
}
self.update_fs(log_service, fs, fs_state);
if !self.logical_frame_active {
if RenderManager::policy_for_app_mode(self.current_cartridge_app_mode)
@@ -293,6 +353,7 @@ impl VirtualMachineRuntime {
if self.needs_prepare_entry_call || vm.call_stack_is_empty() {
if let Err(error) = vm.prepare_boot_call() {
let report = CrashReport::VmInit { error };
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
@@ -341,6 +402,9 @@ impl VirtualMachineRuntime {
self.atomic_telemetry.cycles_used.fetch_add(run.cycles_used, Ordering::Relaxed);
self.atomic_telemetry.vm_steps.fetch_add(run.steps_executed, Ordering::Relaxed);
if run.reason == LogicalFrameEndingReason::Halted {
platform.audio_mut().reset();
}
if run.reason == LogicalFrameEndingReason::Breakpoint {
self.paused = true;
self.debug_step_request = false;
@@ -363,6 +427,7 @@ impl VirtualMachineRuntime {
report.log_tag(),
report.summary(),
);
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
@@ -376,6 +441,7 @@ impl VirtualMachineRuntime {
report.log_tag(),
report.summary(),
);
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
@@ -500,6 +566,8 @@ impl VirtualMachineRuntime {
log_service.reset_count();
// Entry return is the runtime's successful implicit frame end.
platform.audio_mut().finish_frame();
self.logical_frame_index += 1;
self.logical_frame_active = false;
self.logical_frame_remaining_cycles = 0;
@@ -532,6 +600,7 @@ impl VirtualMachineRuntime {
report.log_tag(),
report.summary(),
);
platform.audio_mut().abort_frame();
self.last_crash_report = Some(report.clone());
return Some(report);
}
@@ -582,7 +651,7 @@ impl VirtualMachineRuntime {
platform: &mut dyn RuntimePlatform,
) {
platform.game2d_frame_composer().begin_frame();
platform.audio_mut().clear_commands();
platform.audio_mut().begin_frame();
self.logs_written_this_frame.clear();
}
}
@@ -1,12 +1,14 @@
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use prometeu_drivers::{AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
use prometeu_drivers::{AudioDelivery, AudioTransport};
use prometeu_hal::LoopMode;
use ringbuf::HeapRb;
use ringbuf::traits::{Consumer, Producer, Split};
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
trait AudioStreamHandle {}
@@ -88,7 +90,11 @@ impl AudioRuntime for CpalAudioRuntime {
}
pub struct HostAudio {
pub producer: Option<ringbuf::wrap::CachingProd<Arc<HeapRb<AudioCommand>>>>,
transport: AudioTransport,
failed: Arc<AtomicBool>,
heartbeat: Arc<AtomicU64>,
last_heartbeat: u64,
last_progress: Instant,
pub perf_consumer: Option<ringbuf::wrap::CachingCons<Arc<HeapRb<u64>>>>,
_stream: Option<Box<dyn AudioStreamHandle>>,
}
@@ -101,15 +107,27 @@ impl Default for HostAudio {
impl HostAudio {
pub fn new() -> Self {
Self { producer: None, perf_consumer: None, _stream: None }
Self {
transport: AudioTransport::default(),
failed: Arc::new(AtomicBool::new(false)),
heartbeat: Arc::new(AtomicU64::new(0)),
last_heartbeat: 0,
last_progress: Instant::now(),
perf_consumer: None,
_stream: None,
}
}
pub fn init(&mut self) -> Result<(), HostAudioError> {
pub fn init(&mut self, transport: AudioTransport) -> Result<(), HostAudioError> {
self.transport = transport;
self.init_with_runtime(&CpalAudioRuntime)
}
fn init_with_runtime<R: AudioRuntime>(&mut self, runtime: &R) -> Result<(), HostAudioError> {
self.producer = None;
self.failed = Arc::new(AtomicBool::new(false));
self.heartbeat = Arc::new(AtomicU64::new(0));
self.last_heartbeat = 0;
self.last_progress = Instant::now();
self.perf_consumer = None;
self._stream = None;
@@ -121,8 +139,9 @@ impl HostAudio {
buffer_size: cpal::BufferSize::Default,
};
let rb = HeapRb::<AudioCommand>::new(1024);
let (prod, mut cons) = rb.split();
let transport = self.transport.clone();
let failed = self.failed.clone();
let heartbeat = self.heartbeat.clone();
let mut mixer = AudioMixer::new();
@@ -134,34 +153,45 @@ impl HostAudio {
&device,
&config,
move |data: &mut [f32]| {
// Consumes commands from ringbuffer
while let Some(cmd) = cons.try_pop() {
mixer.process_command(cmd);
heartbeat.fetch_add(1, Ordering::Relaxed);
if let Some(delivery) = transport.try_take() {
mixer.apply_delivery(delivery);
}
// Mixes audio
mixer.fill_buffer(data);
// Sends processing time in microseconds
let _ = perf_prod.try_push(mixer.last_processing_time.as_micros() as u64);
},
|err| eprintln!("audio stream error: {}", err),
move |err| {
failed.store(true, Ordering::Relaxed);
eprintln!("audio stream error: {err}; switching to silent audio");
},
)?;
runtime.play_stream(&stream)?;
self.producer = Some(prod);
self.perf_consumer = Some(perf_cons);
self._stream = Some(Box::new(stream));
Ok(())
}
pub fn send_commands(&mut self, commands: &mut Vec<AudioCommand>) {
if let Some(producer) = &mut self.producer {
for cmd in commands.drain(..) {
if producer.try_push(cmd).is_err() {
eprintln!("[HostAudio] Command ringbuffer full, dropping command.");
}
}
} else {
commands.clear();
/// Called even while guest execution is backpressured. A failed or stalled
/// device cannot retain the only publication slot indefinitely.
pub fn service(&mut self) {
let heartbeat = self.heartbeat.load(Ordering::Relaxed);
if heartbeat != self.last_heartbeat {
self.last_heartbeat = heartbeat;
self.last_progress = Instant::now();
}
if self._stream.is_some()
&& (self.failed.load(Ordering::Relaxed)
|| self.last_progress.elapsed() >= Duration::from_secs(2))
{
eprintln!("[HostAudio] Output unavailable/stalled; consuming audio silently.");
self._stream = None;
self.perf_consumer = None;
}
if self._stream.is_none() {
self.transport.consume_silently();
}
}
@@ -221,14 +251,10 @@ mod tests {
}
#[test]
fn test_send_commands_without_audio_drops_pending_commands() {
fn test_service_without_audio_is_safe() {
let mut audio = HostAudio::new();
let mut commands = vec![AudioCommand::MasterPause, AudioCommand::MasterResume];
audio.send_commands(&mut commands);
assert!(commands.is_empty());
assert!(audio.producer.is_none());
audio.service();
assert!(audio.transport.ready());
}
#[test]
@@ -250,7 +276,6 @@ mod tests {
let result = audio.init_with_runtime(&runtime);
assert_eq!(result, Err(HostAudioError::NoOutputDevice));
assert!(audio.producer.is_none());
assert!(audio.perf_consumer.is_none());
assert!(audio._stream.is_none());
}
@@ -267,7 +292,6 @@ mod tests {
let result = audio.init_with_runtime(&runtime);
assert_eq!(result, Err(HostAudioError::BuildStream("simulated build failure".to_string())));
assert!(audio.producer.is_none());
assert!(audio.perf_consumer.is_none());
assert!(audio._stream.is_none());
}
@@ -284,7 +308,6 @@ mod tests {
let result = audio.init_with_runtime(&runtime);
assert_eq!(result, Err(HostAudioError::PlayStream("simulated play failure".to_string())));
assert!(audio.producer.is_none());
assert!(audio.perf_consumer.is_none());
assert!(audio._stream.is_none());
}
@@ -296,7 +319,6 @@ mod tests {
audio.init_with_runtime(&runtime).unwrap();
assert!(audio.producer.is_some());
assert!(audio.perf_consumer.is_some());
assert!(audio._stream.is_some());
}
@@ -306,6 +328,7 @@ pub struct AudioMixer {
voices: [Channel; MAX_CHANNELS],
pub last_processing_time: Duration,
paused: bool,
epoch: u64,
}
impl Default for AudioMixer {
@@ -316,17 +339,35 @@ impl Default for AudioMixer {
impl AudioMixer {
pub fn new() -> Self {
Self { voices: Default::default(), last_processing_time: Duration::ZERO, paused: false }
Self {
voices: Default::default(),
last_processing_time: Duration::ZERO,
paused: false,
epoch: 0,
}
}
pub fn apply_delivery(&mut self, delivery: AudioDelivery) {
if delivery.epoch < self.epoch {
return;
}
if delivery.epoch != self.epoch {
self.voices = Default::default();
self.epoch = delivery.epoch;
}
// A frame pending before a lifecycle hook is always applied first.
for batch in [delivery.frame, delivery.lifecycle].into_iter().flatten() {
for command in batch {
self.process_command(command);
}
}
self.paused = delivery.paused;
}
pub fn process_command(&mut self, cmd: AudioCommand) {
match cmd {
AudioCommand::Play { sample, voice_id, volume, pan, pitch, priority, loop_mode } => {
if voice_id < MAX_CHANNELS {
println!(
"[AudioMixer] Playing voice {}: vol={}, pitch={}, loop={:?}",
voice_id, volume, pitch, loop_mode
);
self.voices[voice_id] = Channel {
sample: Some(sample),
active: true,
@@ -360,14 +401,6 @@ impl AudioMixer {
self.voices[voice_id].pitch = pitch;
}
}
AudioCommand::MasterPause => {
println!("[AudioMixer] Master Pause");
self.paused = true;
}
AudioCommand::MasterResume => {
println!("[AudioMixer] Master Resume");
self.paused = false;
}
}
}
@@ -384,59 +417,62 @@ impl AudioMixer {
}
for voice in self.voices.iter_mut() {
let sample_data = match &voice.sample {
Some(s) => s,
None => continue,
let Some(sample) = voice.sample.as_ref() else {
continue;
};
let pitch_ratio = sample_data.sample_rate as f64 / OUTPUT_SAMPLE_RATE as f64;
let step = voice.pitch * pitch_ratio;
let vol_f = voice.volume as f32 / 255.0;
let pan_f = voice.pan as f32 / 255.0;
let vol_l = vol_f * (1.0 - pan_f).sqrt();
let vol_r = vol_f * pan_f.sqrt();
let len = sample.data.len();
if len == 0 {
voice.active = false;
voice.sample = None;
continue;
}
let (loop_start, end) = match (sample.loop_start, sample.loop_end) {
(Some(start), Some(end)) if start < end && end as usize <= len => {
(start as f64, end as f64)
}
_ => (0.0, len as f64),
};
let ratio = sample.sample_rate as f64 / OUTPUT_SAMPLE_RATE as f64;
let volume = voice.volume as f32 / 255.0;
let pan = voice.pan as f32 / 255.0;
let left = volume * (1.0 - pan).sqrt();
let right = volume * pan.sqrt();
for frame in buffer.as_chunks_mut::<2>().0 {
let pos_int = voice.pos as usize;
let pos_fract = voice.pos - pos_int as f64;
if pos_int >= sample_data.data.len() {
let pos = voice.pos as usize;
if pos >= len {
voice.active = false;
voice.sample = None;
break;
}
// Linear Interpolation
let s1 = sample_data.data[pos_int] as f32 / 32768.0;
let s2 = if pos_int + 1 < sample_data.data.len() {
sample_data.data[pos_int + 1] as f32 / 32768.0
} else if voice.loop_mode == LoopMode::On {
let loop_start = sample_data.loop_start.unwrap_or(0) as usize;
sample_data.data[loop_start] as f32 / 32768.0
let s1 = sample.data[pos] as f32 / 32768.0;
let next = if voice.loop_mode == LoopMode::On && (pos + 1) as f64 >= end {
loop_start as usize
} else {
0.0
pos + 1
};
let sample_val = s1 + (s2 - s1) * pos_fract as f32;
frame[0] += sample_val * vol_l;
frame[1] += sample_val * vol_r;
voice.pos += step;
let end_pos =
sample_data.loop_end.map(|e| e as f64).unwrap_or(sample_data.data.len() as f64);
if voice.pos >= end_pos {
if voice.loop_mode == LoopMode::On {
let loop_start = sample_data.loop_start.unwrap_or(0) as f64;
voice.pos = loop_start + (voice.pos - end_pos);
} else {
let s2 = sample.data.get(next).copied().unwrap_or(0) as f32 / 32768.0;
let value = s1 + (s2 - s1) * (voice.pos - pos as f64) as f32;
frame[0] += value * left;
frame[1] += value * right;
if ratio == 0.0 {
continue;
}
if voice.pitch >= (end - voice.pos) / ratio {
if voice.loop_mode == LoopMode::Off {
voice.active = false;
voice.sample = None;
break;
}
let length = end - loop_start;
// Reduce before multiplication: every finite positive pitch,
// including f64::MAX, remains finite and wraps multiple loops.
let step = (voice.pitch % (length / ratio)) * ratio;
voice.pos = loop_start + (voice.pos - loop_start + step).rem_euclid(length);
if voice.pos >= end {
voice.pos = loop_start;
}
} else {
voice.pos += voice.pitch * ratio;
}
}
}
@@ -448,3 +484,241 @@ impl AudioMixer {
self.last_processing_time = start.elapsed();
}
}
#[cfg(test)]
mod control_tests {
use super::*;
use prometeu_drivers::{Audio, MemoryBanks};
use prometeu_hal::{AudioBridge, AudioOpStatus, sample::Sample};
fn pair() -> (Audio, AudioMixer) {
(Audio::new(Arc::new(MemoryBanks::new())), AudioMixer::new())
}
fn apply(audio: &Audio, mixer: &mut AudioMixer) {
mixer.apply_delivery(audio.transport().try_take().unwrap());
}
fn play(audio: &mut Audio, sample: Arc<Sample>, pitch: f64, looping: bool) {
assert_eq!(
audio.play_sample(
sample,
0,
255,
0,
pitch,
0,
if looping { LoopMode::On } else { LoopMode::Off }
),
AudioOpStatus::Ok
);
}
#[test]
fn pcm_controls_preserve_position_and_stop_is_idempotent() {
let (mut audio, mut mixer) = pair();
play(&mut audio, Arc::new(Sample::new(48_000, vec![16384; 32])), 1.0, true);
audio.finish_frame();
apply(&audio, &mut mixer);
let mut pcm = [0.0; 4];
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.5, 0.0, 0.5, 0.0]);
assert_eq!(mixer.voices[0].pos, 2.0);
audio.set_pan(0, 255);
audio.set_volume(0, 51);
audio.set_pitch(0, 2.0);
audio.finish_frame();
apply(&audio, &mut mixer);
assert_eq!(mixer.voices[0].pos, 2.0);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0, 0.1, 0.0, 0.1]);
assert_eq!(mixer.voices[0].pos, 6.0);
audio.set_volume(0, 0);
audio.finish_frame();
apply(&audio, &mut mixer);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 4]);
assert_eq!(mixer.voices[0].pos, 10.0);
audio.stop(0);
audio.stop(0);
audio.finish_frame();
apply(&audio, &mut mixer);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 4]);
assert!(mixer.voices[0].sample.is_none());
}
#[test]
fn fifo_reuse_and_inactive_setters_do_not_create_play_defaults() {
let (mut audio, mut mixer) = pair();
audio.set_volume(0, 0);
audio.set_pitch(0, 4.0);
play(&mut audio, Arc::new(Sample::new(48_000, vec![16384; 16])), 1.0, true);
audio.stop(0);
play(&mut audio, Arc::new(Sample::new(48_000, vec![8192; 16])), 1.0, true);
audio.finish_frame();
apply(&audio, &mut mixer);
let mut pcm = [0.0; 2];
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.25, 0.0]);
assert_eq!(mixer.voices[0].pos, 1.0);
}
#[test]
fn pause_and_session_reset_work_with_pending_batches() {
let (mut audio, mut mixer) = pair();
audio.set_session(Some(1));
play(&mut audio, Arc::new(Sample::new(48_000, vec![16384; 16])), 1.0, true);
audio.finish_frame();
audio.set_paused(true);
apply(&audio, &mut mixer);
let mut pcm = [1.0; 4];
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 4]);
assert_eq!(mixer.voices[0].pos, 0.0);
audio.begin_lifecycle();
audio.set_pan(0, 255);
audio.finish_lifecycle(true);
audio.set_paused(false);
apply(&audio, &mut mixer);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0, 0.5, 0.0, 0.5]);
assert_eq!(mixer.voices[0].pos, 2.0);
play(&mut audio, Arc::new(Sample::new(48_000, vec![16384; 16])), 1.0, true);
audio.finish_frame();
let stale = audio.transport().try_take().unwrap();
audio.reset();
apply(&audio, &mut mixer);
mixer.apply_delivery(stale);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 4]);
}
#[test]
fn play_before_home_cannot_restart_after_callback_stop_and_resume() {
let (mut audio, mut mixer) = pair();
play(&mut audio, Arc::new(Sample::new(48_000, vec![16384; 16])), 1.0, true);
// Home occurs before FRAME_SYNC; the old play must precede the hook stop.
audio.set_paused(true);
audio.begin_lifecycle();
audio.stop(0);
audio.finish_lifecycle(true);
apply(&audio, &mut mixer);
assert!(mixer.voices[0].sample.is_none());
audio.begin_lifecycle();
audio.finish_lifecycle(true);
audio.set_paused(false);
apply(&audio, &mut mixer);
let mut pcm = [1.0; 16];
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 16]);
audio.finish_frame();
apply(&audio, &mut mixer);
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm, [0.0; 16]);
assert!(mixer.voices[0].sample.is_none());
}
#[test]
fn short_loops_and_extreme_pitch_remain_finite_and_release_at_completion() {
for pitch in [0.125, 1.0, 4.0, 1000.0, f64::MAX] {
let (mut audio, mut mixer) = pair();
play(
&mut audio,
Arc::new(Sample::new(96_000, vec![16384; 3]).with_loop(1, 3)),
pitch,
true,
);
audio.finish_frame();
apply(&audio, &mut mixer);
let mut pcm = [0.0; 128];
mixer.fill_buffer(&mut pcm);
assert!(pcm.iter().all(|v| v.is_finite()));
assert!(pcm.chunks_exact(2).all(|frame| frame == [0.5, 0.0]));
assert!(mixer.voices[0].active);
assert!(mixer.voices[0].pos >= 1.0 && mixer.voices[0].pos < 3.0);
}
let (mut audio, mut mixer) = pair();
let sample = Arc::new(Sample::new(48_000, vec![16384]));
let weak = Arc::downgrade(&sample);
play(&mut audio, sample, 1.0, false);
audio.finish_frame();
apply(&audio, &mut mixer);
mixer.fill_buffer(&mut [0.0; 4]);
assert!(weak.upgrade().is_none());
}
#[test]
fn unloading_bank_keeps_playback_until_stop() {
use prometeu_drivers::SoundBankPoolInstaller;
use prometeu_hal::sound_bank::SoundBank;
let banks = Arc::new(MemoryBanks::new());
let sample = Arc::new(Sample::new(48_000, vec![16384; 4]));
let weak = Arc::downgrade(&sample);
banks.install_sound_bank(0, Arc::new(SoundBank::new(vec![sample])));
let mut audio = Audio::new(banks.clone());
let mut mixer = AudioMixer::new();
assert_eq!(audio.play(0, 0, 0, 255, 0, 1.0, 0, LoopMode::On), AudioOpStatus::Ok);
audio.finish_frame();
banks.clear_sound_banks();
apply(&audio, &mut mixer);
let mut pcm = [0.0; 8];
mixer.fill_buffer(&mut pcm);
assert_eq!(pcm[0], 0.5);
assert!(weak.upgrade().is_some());
assert_eq!(audio.play(0, 0, 0, 255, 0, 1.0, 0, LoopMode::On), AudioOpStatus::BankInvalid);
audio.stop(0);
audio.finish_frame();
apply(&audio, &mut mixer);
assert!(weak.upgrade().is_none());
}
#[test]
fn failed_or_stalled_output_releases_backpressure() {
for failed in [true, false] {
let (mut audio, _) = pair();
audio.stop(0);
audio.finish_frame();
let mut host = HostAudio::new();
host.transport = audio.transport();
host._stream = Some(Box::new(FakeSmokeStream));
host.failed.store(failed, Ordering::Relaxed);
if !failed {
host.last_progress = Instant::now() - Duration::from_secs(3);
}
host.service();
assert!(audio.ready());
assert!(host._stream.is_none());
}
}
struct FakeSmokeStream;
impl AudioStreamHandle for FakeSmokeStream {}
#[test]
#[ignore = "requires a real desktop audio device; emits a brief quiet tone"]
fn desktop_audio_device_smoke() {
let (mut audio, _) = pair();
let mut host = HostAudio::new();
host.init(audio.transport()).expect("physical output device");
let data = (0..4800)
.map(|i| ((i as f64 * std::f64::consts::TAU * 440.0 / 48_000.0).sin() * 1500.0) as i16)
.collect();
play(&mut audio, Arc::new(Sample::new(48_000, data)), 1.0, true);
audio.finish_frame();
let deadline = Instant::now() + Duration::from_secs(2);
while !audio.ready() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(audio.ready());
assert!(host.heartbeat.load(Ordering::Relaxed) > 0);
audio.set_volume(0, 127);
audio.set_pan(0, 255);
audio.set_pitch(0, 1.5);
audio.finish_frame();
std::thread::sleep(Duration::from_millis(100));
assert!(audio.ready());
audio.stop(0);
audio.finish_frame();
std::thread::sleep(Duration::from_millis(100));
assert!(audio.ready());
assert!(!host.failed.load(Ordering::Relaxed));
}
}
@@ -8,10 +8,10 @@ use crate::utilities::{draw_owned_rgba8888_frame_to_rgba8, draw_rgba8888_to_rgba
use pixels::wgpu::PresentMode;
use pixels::{Pixels, PixelsBuilder, SurfaceTexture};
use prometeu_drivers::hardware::Hardware;
use prometeu_drivers::{AudioCommand, LocalFramebufferRenderBackend, MemoryBanks};
use prometeu_drivers::{LocalFramebufferRenderBackend, MemoryBanks};
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
use prometeu_hal::telemetry::CertificationConfig;
use prometeu_hal::{OwnedRgba8888Frame, RenderOwnership, RuntimePlatform};
use prometeu_hal::{AudioBridge, OwnedRgba8888Frame, RenderOwnership, RuntimePlatform};
use prometeu_system::{LatestRenderFrameStore, RenderWorkerConfig, discover_games_root};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -147,8 +147,6 @@ pub struct HostRunner {
/// The physical audio driver.
audio: HostAudio,
/// Last known pause state to sync with audio.
last_paused_state: bool,
/// Worker-published frame store used as the single observable publication source.
render_frame_store: LatestRenderFrameStore,
/// Tracks whether a new logical frame or host-only surface invalidation requires presentation.
@@ -238,7 +236,6 @@ impl HostRunner {
stats: HostStats::new(),
debugger: HostDebugger::new(),
audio: HostAudio::new(),
last_paused_state: false,
render_frame_store,
presentation: PresentationState::default(),
}
@@ -312,7 +309,7 @@ impl ApplicationHandler for HostRunner {
self.pixels = Some(pixels);
if let Err(err) = self.audio.init() {
if let Err(err) = self.audio.init(self.hardware.audio.transport()) {
eprintln!("[HostAudio] Disabled: {}", err);
}
@@ -442,22 +439,11 @@ impl ApplicationHandler for HostRunner {
self.stats.record_host_cpu_time(self.firmware.os.vm().last_frame_cpu_time_us());
}
// Sync pause state with audio.
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
// being cleared by the OS if a new logical frame starts in this tick.
let lifecycle_audio_paused = self.firmware.game_lifecycle_audio_paused();
let is_paused = lifecycle_audio_paused
let is_paused = self.firmware.game_lifecycle_audio_paused()
|| self.firmware.os.vm().paused()
|| self.debugger.waiting_for_start;
if is_paused != self.last_paused_state {
self.last_paused_state = is_paused;
let cmd =
if is_paused { AudioCommand::MasterPause } else { AudioCommand::MasterResume };
self.hardware.audio.commands.push(cmd);
}
// Sync virtual audio commands to the physical mixer.
self.audio.send_commands(&mut self.hardware.audio.commands);
self.hardware.audio.set_paused(is_paused);
self.audio.service();
self.accumulator -= self.frame_target_dt;
self.stats.record_frame();
@@ -287,7 +287,7 @@ impl HeadlessHost {
self.require_active("step")?;
self.firmware.os.vm().set_paused(true);
let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform);
self.platform.hardware.audio.clear_commands();
self.platform.hardware.audio.transport().consume_silently();
Ok(report)
}
@@ -410,7 +410,7 @@ impl HeadlessHost {
fn tick_once(&mut self) {
self.firmware.tick(&self.signals, &mut self.platform);
self.platform.hardware.audio.clear_commands();
self.platform.hardware.audio.transport().consume_silently();
}
fn execution_status(&mut self) -> HostExecutionStatus {
@@ -683,3 +683,34 @@ fn module_with_locals(code: Vec<u8>, syscalls: Vec<SyscallDecl>, local_slots: u1
fn asm(source: &str) -> Vec<u8> {
assemble(source).expect("assemble")
}
#[test]
fn audio_controls_quota_and_multiple_frames_are_device_independent() {
let dir = temp_cart("audio-controls");
let syscalls: Vec<_> = [("stop", 1), ("set_volume", 2), ("set_pan", 2), ("set_pitch", 2)]
.into_iter()
.map(|(name, arg_slots)| SyscallDecl {
module: "audio".into(),
name: name.into(),
version: 1,
arg_slots,
ret_slots: 1,
})
.collect();
let mut code = "PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\n".repeat(1021);
// Cross a physical tick while retaining the same logical-frame quota.
code.push_str(&"NOP\n".repeat(250_001));
code.push_str("PUSH_I32 0\nPUSH_I32 255\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 127\nHOSTCALL 2\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 2\nHOSTCALL 3\nPOP_N 1\nPUSH_I32 0\nHOSTCALL 0\nFRAME_SYNC\nPOP_N 1\nJMP 0");
let program = module(asm(&code), syscalls.clone());
write_cartridge(&dir, 50, "Audio Controls", &program, &syscalls);
let mut first = HeadlessHost::new();
first.boot(&dir).unwrap();
let mut second = HeadlessHost::new();
second.boot(&dir).unwrap();
for _ in 0..3 {
completed(first.advance_frame().unwrap());
completed(second.advance_frame().unwrap());
assert_same_state(&first.get_state(), &second.get_state());
assert_eq!(first.get_state().stack_top.last(), Some(&prometeu_bytecode::Value::Int64(7)));
}
}
@@ -0,0 +1,67 @@
---
id: LSN-0069
ticket: guest-audio-voice-control
title: Audio Admission Needs a Delivery Boundary and Independent Lifecycle Control
created: 2026-10-14
tags: [audio, runtime, lifecycle, host]
---
## Context
The runtime already played PCM samples on sixteen explicit voices, but the guest could not stop a loop or change an ongoing playback. Exposing four existing mixer operations also exposed a delivery problem: a full desktop ring buffer discarded commands, including a successful stop.
Source record: DEC-0057 was accepted from AGD-0058 and implemented through PLN-0188 in DSC-0055. The workflow records were completed and pruned after publication. The [audio peripheral specification](../../../docs/specs/runtime/05-audio-peripheral.md) is normative; this lesson explains the resulting implementation.
## Admission Is Not Application
A successful audio syscall means that a validated command was admitted into a bounded logical batch. It does not mean the callback has already mixed it or that the device has emitted sound. Keeping those events separate makes overload understandable: an invalid argument consumes no quota, a command beyond the batch quota returns an explicit status, and an accepted command cannot silently disappear because the physical device is slower.
The guest now has stop, volume, pan and pitch controls beside the two playback calls. All use the same quota and status-first boundary. Explicit voice selection keeps replacement simple: play A, stop, play B leaves B. Setters preserve position and do not establish defaults for a later play. The implementation keeps finite-positive pitch instead of imposing an arbitrary musical range.
The [driver](../../../crates/console/prometeu-drivers/src/audio.rs) stages commands, while the [transport](../../../crates/console/prometeu-drivers/src/audio/transport.rs) holds one pending frame batch. The producer waits before advancing more guest work when publication is occupied. The callback only tries to take a batch; it never waits for the producer lock. This trades occasional host-side delay for bounded memory and reliable admitted work.
## Logical Completion Must Match the Runtime's Existing Entry Model
Physical ticks are not publication boundaries. A logical frame can span multiple host ticks, and debugger stepping can emit commands before normal execution resumes. Clearing staging on every physical tick loses work and resets quota incorrectly.
The existing runtime completes a logical frame at explicit FRAME_SYNC or normal entry-function return. Both now publish the batch. Treating return as an abort would break return-based cartridges. The [runtime integration](../../../crates/console/prometeu-system/src/services/vm_runtime/tick.rs) also derives entry return and HALT when stepping, because the VM's budgeted runner normally derives those outcomes outside the individual instruction.
Faults and aborted execution cancel unpublished commands. Tests distinguish cancellation from successful implicit completion, rather than assuming every boundary looks like a FRAME_SYNC opcode.
## Lifecycle Cannot Compete for the Last Guest Slot
A paused guest might never execute another FRAME_SYNC. A reset must work even if the last frame filled its entire quota. Therefore pause state and session invalidation do not enter the ordinary guest queue.
Lifecycle callbacks have their own bounded staging and publication lane. A pending normal frame precedes the subsequent callback batch; callback controls are applied before resumed PCM generation. A successful lifecycle boundary flushes an interrupted frame's pending prefix before the callback commands. Without that exception, a play emitted before Home could be applied after the callback's stop on resume. The combined delivery is still bounded (1,024 frame commands plus 1,024 callback commands). Admission accounting is separate from vector length: flushing the prefix does not replenish the interrupted frame's quota, even across repeated pause/resume transitions. Absent optional hooks still complete this boundary; failed hooks cancel unpublished work. A later fault cannot roll back a prefix already published. A session generation invalidates prior commands and mixer voices together, preventing a delayed play from reviving an ended cartridge.
Firmware synchronizes resident identity and pause state around its tick, and the explicit reset/termination paths invalidate audio. The desktop continues servicing events during guest backpressure. Missing or failed output consumes silently, and a callback-progress watchdog prevents a stalled device from holding the publication slot forever. These foreground guarantees do not establish ownership among multiple background producers.
## Completion Ownership Determines Reference Lifetime
The driver previously mirrored voice state, retaining a sample without receiving the mixer's natural-completion signal. Exporting that mirror as is_playing would have created both an unreliable query and a retention problem.
The delivered driver owns staged commands rather than a second playback mirror. The mixer owns playback position and observes natural completion. A bank can be unloaded while an admitted command or voice retains its immutable sample; memory becomes reclaimable after the last owner stops, finishes, is replaced or is invalidated. Tests use weak references to verify that distinction directly.
The mixer also reduces large pitch steps before multiplication when wrapping loops. Merely subtracting one loop length fails when a step crosses several repetitions, and multiplying an arbitrary finite pitch by the sample-rate ratio can overflow. Short-loop tests include f64::MAX and non-unit source/output sample-rate ratios.
## Evidence and Limits
Validation was run locally on macOS/aarch64 on 2026-10-14:
- `cargo test --workspace --all-targets --all-features --no-fail-fast`: **1,016 passed**, zero failed, eleven ignored across 55 reported suites.
- `cargo test -p prometeu-host-desktop-winit --lib -- --ignored`: **six passed**, including physical audio output and debugger sockets. The sandbox could not open the device; the authorized run outside it passed.
- `cargo clippy --workspace --all-features`: passed without warnings.
- `cargo fmt --all -- --check`, `git diff --check`, and `discussion validate`: passed.
- Regression coverage includes staged play before Home followed by callback stop, silence after resume and later frame completion, absent optional hooks, independent callback quota, the 2,048-command combined bound, and repeated lifecycle flushes without replenishing frame admission.
The device smoke initialized a physical stream and observed callback consumption through play, volume/pan/pitch changes and stop. Synthetic PCM assertions establish signal values, silence, position continuity, short-loop wrapping and sample lifetime. No human listening observation or cross-device PCM identity is claimed.
The API is a foreground PCM control surface. It does not establish musical sequencing, FM synthesis, completion events, playback handles or authoring formats. Reference-game integration remains a separate consumer delivery and cannot be inferred from these provider tests.
## Reusable Checks
- Identify the event that admits work separately from the event that makes it observable.
- Bound staging as well as transport, and report rejection before mutating state.
- Keep shutdown, pause and session invalidation independent of guest saturation.
- Place completion-sensitive state with the component that actually observes completion.
- Test both explicit and implicit runtime boundaries, including debugger transitions.
+58 -188
View File
@@ -1,225 +1,95 @@
# Audio Peripheral (Audio System)
# Audio Peripheral
Domain: virtual hardware: audio
Function: normative
Didactic companion: [`../learn/mental-model-audio.md`](../runtime/learn/mental-model-audio.md)
Didactic companion: [Audio admission and lifecycle delivery](../../../discussion/lessons/DSC-0055-guest-audio-voice-control/LSN-0069-audio-admission-needs-a-delivery-boundary-and-independent-lifecycle-control.md).
## 1 Scope
## 1 Scope and machine limits
This chapter defines the runtime-facing audio contract of PROMETEU.
The AUDIO peripheral provides command-driven PCM playback on **16 explicitly selected voices**. Each voice plays one immutable mono PCM16 sample, with independent volume, stereo pan, playback rate and optional looping. The output target is **48,000 Hz stereo**, with saturating mixing. Hosts may use normalized floating-point device buffers to represent that output.
The AUDIO peripheral is responsible for sound generation and mixing under explicit machine limits.
The guest controls playback at logical-frame boundaries. The host renders samples independently of the 60 Hz game loop. These are separate clocks: a successful syscall admits a command, without promising that sound has already reached the device or a fixed latency in milliseconds.
Core contract:
This surface does not define playback handles, completion queries/events, automatic voice allocation, music sequencing, synthesis, streaming, envelopes or background audio producers.
- command-driven control from the game loop;
- fixed output format;
- finite voice count;
- deterministic voice conflict policy;
- explicit cost in cycles and certification surface.
## 2 Guest ABI v1
## 2 General Architecture
Every entry requires capability `AUDIO`, returns exactly one `status:int`, and has fixed syscall cost **5 cycles**, including operational rejection. Structural ABI misuse follows the VM trap policy. Mixing time is host work, not the syscall's logical cycle charge.
The audio system is composed of:
| Identity | ID | Arguments in order |
| --- | --- | --- |
| `audio.play_sample` | `0x3001` | `sample:int, voice:int, volume:int, pan:int, pitch:number` |
| `audio.play` | `0x3002` | `bank:int, sample:int, voice:int, volume:int, pan:int, pitch:number, loop:int` |
| `audio.stop` | `0x3003` | `voice:int` |
| `audio.set_volume` | `0x3004` | `voice:int, volume:int` |
| `audio.set_pan` | `0x3005` | `voice:int, pan:int` |
| `audio.set_pitch` | `0x3006` | `voice:int, pitch:number` |
- **Voices (channels)** — independent players
- **Samples** — PCM data
- **Mixer** — summation of voices
- **Output** — PCM stereo buffer
`number` means the existing VM numeric carriers accepted by audio playback, including integer and floating-point values; it is not a new ABI type. `play_sample` uses bank 0 and looping off. Both plays use internal priority 0. The public API has no priority argument.
Timing boundary:
### 2.1 Ranges and validation
- game sends commands at **60 Hz**;
- audio generates PCM at **48 kHz**.
- Voice: integer **0..15**.
- Bank: integer **0..15**, referring to an installed sound bank. Validate before narrowing; 256 must never alias bank 0.
- Sample index: integer **0..65535**; the sample must exist in the selected bank.
- Volume: integer **0..255**. Zero silences output while playback position continues advancing.
- Pan: integer **0..255**, from fully left to fully right. The mixer uses equal-power gains `sqrt(1-pan/255)` and `sqrt(pan/255)`.
- Pitch: **finite and strictly positive**; 1 means original speed. NaN, infinity, zero and negative values are rejected. No 0.25..4 restriction is imposed. Setters and plays use the same range.
- Loop: integer **0 or 1**, meaning off or on. Other values are rejected, without normalization.
## 3 Output Format
Structural type/shape/capability checks precede operational validation. Validate voice first, then other arguments/resources, then command admission. Rejection must not alter playback state or enqueue a command. When multiple operational errors exist, voice takes precedence; bank validity precedes sample lookup for bank playback.
- Sample rate: **48,000 Hz**
- Format: **PCM16 stereo (signed i16)**
- Clipping: saturation/clamp
### 2.2 Status values
## 4 Voices
| Value | Name | Meaning |
| --- | --- | --- |
| 0 | `OK` | Command admitted; application is asynchronous |
| 1 | `VOICE_INVALID` | Voice outside 0..15 |
| 2 | `SAMPLE_NOT_FOUND` | Sample absent from the selected installed bank |
| 3 | `ARG_RANGE_INVALID` | Invalid sample index, volume, pan, pitch or loop value |
| 4 | `ASSET_NOT_FOUND` | Reserved existing status |
| 5 | `NO_EFFECT` | Reserved existing status; inactive-voice controls do not use it |
| 6 | `BANK_INVALID` | Invalid or uninstalled sound bank |
| 7 | `COMMAND_LIMIT` | Current guest batch already admitted 1,024 commands |
### 4.1 Quantity
Stop and setters can return 0, 1, 3 where applicable, or 7. Stopping an inactive voice or changing its parameters succeeds. No helper based on the driver's former activity mirror is exposed as a playback-completion query.
```
MAX_VOICES = 16
```
## 3 Ordering and voice reuse
Each voice:
Commands in a published batch apply in emission order before a subsequent output buffer. The API does not promise sample offsets within a buffer.
- plays **1 sample at a time**
- is independent
- is mixed into the final output
A play explicitly replaces the selected voice, resets its position, and supplies every playback parameter. There is no automatic stealing of another voice. `play(A), stop, play(B)` on one voice leaves B playing. A setter following play changes that playback without resetting position. Stop is idempotent, releases the sample and silences the voice. Setters on inactive voices do not establish defaults for future plays.
### 4.2 Voice State
## 4 Admission, publication and backpressure
Each voice maintains:
A logical frame admits at most **1,024 commands**, shared by both plays and all four controls. Invalid calls do not consume quota. An excess call returns `COMMAND_LIMIT`; a rejected stop requires a guest retry. Quota depends on the logical frame, not the device callback speed or number of physical host ticks.
- `sample_id`
- `pos` (fractional position in the sample)
- `rate` (pitch)
- `volume` (0..255)
- `pan` (0..255, left→right)
- `loop_mode` (off / on)
- `loop_start`, `loop_end`
- `priority` (optional)
Except for the lifecycle prefix publication defined below, commands remain staged until successful logical-frame completion: explicit `FRAME_SYNC` or the runtime's implicit frame end when the entry function returns (`EndOfRom`). An aborted/faulted frame or `HALT` cancels its unpublished commands. Debugger stepping preserves staging and publishes at either successful completion boundary.
### 4.3 Voice Conflict
The transport holds **one pending frame batch**, in addition to producer staging and a batch already taken by the mixer. The guest waits for pending publication to be consumed before advancing further; the host continues handling events. Accepted commands must not be silently dropped because a device queue is full. The audio callback must not wait on a producer lock: if a short publication critical section is busy, it retries on a later buffer.
If all voices are occupied:
Lifecycle callbacks have independent staging and one independent pending publication slot. Callback admission is bounded to **1,024 guest commands per callback**. This prevents an occupied frame slot or exhausted frame quota from blocking callback controls. A successful callback publishes without requiring `FRAME_SYNC`; a failed callback cancels its staged commands. Pending frame publication precedes subsequent lifecycle publication; guest frames do not advance while either publication slot is occupied.
- an explicit policy is applied:
- `STEAL_OLDEST`
- `STEAL_QUIETEST`
- `STEAL_LOWEST_PRIORITY`
A successful lifecycle boundary publishes the interrupted frame's staged prefix **before** the callback commands, together in the lifecycle delivery. This explicit early-publication boundary preserves emission order: `play` before Home followed by `stop` in the callback must remain stopped after resume. An absent optional callback still completes this boundary. The combined delivery holds at most **2,048 commands**: up to 1,024 from the interrupted frame plus 1,024 from the callback.
## 5 Samples
Flushing a prefix does **not** replenish that frame's admission quota. The resumed frame retains its admitted-command count across repeated pause/resume transitions until normal frame completion, abort or session reset. The prefix is not published again when the frame completes. Failed callbacks cancel their unpublished commands and prefix. A later fault in the resumed frame cannot roll back a prefix already published at the earlier lifecycle boundary.
### 5.1 Format
## 5 Pause, reset and sessions
PROMETEU samples:
Home and debugger pause stop progression of Game voices, preserving their position. Resume continues from that position. Callback commands are applied before resumed PCM generation. Pause state and session invalidation are internal controls independent of guest quota and pending batch capacity.
- **PCM16 mono**
- own sample_rate (e.g., 22050, 44100, 48000)
- immutable data at runtime
Reset, termination, crash or cartridge replacement ends the audio session, stops all its voices and invalidates its pending/staged commands. Internal session generations prevent old deliveries from restarting playback. Ending a session may cancel previously admitted commands. Silence is guaranteed from processing the transition in the mixer; buffers already submitted to a physical device cannot be recalled.
Fields:
## 6 Samples, interpolation and ownership
- `sample_rate`
- `frames_len`
- `loop_start`, `loop_end` (optional)
Samples are immutable PCM16 mono, with a source sample rate and optional loop bounds. Linear interpolation uses fractional playback position. Playback rate combines source/output sample-rate ratio and pitch. Looping uses the sample's valid loop interval, or the full sample when no valid interval is present. Loop steps may cross multiple repetitions; finite positive pitch must not accidentally terminate a short loop or produce an infinite position.
### 5.2 Command Surface
Unloading or replacing a bank does not interrupt a sample already retained by an admitted command or mixer voice. New plays resolve the current bank. Memory can remain retained until the command is cancelled or the playback ends, stops, is replaced, or its session ends. The driver must not retain a second sample reference indefinitely after the mixer observes natural completion.
Representative command surface:
## 7 Host responsibilities and evidence
```text
audio.play(sample, voice, volume, pan, pitch, priority)
audio.stop(voice)
audio.setVolume(voice, value)
audio.setPan(voice, value)
audio.setPitch(voice, value)
audio.isPlaying(voice)
```
The desktop host consumes batches, mixes PCM and schedules the physical output. If no output device is available, it consumes committed batches silently. A failed or stalled device is diagnosed and detached so pending publication cannot block the guest indefinitely. The desktop implementation treats two seconds without callback progress as a stalled output.
## 6 Pitch and Interpolation
- `rate = 1.0` → normal speed
- `rate > 1.0` → higher pitch
- `rate < 1.0` → lower pitch
As position becomes fractional:
- **linear interpolation** is used between two neighboring samples
## 7 Mixer
For each output frame (48kHz):
1. For each active voice:
- read sample at current position
- apply pitch
- apply volume
- apply pan → generates L/R
2. Sum all voices
3. Apply clamp
4. Write to the stereo buffer
Cost depends on:
- number of active voices
- use of interpolation
## 8 Synchronization with the Game
- Game runs at **60Hz**
- Audio generates data at **48kHz**
Every frame (60Hz):
- game sends commands:
- play
- stop
- set_volume
- set_pan
- set_pitch
The audio applies these commands and continues playing.
## 9 Host Responsibilities
The PROMETEU machine defines the audio model, commands, and limits.
The host is responsible for:
- choosing the concrete audio backend;
- scheduling buffer delivery;
- keeping PCM output continuous without changing logical behavior.
## 10 Audio and CAP
Audio participates in the Execution CAP:
- mixing cost per frame
- cost per active voice
- command cost
Example:
```
Frame 1024:
voices_active: 9
mix_cycles: 410
audio_commands: 6
```
## 11 Syscall Return and Fault Policy
`audio` follows status-first policy for operations with operational failure modes.
Fault boundary:
- `Trap`: structural ABI misuse (type/arity/capability/shape mismatch);
- `status`: operational failure;
- `Panic`: internal invariant break only.
### 11.1 MVP return shape
In the current MVP:
- `audio.play` returns `status:int`;
- `audio.play_sample` returns `status:int`.
ABI `audio.play`:
1. `bank_id: int` — index of the sound bank
2. `sample_id: int` — index of the sample within the bank
3. `voice_id: int` — index of the voice to use (0..15)
4. `volume: int` — volume level (0..255)
5. `pan: int` — panning (0..255)
6. `pitch: float` — playback rate
7. `loop_mode: int` — `0` for Off, `1` for On
Return-shape matrix in v1 syscall surface:
| Syscall | Return | Policy basis |
| --------------------- | ------------ | -------------------------------------- |
| `audio.play` | `status:int` | operational rejection is observable |
| `audio.play_sample` | `status:int` | operational rejection is observable |
### 11.2 Minimum status table for `play`/`play_sample`
- `0` = `OK`
- `1` = `VOICE_INVALID`
- `2` = `SAMPLE_NOT_FOUND`
- `3` = `ARG_RANGE_INVALID`
- `5` = `NO_EFFECT`
- `6` = `BANK_INVALID`
Operational rules:
- no fallback to default bank when a bank id cannot be resolved;
- no silent no-op for invalid `voice_id`;
- invalid `voice_id` must return `VOICE_INVALID`, not `ARG_RANGE_INVALID`;
- invalid numeric ranges (e.g. `volume`, `pan`, `pitch`) must return explicit status.
Headless execution consumes committed batches silently and preserves incomplete frame/callback staging. It validates admission and runtime behavior, without proving audible output. Synthetic mixer tests establish signal behavior; a real device smoke establishes stream initialization and callback consumption, while listening remains a separate observation. Bit-identical PCM across physical devices is not required.