Files
prometeu-runtime/crates/console/prometeu-drivers/src/memory_banks.rs
T
bquarkz 8510c5b00d feat(audio): add 32-voice PCM mixing and native music sequencing
Add self-contained SoundBanks and MusicBanks with per-sample PCM16 and IMA ADPCM storage, materialized to resident PCM16. Integrate instrument envelopes, automation, shared DSP and host lifecycle controls while preserving staged real-time execution.
2026-11-20 22:15:24 +00:00

386 lines
14 KiB
Rust

//! Memory bank access boundary.
//!
//! Render consumers must cross this boundary through small, read-only traits.
//! Frame packets carry resource IDs; large resident resources stay in banks and
//! are read in place through a narrow HAL callback contract. Installation and
//! slot replacement remain separate owner-side operations and are not part of
//! the render read surface.
use prometeu_hal::glyph_bank::GlyphBank;
use prometeu_hal::music_bank::MusicBank;
use prometeu_hal::render_resources::RenderResourceAccess as HalRenderResourceAccess;
use prometeu_hal::scene_bank::SceneBank;
use prometeu_hal::sound_bank::SoundBank;
use std::sync::{Arc, RwLock};
/// Non-generic interface for peripherals to access graphical glyph banks.
pub trait GlyphBankPoolAccess: Send + Sync {
/// Returns a reference to the resident GlyphBank in the specified slot, if any.
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>>;
/// Returns the total number of slots available in this bank.
fn glyph_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install graphical glyph banks.
pub trait GlyphBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident GlyphBank in the specified slot.
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
/// Clears all resident GlyphBank slots.
fn clear_glyph_banks(&self);
}
/// Non-generic interface for peripherals to access sound banks.
pub trait SoundBankPoolAccess: Send + Sync {
fn music_bank_slot(&self, slot: usize) -> Option<Arc<MusicBank>>;
/// Returns a reference to the resident SoundBank in the specified slot, if any.
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>>;
/// Returns the total number of slots available in this bank.
fn sound_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install sound banks.
pub trait SoundBankPoolInstaller: Send + Sync {
fn install_music_bank(&self, slot: usize, bank: Arc<MusicBank>);
fn clear_music_banks(&self);
fn unload_audio_bank(&self, music: bool, slot: usize);
/// Atomically swaps the resident SoundBank in the specified slot.
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
/// Clears all resident SoundBank slots.
fn clear_sound_banks(&self);
}
/// Non-generic interface for peripherals to access scene banks.
pub trait SceneBankPoolAccess: Send + Sync {
/// Returns a reference to the resident SceneBank in the specified slot, if any.
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>>;
/// Returns the total number of slots available in this bank.
fn scene_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install scene banks.
pub trait SceneBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident SceneBank in the specified slot.
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>);
/// Clears all resident SceneBank slots.
fn clear_scene_banks(&self);
}
/// Centralized container for all hardware memory banks.
///
/// MemoryBanks represent the actual hardware slot state.
/// Peripherals consume this state via narrow, non-generic traits.
/// AssetManager coordinates residency and installs assets into these slots.
pub struct MemoryBanks {
glyph_bank_pool: Arc<RwLock<[Option<Arc<GlyphBank>>; 16]>>,
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
music_bank_pool: Arc<RwLock<[Option<Arc<MusicBank>>; 16]>>,
scene_bank_pool: Arc<RwLock<[Option<Arc<SceneBank>>; 16]>>,
}
impl Default for MemoryBanks {
fn default() -> Self {
Self::new()
}
}
impl MemoryBanks {
/// Creates a new set of memory banks with empty slots.
pub fn new() -> Self {
Self {
glyph_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
music_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
scene_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
}
}
}
impl GlyphBankPoolAccess for MemoryBanks {
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>> {
let pool = self.glyph_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn glyph_bank_slot_count(&self) -> usize {
16
}
}
impl GlyphBankPoolInstaller for MemoryBanks {
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>) {
let mut pool = self.glyph_bank_pool.write().unwrap();
if slot < 16 {
pool[slot] = Some(bank);
}
}
fn clear_glyph_banks(&self) {
self.glyph_bank_pool.write().unwrap().fill(None);
}
}
impl SoundBankPoolAccess for MemoryBanks {
fn music_bank_slot(&self, slot: usize) -> Option<Arc<MusicBank>> {
self.music_bank_pool.read().unwrap().get(slot).and_then(Clone::clone)
}
fn sound_bank_slot(&self, slot: usize) -> Option<Arc<SoundBank>> {
let pool = self.sound_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn sound_bank_slot_count(&self) -> usize {
16
}
}
impl SoundBankPoolInstaller for MemoryBanks {
fn install_music_bank(&self, slot: usize, bank: Arc<MusicBank>) {
if slot >= 16 {
return;
}
let prepared = Arc::new(bank.resident_copy());
let mut pool = self.music_bank_pool.write().unwrap();
if let Some(target) = pool.get_mut(slot) {
if let Some(old) = target.take() {
old.invalidate();
}
*target = Some(prepared);
}
}
fn clear_music_banks(&self) {
let mut pool = self.music_bank_pool.write().unwrap();
for bank in pool.iter_mut() {
if let Some(old) = bank.take() {
old.invalidate();
}
}
}
fn unload_audio_bank(&self, music: bool, slot: usize) {
if music {
if let Some(bank) =
self.music_bank_pool.write().unwrap().get_mut(slot).and_then(Option::take)
{
bank.invalidate();
}
} else if let Some(bank) =
self.sound_bank_pool.write().unwrap().get_mut(slot).and_then(Option::take)
{
bank.invalidate();
}
}
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>) {
if slot >= 16 {
return;
}
let prepared = Arc::new(bank.resident_copy());
let mut pool = self.sound_bank_pool.write().unwrap();
if slot < 16 {
if let Some(old) = pool[slot].take() {
old.invalidate();
}
pool[slot] = Some(prepared);
}
}
fn clear_sound_banks(&self) {
let mut pool = self.sound_bank_pool.write().unwrap();
for bank in pool.iter_mut() {
if let Some(old) = bank.take() {
old.invalidate();
}
}
}
}
impl SceneBankPoolAccess for MemoryBanks {
fn scene_bank_slot(&self, slot: usize) -> Option<Arc<SceneBank>> {
let pool = self.scene_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn scene_bank_slot_count(&self) -> usize {
16
}
}
impl SceneBankPoolInstaller for MemoryBanks {
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>) {
let mut pool = self.scene_bank_pool.write().unwrap();
if slot < 16 {
pool[slot] = Some(bank);
}
}
fn clear_scene_banks(&self) {
self.scene_bank_pool.write().unwrap().fill(None);
}
}
impl HalRenderResourceAccess for MemoryBanks {
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R> {
let pool = self.glyph_bank_pool.read().unwrap();
let bank = pool.get(bank_id)?.as_deref()?;
Some(read(bank))
}
fn glyph_bank_count(&self) -> usize {
16
}
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R> {
let pool = self.scene_bank_pool.read().unwrap();
let bank = pool.get(bank_id)?.as_deref()?;
Some(read(bank))
}
fn scene_bank_count(&self) -> usize {
16
}
}
#[cfg(test)]
mod tests {
use super::*;
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::glyph_bank::TileSize;
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
use prometeu_hal::tile::Tile;
use prometeu_hal::tilemap::TileMap;
fn assert_send_sync<T: Send + Sync>() {}
fn make_glyph_bank() -> GlyphBank {
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
bank
}
fn make_scene_bank() -> SceneBank {
let layer = SceneLayer {
active: true,
glyph_asset_id: 0,
tile_size: TileSize::Size8,
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
tilemap: TileMap {
width: 1,
height: 1,
tiles: vec![Tile {
active: true,
glyph: Glyph { glyph_id: 0, palette_id: 0 },
flip_x: false,
flip_y: false,
}],
},
};
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
}
#[test]
fn render_resource_access_traits_are_thread_safe() {
assert_send_sync::<MemoryBanks>();
assert_send_sync::<Arc<dyn GlyphBankPoolAccess>>();
assert_send_sync::<Arc<dyn SceneBankPoolAccess>>();
}
#[test]
fn render_resource_access_exposes_read_only_glyph_and_scene_banks_without_arc_contract() {
let banks = MemoryBanks::new();
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
banks.install_scene_bank(1, Arc::new(make_scene_bank()));
let glyph_tile_size =
HalRenderResourceAccess::with_glyph_bank(&banks, 0, |bank| bank.tile_size);
let scene_tile_size =
HalRenderResourceAccess::with_scene_bank(&banks, 1, |bank| bank.layers[0].tile_size);
assert_eq!(glyph_tile_size, Some(TileSize::Size8));
assert_eq!(scene_tile_size, Some(TileSize::Size8));
assert_eq!(HalRenderResourceAccess::with_glyph_bank(&banks, 15, |_| ()), None);
assert_eq!(HalRenderResourceAccess::with_scene_bank(&banks, 15, |_| ()), None);
assert_eq!(HalRenderResourceAccess::glyph_bank_count(&banks), 16);
assert_eq!(HalRenderResourceAccess::scene_bank_count(&banks), 16);
}
}
/// Owner-thread diagnostics: canonical bank costs and unique PCM allocation costs
/// are separate, so loading the same asset in two slots does not double-count RAM.
#[derive(Debug, Clone)]
pub struct AudioSlotMemory {
pub music: bool,
pub slot: usize,
pub name: String,
pub metrics: prometeu_hal::sound_bank::AudioBankMetrics,
}
#[derive(Debug, Default)]
pub struct AudioMemorySnapshot {
pub banks: Vec<AudioSlotMemory>,
pub unique_pcm_bytes: usize,
pub allocated_pcm_bytes: usize,
/// Resident Rust structs/vector/string capacities; excludes allocator/Arc headers and host caches.
pub metadata_bytes: usize,
pub total_accounted_bytes: usize,
}
impl MemoryBanks {
pub fn audio_memory(&self) -> AudioMemorySnapshot {
let mut snapshot = AudioMemorySnapshot::default();
let mut seen = std::collections::HashSet::new();
let mut metadata = 0usize;
let mut vectors = std::collections::HashSet::new();
let mut add =
|music, slot, name: String, metrics, samples: &[Arc<prometeu_hal::sample::Sample>]| {
for sample in samples {
if seen.insert(Arc::as_ptr(sample)) {
metadata += std::mem::size_of::<prometeu_hal::sample::Sample>();
snapshot.unique_pcm_bytes += sample.data.len() * 2;
snapshot.allocated_pcm_bytes += sample.data.capacity() * 2;
}
}
snapshot.banks.push(AudioSlotMemory { music, slot, name, metrics });
};
for (slot, bank) in self.sound_bank_pool.read().unwrap().iter().enumerate() {
if let Some(b) = bank {
add(false, slot, b.name.clone(), b.metrics, &b.samples);
snapshot.metadata_bytes += std::mem::size_of::<SoundBank>()
+ b.name.capacity()
+ std::mem::size_of::<std::sync::atomic::AtomicBool>();
if vectors.insert(Arc::as_ptr(&b.samples) as usize) {
snapshot.metadata_bytes += std::mem::size_of::<
Vec<Arc<prometeu_hal::sample::Sample>>,
>() + b.samples.capacity()
* std::mem::size_of::<Arc<prometeu_hal::sample::Sample>>();
}
}
}
for (slot, bank) in self.music_bank_pool.read().unwrap().iter().enumerate() {
if let Some(b) = bank {
add(true, slot, b.name.clone(), b.metrics, &b.samples);
snapshot.metadata_bytes += std::mem::size_of::<MusicBank>()
+ b.name.capacity()
+ std::mem::size_of::<std::sync::atomic::AtomicBool>();
if vectors.insert(Arc::as_ptr(&b.samples) as usize) {
snapshot.metadata_bytes += std::mem::size_of::<
Vec<Arc<prometeu_hal::sample::Sample>>,
>() + b.samples.capacity()
* std::mem::size_of::<Arc<prometeu_hal::sample::Sample>>();
}
if vectors.insert(Arc::as_ptr(&b.instruments) as usize) {
snapshot.metadata_bytes += std::mem::size_of::<
Vec<prometeu_hal::music_bank::Instrument>,
>() + b.instruments.capacity()
* std::mem::size_of::<prometeu_hal::music_bank::Instrument>();
}
if vectors.insert(Arc::as_ptr(&b.events) as usize) {
snapshot.metadata_bytes += std::mem::size_of::<
Vec<prometeu_hal::music_bank::TimedMusicEvent>,
>() + b.events.capacity()
* std::mem::size_of::<prometeu_hal::music_bank::TimedMusicEvent>();
}
}
}
snapshot.metadata_bytes += metadata;
snapshot.total_accounted_bytes = snapshot.allocated_pcm_bytes + snapshot.metadata_bytes;
snapshot
}
}