From 1e11c224934f8e8cc98ba44cd4735b714beabd1f Mon Sep 17 00:00:00 2001 From: Theron Date: Thu, 19 Dec 2019 18:35:14 -0600 Subject: [PATCH] apu --- src/apu/mod.rs | 2 +- src/audio.rs | 13 ++++++++++--- src/main.rs | 8 ++++++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/apu/mod.rs b/src/apu/mod.rs index 4d4640b..bda4666 100644 --- a/src/apu/mod.rs +++ b/src/apu/mod.rs @@ -81,7 +81,7 @@ impl Apu { } } - pub fn step(&mut self) -> Option { + pub fn clock(&mut self) -> Option { let mut sample = None; if (self.frame_counter == 4 && FRAME_COUNTER_STEPS[..4].contains(&self.cycle)) diff --git a/src/audio.rs b/src/audio.rs index 9c7d470..e986c72 100644 --- a/src/audio.rs +++ b/src/audio.rs @@ -3,7 +3,7 @@ extern crate sdl2; use sdl2::audio::{AudioCallback, AudioSpecDesired}; pub struct Speaker { - buffer: Vec, + buffer: [f32; 4096*4], head: usize, } @@ -13,7 +13,14 @@ impl AudioCallback for Speaker { for (i, x) in out.iter_mut().enumerate() { *x = self.buffer[i+self.head]; // get data from apu } - self.buffer = self.buffer[4096..].to_vec(); + self.head = (self.head + 4096) % (4096*4) + } +} + +impl Speaker { + pub fn append(&mut self, sample: f32) { + self.buffer[self.head] = sample; + self.head = (self.head + 1) % (4096*4); } } @@ -31,6 +38,6 @@ pub fn initialize(context: &sdl2::Sdl) -> Result Result<(), String> { let mut screen_buffer = vec![0; byte_width * byte_height]; // contains raw RGB data for the screen // Set up audio - let mut speaker = audio::initialize(&sdl_context).expect("Could not create audio device"); + let mut audio_device = audio::initialize(&sdl_context).expect("Could not create audio device"); let mut half_cycle = false; + audio_device.resume(); // Initialize hardware components let cart = Cartridge::new(); @@ -64,7 +65,10 @@ fn main() -> Result<(), String> { } } for _ in 0..apu_cycles { - cpu.apu.step(); + match cpu.apu.clock() { + Some(sample) => audio_device.speaker.append(sample), + None => (), + } } // clock PPU three times for every CPU cycle for _ in 0..cpu_cycles * 3 {