Add audio, fix timing

This commit is contained in:
2024-11-04 09:59:58 -05:00
parent 8bba7b9e1b
commit 70373647fb
6 changed files with 597 additions and 17 deletions
+46 -9
View File
@@ -1,29 +1,60 @@
use std::{
fs,
path::Path,
path::{Path, PathBuf},
sync::mpsc::{self, TryRecvError},
};
use anyhow::Result;
use crate::{renderer::GameRenderer, shrooms_vb_core::CoreVB};
use crate::{audio::Audio, renderer::GameRenderer, shrooms_vb_core::CoreVB};
pub struct EmulatorBuilder {
rom: Option<PathBuf>,
commands: mpsc::Receiver<EmulatorCommand>,
}
impl EmulatorBuilder {
pub fn new() -> (Self, EmulatorClient) {
let (queue, commands) = mpsc::channel();
let builder = Self {
rom: None,
commands,
};
let client = EmulatorClient { queue };
(builder, client)
}
pub fn with_rom(self, path: &Path) -> Self {
Self {
rom: Some(path.into()),
..self
}
}
pub fn build(self) -> Result<Emulator> {
let mut emulator = Emulator::new(self.commands)?;
if let Some(path) = self.rom {
emulator.load_rom(&path)?;
}
Ok(emulator)
}
}
pub struct Emulator {
sim: CoreVB,
audio: Audio,
commands: mpsc::Receiver<EmulatorCommand>,
renderer: Option<GameRenderer>,
}
impl Emulator {
pub fn new() -> (Self, EmulatorClient) {
let (sink, source) = mpsc::channel();
let emu = Emulator {
fn new(commands: mpsc::Receiver<EmulatorCommand>) -> Result<Self> {
Ok(Self {
sim: CoreVB::new(),
commands: source,
audio: Audio::init()?,
commands,
renderer: None,
};
let queue = EmulatorClient { queue: sink };
(emu, queue)
})
}
pub fn load_rom(&mut self, path: &Path) -> Result<()> {
@@ -34,6 +65,7 @@ impl Emulator {
pub fn run(&mut self) {
let mut eye_contents = vec![0u8; 384 * 224 * 2];
let mut audio_samples = vec![];
loop {
self.sim.emulate_frame();
if let Some(renderer) = &mut self.renderer {
@@ -41,6 +73,11 @@ impl Emulator {
renderer.render(&eye_contents);
}
}
self.sim.read_samples(&mut audio_samples);
if !audio_samples.is_empty() {
self.audio.update(&audio_samples);
audio_samples.clear();
}
loop {
match self.commands.try_recv() {
Ok(command) => self.handle_command(command),