feat(audio): add guest voice controls and reliable lifecycle delivery
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
This commit is contained in:
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user