core: Start working on a scheduler

A more robust cycle aware event scheduling, to easily implement serial-io, dmg audio channels and improve accuracy.
This brings a slight performance hit :/

I also ran dos2unix on some of the files :D


Former-commit-id: 62f4ba33e3a083b7976d6512ba6f5720ec493aa0
Former-commit-id: a4b3a92cd1eb156bbe9fd0ef77fbb0e7a45660cb
This commit is contained in:
Michel Heily 2020-10-03 22:09:38 +03:00 committed by MishMish
parent b68c73819a
commit 0de8a60006
9 changed files with 1113 additions and 634 deletions

View file

@ -11,13 +11,14 @@ use super::dma::DmaController;
use super::gpu::*; use super::gpu::*;
use super::interrupt::*; use super::interrupt::*;
use super::iodev::*; use super::iodev::*;
use super::sched::{EventHandler, EventType, Scheduler, SharedScheduler};
use super::sound::SoundController; use super::sound::SoundController;
use super::sysbus::SysBus; use super::sysbus::SysBus;
use super::timer::Timers; use super::timer::Timers;
use super::{AudioInterface, InputInterface};
#[cfg(not(feature = "no_video_interface"))] #[cfg(not(feature = "no_video_interface"))]
use super::VideoInterface; use super::VideoInterface;
use super::{AudioInterface, InputInterface};
pub struct GameBoyAdvance { pub struct GameBoyAdvance {
pub sysbus: Box<SysBus>, pub sysbus: Box<SysBus>,
@ -30,6 +31,8 @@ pub struct GameBoyAdvance {
pub cycles_to_next_event: usize, pub cycles_to_next_event: usize,
scheduler: SharedScheduler,
overshoot_cycles: usize, overshoot_cycles: usize,
interrupt_flags: SharedInterruptFlags, interrupt_flags: SharedInterruptFlags,
} }
@ -37,6 +40,7 @@ pub struct GameBoyAdvance {
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct SaveState { struct SaveState {
sysbus: Box<SysBus>, sysbus: Box<SysBus>,
scheduler: Scheduler,
interrupt_flags: u16, interrupt_flags: u16,
cpu: arm7tdmi::Core, cpu: arm7tdmi::Core,
} }
@ -58,8 +62,7 @@ impl GameBoyAdvance {
pub fn new( pub fn new(
bios_rom: Box<[u8]>, bios_rom: Box<[u8]>,
gamepak: Cartridge, gamepak: Cartridge,
#[cfg(not(feature = "no_video_interface"))] #[cfg(not(feature = "no_video_interface"))] video_device: Rc<RefCell<dyn VideoInterface>>,
video_device: Rc<RefCell<dyn VideoInterface>>,
audio_device: Rc<RefCell<dyn AudioInterface>>, audio_device: Rc<RefCell<dyn AudioInterface>>,
input_device: Rc<RefCell<dyn InputInterface>>, input_device: Rc<RefCell<dyn InputInterface>>,
) -> GameBoyAdvance { ) -> GameBoyAdvance {
@ -70,12 +73,14 @@ impl GameBoyAdvance {
}; };
let interrupt_flags = Rc::new(Cell::new(IrqBitmask(0))); let interrupt_flags = Rc::new(Cell::new(IrqBitmask(0)));
let scheduler = Scheduler::new_shared();
let intc = InterruptController::new(interrupt_flags.clone()); let intc = InterruptController::new(interrupt_flags.clone());
let gpu = Box::new(Gpu::new(interrupt_flags.clone())); let gpu = Box::new(Gpu::new(scheduler.clone(), interrupt_flags.clone()));
let dmac = DmaController::new(interrupt_flags.clone()); let dmac = DmaController::new(interrupt_flags.clone());
let timers = Timers::new(interrupt_flags.clone()); let timers = Timers::new(interrupt_flags.clone());
let sound_controller = Box::new(SoundController::new( let sound_controller = Box::new(SoundController::new(
scheduler.clone(),
audio_device.borrow().get_sample_rate() as f32, audio_device.borrow().get_sample_rate() as f32,
)); ));
let io = IoDevices::new(intc, gpu, dmac, timers, sound_controller); let io = IoDevices::new(intc, gpu, dmac, timers, sound_controller);
@ -92,6 +97,8 @@ impl GameBoyAdvance {
audio_device: audio_device, audio_device: audio_device,
input_device: input_device, input_device: input_device,
scheduler: scheduler,
cycles_to_next_event: 1, cycles_to_next_event: 1,
overshoot_cycles: 0, overshoot_cycles: 0,
interrupt_flags: interrupt_flags, interrupt_flags: interrupt_flags,
@ -104,8 +111,7 @@ impl GameBoyAdvance {
pub fn from_saved_state( pub fn from_saved_state(
savestate: &[u8], savestate: &[u8],
#[cfg(not(feature = "no_video_interface"))] #[cfg(not(feature = "no_video_interface"))] video_device: Rc<RefCell<dyn VideoInterface>>,
video_device: Rc<RefCell<dyn VideoInterface>>,
audio_device: Rc<RefCell<dyn AudioInterface>>, audio_device: Rc<RefCell<dyn AudioInterface>>,
input_device: Rc<RefCell<dyn InputInterface>>, input_device: Rc<RefCell<dyn InputInterface>>,
) -> bincode::Result<GameBoyAdvance> { ) -> bincode::Result<GameBoyAdvance> {
@ -114,7 +120,10 @@ impl GameBoyAdvance {
let arm7tdmi = decoded.cpu; let arm7tdmi = decoded.cpu;
let mut sysbus = decoded.sysbus; let mut sysbus = decoded.sysbus;
let interrupts = Rc::new(Cell::new(IrqBitmask(decoded.interrupt_flags))); let interrupts = Rc::new(Cell::new(IrqBitmask(decoded.interrupt_flags)));
let scheduler = decoded.scheduler.make_shared();
sysbus.io.gpu.set_scheduler(scheduler.clone());
sysbus.io.sound.set_scheduler(scheduler.clone());
sysbus.io.connect_irq(interrupts.clone()); sysbus.io.connect_irq(interrupts.clone());
Ok(GameBoyAdvance { Ok(GameBoyAdvance {
@ -131,6 +140,8 @@ impl GameBoyAdvance {
cycles_to_next_event: 1, cycles_to_next_event: 1,
overshoot_cycles: 0, overshoot_cycles: 0,
scheduler: scheduler,
}) })
} }
@ -139,6 +150,7 @@ impl GameBoyAdvance {
cpu: self.cpu.clone(), cpu: self.cpu.clone(),
sysbus: self.sysbus.clone(), sysbus: self.sysbus.clone(),
interrupt_flags: self.interrupt_flags.get().value(), interrupt_flags: self.interrupt_flags.get().value(),
scheduler: (*self.scheduler).clone(),
}; };
bincode::serialize(&s) bincode::serialize(&s)
@ -149,10 +161,13 @@ impl GameBoyAdvance {
self.cpu = decoded.cpu; self.cpu = decoded.cpu;
self.sysbus = decoded.sysbus; self.sysbus = decoded.sysbus;
self.scheduler = Scheduler::make_shared(decoded.scheduler);
self.interrupt_flags = Rc::new(Cell::new(IrqBitmask(decoded.interrupt_flags))); self.interrupt_flags = Rc::new(Cell::new(IrqBitmask(decoded.interrupt_flags)));
// Redistribute shared pointer for interrupts // Redistribute shared pointers
self.sysbus.io.connect_irq(self.interrupt_flags.clone()); self.sysbus.io.connect_irq(self.interrupt_flags.clone());
self.sysbus.io.gpu.set_scheduler(self.scheduler.clone());
self.sysbus.io.sound.set_scheduler(self.scheduler.clone());
self.cycles_to_next_event = 1; self.cycles_to_next_event = 1;
@ -177,10 +192,12 @@ impl GameBoyAdvance {
pub fn frame(&mut self) { pub fn frame(&mut self) {
self.key_poll(); self.key_poll();
let mut scheduler = self.scheduler.clone();
let mut remaining_cycles = CYCLES_FULL_REFRESH - self.overshoot_cycles; let mut remaining_cycles = CYCLES_FULL_REFRESH - self.overshoot_cycles;
while remaining_cycles > 0 { while remaining_cycles > 0 {
let cycles = self.step(); let cycles = self.step(&mut scheduler);
if remaining_cycles >= cycles { if remaining_cycles >= cycles {
remaining_cycles -= cycles; remaining_cycles -= cycles;
} else { } else {
@ -228,15 +245,15 @@ impl GameBoyAdvance {
self.cpu.cycles - previous_cycles self.cpu.cycles - previous_cycles
} }
pub fn step(&mut self) -> usize { pub fn step(&mut self, scheduler: &mut Scheduler) -> usize {
// I hate myself for doing this, but rust left me no choice. // I hate myself for doing this, but rust left me no choice.
let io = unsafe { let io = unsafe {
let ptr = &mut *self.sysbus as *mut SysBus; let ptr = &mut *self.sysbus as *mut SysBus;
&mut (*ptr).io as &mut IoDevices &mut (*ptr).io as &mut IoDevices
}; };
let mut cycles_left = self.cycles_to_next_event; let available_cycles = self.scheduler.get_cycles_to_next_event();
let mut cycles_to_next_event = std::usize::MAX; let mut cycles_left = available_cycles;
let mut cycles = 0; let mut cycles = 0;
while cycles_left > 0 { while cycles_left > 0 {
@ -259,18 +276,9 @@ impl GameBoyAdvance {
cycles_left -= _cycles; cycles_left -= _cycles;
} }
// update gpu & sound
io.timers.update(cycles, &mut self.sysbus); io.timers.update(cycles, &mut self.sysbus);
io.gpu.update(
cycles, scheduler.run(cycles, self);
&mut cycles_to_next_event,
self.sysbus.as_mut(),
#[cfg(not(feature = "no_video_interface"))]
&self.video_device,
);
io.sound
.update(cycles, &mut cycles_to_next_event, &self.audio_device);
self.cycles_to_next_event = cycles_to_next_event;
cycles cycles
} }
@ -293,17 +301,11 @@ impl GameBoyAdvance {
let cycles = self.step_cpu(io); let cycles = self.step_cpu(io);
let breakpoint = self.check_breakpoint(); let breakpoint = self.check_breakpoint();
let mut _ignored = 0;
// update gpu & sound
io.timers.update(cycles, &mut self.sysbus); io.timers.update(cycles, &mut self.sysbus);
io.gpu.update(
cycles, // update gpu & sound
&mut _ignored, let mut scheduler = self.scheduler.clone();
self.sysbus.as_mut(), scheduler.run(cycles, self);
#[cfg(not(feature = "no_video_interface"))]
&self.video_device,
);
io.sound.update(cycles, &mut _ignored, &self.audio_device);
breakpoint breakpoint
} }
@ -320,6 +322,25 @@ impl GameBoyAdvance {
} }
} }
impl EventHandler for GameBoyAdvance {
fn handle_event(&mut self, event: EventType, extra_cycles: usize) {
let io = unsafe {
let ptr = &mut *self.sysbus as *mut SysBus;
&mut (*ptr).io as &mut IoDevices
};
match event {
EventType::Gpu(event) => io.gpu.on_event(
event,
extra_cycles,
self.sysbus.as_mut(),
#[cfg(not(feature = "no_video_interface"))]
&self.video_device,
),
EventType::Apu(event) => io.sound.on_event(event, extra_cycles, &self.audio_device),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -337,6 +358,7 @@ mod tests {
} }
} }
#[cfg(not(feature = "no_video_interface"))]
impl VideoInterface for DummyInterface {} impl VideoInterface for DummyInterface {}
impl AudioInterface for DummyInterface {} impl AudioInterface for DummyInterface {}
impl InputInterface for DummyInterface {} impl InputInterface for DummyInterface {}
@ -350,8 +372,14 @@ mod tests {
.build() .build()
.unwrap(); .unwrap();
let dummy = Rc::new(RefCell::new(DummyInterface::new())); let dummy = Rc::new(RefCell::new(DummyInterface::new()));
let mut gba = let mut gba = GameBoyAdvance::new(
GameBoyAdvance::new(bios, cartridge, dummy.clone(), dummy.clone(), dummy.clone()); bios,
cartridge,
#[cfg(not(feature = "no_video_interface"))]
dummy.clone(),
dummy.clone(),
dummy.clone(),
);
gba.skip_bios(); gba.skip_bios();
gba gba

View file

@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize};
use super::bus::*; use super::bus::*;
use super::dma::{DmaNotifer, TIMING_HBLANK, TIMING_VBLANK}; use super::dma::{DmaNotifer, TIMING_HBLANK, TIMING_VBLANK};
use super::interrupt::{self, Interrupt, InterruptConnect, SharedInterruptFlags}; use super::interrupt::{self, Interrupt, InterruptConnect, SharedInterruptFlags};
use super::sched::*;
pub use super::sysbus::consts::*; pub use super::sysbus::consts::*;
use super::util::BoxedMemory; use super::util::BoxedMemory;
#[cfg(not(feature = "no_video_interface"))] #[cfg(not(feature = "no_video_interface"))]
@ -183,6 +184,11 @@ pub struct Gpu {
pub state: GpuState, pub state: GpuState,
interrupt_flags: SharedInterruptFlags, interrupt_flags: SharedInterruptFlags,
/// When deserializing this struct using serde, make sure to call Gpu:::set_scheduler
#[serde(skip)]
#[serde(default = "Scheduler::new_shared")]
scheduler: SharedScheduler,
/// how many cycles left until next gpu state ? /// how many cycles left until next gpu state ?
cycles_left_for_current_state: usize, cycles_left_for_current_state: usize,
@ -224,9 +230,11 @@ impl InterruptConnect for Gpu {
} }
impl Gpu { impl Gpu {
pub fn new(interrupt_flags: SharedInterruptFlags) -> Gpu { pub fn new(mut scheduler: SharedScheduler, interrupt_flags: SharedInterruptFlags) -> Gpu {
scheduler.add_gpu_event(GpuEvent::HDraw, CYCLES_HDRAW);
Gpu { Gpu {
interrupt_flags, interrupt_flags,
scheduler,
dispcnt: DisplayControl(0x80), dispcnt: DisplayControl(0x80),
dispstat: DisplayStatus(0), dispstat: DisplayStatus(0),
backgrounds: [ backgrounds: [
@ -261,6 +269,10 @@ impl Gpu {
} }
} }
pub fn set_scheduler(&mut self, scheduler: SharedScheduler) {
self.scheduler = scheduler;
}
pub fn write_dispcnt(&mut self, value: u16) { pub fn write_dispcnt(&mut self, value: u16) {
let new_dispcnt = DisplayControl(value); let new_dispcnt = DisplayControl(value);
let old_mode = self.dispcnt.mode(); let old_mode = self.dispcnt.mode();
@ -414,6 +426,93 @@ impl Gpu {
&self.frame_buffer &self.frame_buffer
} }
#[inline]
fn update_vcount(&mut self, value: usize) {
self.vcount = value;
let vcount_setting = self.dispstat.vcount_setting();
self.dispstat
.set_vcount_flag(vcount_setting == self.vcount as u16);
if self.dispstat.vcount_irq_enable() && self.dispstat.get_vcount_flag() {
interrupt::signal_irq(&self.interrupt_flags, Interrupt::LCD_VCounterMatch);
}
}
#[inline]
fn handle_hdraw<D: DmaNotifer>(&mut self, dma_notifier: &mut D) -> (GpuEvent, usize) {
self.dispstat.set_hblank_flag(true);
if self.dispstat.hblank_irq_enable() {
interrupt::signal_irq(&self.interrupt_flags, Interrupt::LCD_HBlank);
};
dma_notifier.notify(TIMING_HBLANK);
// Next event
(GpuEvent::HBlank, CYCLES_HBLANK)
}
fn handle_hblank<D: DmaNotifer>(
&mut self,
dma_notifier: &mut D,
#[cfg(not(feature = "no_video_interface"))] video_device: &VideoDeviceRcRefCell,
) -> (GpuEvent, usize) {
self.update_vcount(self.vcount + 1);
if self.vcount < DISPLAY_HEIGHT {
self.dispstat.set_hblank_flag(false);
self.render_scanline();
// update BG2/3 reference points on the end of a scanline
for i in 0..2 {
self.bg_aff[i].internal_x += self.bg_aff[i].pb as i16 as i32;
self.bg_aff[i].internal_y += self.bg_aff[i].pd as i16 as i32;
}
(GpuEvent::HDraw, CYCLES_HDRAW)
} else {
// latch BG2/3 reference points on vblank
for i in 0..2 {
self.bg_aff[i].internal_x = self.bg_aff[i].x;
self.bg_aff[i].internal_y = self.bg_aff[i].y;
}
self.dispstat.set_vblank_flag(true);
self.dispstat.set_hblank_flag(false);
if self.dispstat.vblank_irq_enable() {
interrupt::signal_irq(&self.interrupt_flags, Interrupt::LCD_VBlank);
};
dma_notifier.notify(TIMING_VBLANK);
#[cfg(not(feature = "no_video_interface"))]
video_device.borrow_mut().render(&self.frame_buffer);
self.obj_buffer_reset();
(GpuEvent::VBlankHDraw, CYCLES_HDRAW)
}
}
fn handle_vblank_hdraw(&mut self) -> (GpuEvent, usize) {
self.dispstat.set_hblank_flag(true);
if self.dispstat.hblank_irq_enable() {
interrupt::signal_irq(&self.interrupt_flags, Interrupt::LCD_HBlank);
};
(GpuEvent::VBlankHBlank, CYCLES_HBLANK)
}
fn handle_vblank_hblank(&mut self) -> (GpuEvent, usize) {
if self.vcount < DISPLAY_HEIGHT + VBLANK_LINES - 1 {
self.update_vcount(self.vcount + 1);
self.dispstat.set_hblank_flag(false);
(GpuEvent::VBlankHDraw, CYCLES_HDRAW)
} else {
self.update_vcount(0);
self.dispstat.set_vblank_flag(false);
self.dispstat.set_hblank_flag(false);
self.render_scanline();
(GpuEvent::HDraw, CYCLES_HDRAW)
}
}
pub fn on_state_completed<D>( pub fn on_state_completed<D>(
&mut self, &mut self,
completed: GpuState, completed: GpuState,
@ -440,12 +539,8 @@ impl Gpu {
// Transition to HBlank // Transition to HBlank
self.state = HBlank; self.state = HBlank;
self.cycles_left_for_current_state = CYCLES_HBLANK; self.cycles_left_for_current_state = CYCLES_HBLANK;
self.dispstat.set_hblank_flag(true);
if self.dispstat.hblank_irq_enable() { self.handle_hdraw(dma_notifier);
interrupt::signal_irq(&self.interrupt_flags, Interrupt::LCD_HBlank);
};
dma_notifier.notify(TIMING_HBLANK);
} }
HBlank => { HBlank => {
update_vcount!(self.vcount + 1); update_vcount!(self.vcount + 1);
@ -538,6 +633,29 @@ impl Gpu {
*cycles_to_next_event = self.cycles_left_for_current_state; *cycles_to_next_event = self.cycles_left_for_current_state;
} }
} }
pub fn on_event<D>(
&mut self,
event: GpuEvent,
extra_cycles: usize,
dma_notifier: &mut D,
#[cfg(not(feature = "no_video_interface"))] video_device: &VideoDeviceRcRefCell,
) where
D: DmaNotifer,
{
let (next_event, cycles) = match event {
GpuEvent::HDraw => self.handle_hdraw(dma_notifier),
GpuEvent::HBlank => self.handle_hblank(
dma_notifier,
#[cfg(not(feature = "no_video_interface"))]
video_device,
),
GpuEvent::VBlankHDraw => self.handle_vblank_hdraw(),
GpuEvent::VBlankHBlank => self.handle_vblank_hblank(),
};
self.scheduler
.schedule(EventType::Gpu(next_event), cycles - extra_cycles);
}
} }
impl Bus for Gpu { impl Bus for Gpu {
@ -625,6 +743,7 @@ mod tests {
frame_counter: usize, frame_counter: usize,
} }
#[cfg(not(feature = "no_video_interface"))]
impl VideoInterface for TestVideoInterface { impl VideoInterface for TestVideoInterface {
fn render(&mut self, _buffer: &[u32]) { fn render(&mut self, _buffer: &[u32]) {
self.frame_counter += 1; self.frame_counter += 1;
@ -633,8 +752,13 @@ mod tests {
#[test] #[test]
fn test_gpu_state_machine() { fn test_gpu_state_machine() {
let mut gpu = Gpu::new(Rc::new(Cell::new(Default::default()))); let mut gpu = Gpu::new(
Scheduler::new_shared(),
Rc::new(Cell::new(Default::default())),
);
#[cfg(not(feature = "no_video_interface"))]
let video = Rc::new(RefCell::new(TestVideoInterface::default())); let video = Rc::new(RefCell::new(TestVideoInterface::default()));
#[cfg(not(feature = "no_video_interface"))]
let video_clone: VideoDeviceRcRefCell = video.clone(); let video_clone: VideoDeviceRcRefCell = video.clone();
let mut dma_notifier = NopDmaNotifer; let mut dma_notifier = NopDmaNotifer;
let mut cycles_to_next_event = CYCLES_FULL_REFRESH; let mut cycles_to_next_event = CYCLES_FULL_REFRESH;
@ -659,6 +783,7 @@ mod tests {
for line in 0..160 { for line in 0..160 {
println!("line = {}", line); println!("line = {}", line);
#[cfg(not(feature = "no_video_interface"))]
assert_eq!(video.borrow().frame_counter, 0); assert_eq!(video.borrow().frame_counter, 0);
assert_eq!(gpu.vcount, line); assert_eq!(gpu.vcount, line);
assert_eq!(gpu.state, GpuState::HDraw); assert_eq!(gpu.state, GpuState::HDraw);
@ -676,6 +801,7 @@ mod tests {
assert_eq!(gpu.interrupt_flags.get().LCD_VCounterMatch(), false); assert_eq!(gpu.interrupt_flags.get().LCD_VCounterMatch(), false);
} }
#[cfg(not(feature = "no_video_interface"))]
assert_eq!(video.borrow().frame_counter, 1); assert_eq!(video.borrow().frame_counter, 1);
for line in 0..68 { for line in 0..68 {
@ -694,6 +820,7 @@ mod tests {
update!(CYCLES_HBLANK); update!(CYCLES_HBLANK);
} }
#[cfg(not(feature = "no_video_interface"))]
assert_eq!(video.borrow().frame_counter, 1); assert_eq!(video.borrow().frame_counter, 1);
assert_eq!(total_cycles, CYCLES_FULL_REFRESH); assert_eq!(total_cycles, CYCLES_FULL_REFRESH);

View file

@ -40,6 +40,7 @@ pub mod arm7tdmi;
pub mod cartridge; pub mod cartridge;
pub mod disass; pub mod disass;
pub mod gpu; pub mod gpu;
mod sched;
pub mod sound; pub mod sound;
pub mod sysbus; pub mod sysbus;
pub use sysbus::SysBus; pub use sysbus::SysBus;

305
core/src/sched.rs Normal file
View file

@ -0,0 +1,305 @@
use std::cell::UnsafeCell;
use std::rc::Rc;
use serde::{Deserialize, Serialize};
const NUM_EVENTS: usize = 32;
#[repr(u32)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub enum GpuEvent {
HDraw,
HBlank,
VBlankHDraw,
VBlankHBlank,
}
#[repr(u32)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub enum ApuEvent {
Psg1Generate,
Psg2Generate,
Psg3Generate,
Psg4Generate,
Sample,
}
#[repr(u32)]
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub enum EventType {
Gpu(GpuEvent),
Apu(ApuEvent),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Event {
typ: EventType,
/// Timestamp in cycles
time: usize,
}
impl Event {
fn new(typ: EventType, time: usize) -> Event {
Event { typ, time }
}
fn get_type(&self) -> EventType {
self.typ
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Scheduler {
timestamp: usize,
events: Vec<Event>,
}
// Opt-out of runtime borrow checking by using unsafe cell
// SAFETY: We need to make sure that the scheduler event queue is not modified while iterating it.
#[repr(transparent)]
#[derive(Debug)]
pub struct SharedScheduler(Rc<UnsafeCell<Scheduler>>);
impl std::ops::Deref for SharedScheduler {
type Target = Scheduler;
fn deref(&self) -> &Self::Target {
unsafe { &(*self.0.get()) }
}
}
impl std::ops::DerefMut for SharedScheduler {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut (*self.0.get()) }
}
}
impl Clone for SharedScheduler {
fn clone(&self) -> SharedScheduler {
SharedScheduler(self.0.clone())
}
}
pub trait EventHandler {
/// Handle the scheduler event
fn handle_event(&mut self, e: EventType, extra_cycles: usize);
}
impl Scheduler {
pub fn new_shared() -> SharedScheduler {
let sched = Scheduler {
timestamp: 0,
events: Vec::with_capacity(NUM_EVENTS),
};
SharedScheduler(Rc::new(UnsafeCell::new(sched)))
}
pub fn make_shared(self) -> SharedScheduler {
SharedScheduler(Rc::new(UnsafeCell::new(self)))
}
pub fn schedule(&mut self, typ: EventType, cycles: usize) {
let event = Event::new(typ, self.timestamp + cycles);
let idx = self
.events
.binary_search_by(|e| e.time.cmp(&event.time))
.unwrap_or_else(|x| x);
self.events.insert(idx, event);
}
pub fn add_gpu_event(&mut self, e: GpuEvent, cycles: usize) {
self.schedule(EventType::Gpu(e), cycles);
}
pub fn add_apu_event(&mut self, e: ApuEvent, cycles: usize) {
self.schedule(EventType::Apu(e), cycles);
}
pub fn run<H: EventHandler>(&mut self, cycles: usize, handler: &mut H) {
let run_to = self.timestamp + cycles;
self.timestamp = run_to;
while self.events.len() > 0 {
if run_to >= self.events[0].time {
let event = self.events.remove(0);
handler.handle_event(event.get_type(), run_to - event.time);
} else {
return;
}
}
}
pub fn get_cycles_to_next_event(&self) -> usize {
assert_ne!(self.events.len(), 0);
self.events[0].time - self.timestamp
}
#[allow(unused)]
fn is_empty(&self) -> bool {
self.events.is_empty()
}
}
#[cfg(test)]
mod test {
use super::*;
/// Some usecase example where a struct holds the scheduler
struct Holder {
sched: SharedScheduler,
event_bitmask: u32,
}
const BIT_GPU_VBLANKHDRAW: u32 = 1 << 0;
const BIT_APU_PSG1GENERATE: u32 = 1 << 1;
const BIT_APU_PSG2GENERATE: u32 = 1 << 2;
const BIT_APU_PSG3GENERATE: u32 = 1 << 3;
const BIT_APU_PSG4GENERATE: u32 = 1 << 4;
const BIT_APU_SAMPLE: u32 = 1 << 5;
#[inline]
fn get_event_bit(e: EventType) -> u32 {
match e {
EventType::Gpu(GpuEvent::VBlankHDraw) => BIT_GPU_VBLANKHDRAW,
EventType::Apu(ApuEvent::Psg1Generate) => BIT_APU_PSG1GENERATE,
EventType::Apu(ApuEvent::Psg2Generate) => BIT_APU_PSG2GENERATE,
EventType::Apu(ApuEvent::Psg3Generate) => BIT_APU_PSG3GENERATE,
EventType::Apu(ApuEvent::Psg4Generate) => BIT_APU_PSG4GENERATE,
EventType::Apu(ApuEvent::Sample) => BIT_APU_SAMPLE,
_ => unimplemented!("unsupported event for this test"),
}
}
impl Holder {
fn new() -> Holder {
Holder {
sched: Scheduler::new_shared(),
event_bitmask: 0,
}
}
fn is_event_done(&self, e: EventType) -> bool {
(self.event_bitmask & get_event_bit(e)) != 0
}
}
impl EventHandler for Holder {
fn handle_event(&mut self, e: EventType, extra_cycles: usize) {
println!("[holder] got event {:?} extra_cycles {}", e, extra_cycles);
self.event_bitmask |= get_event_bit(e);
}
}
#[test]
fn test_scheduler() {
let mut holder = Holder::new();
// clone the sched so we get a reference that is not owned by the holder
// SAFETY: since the SharedScheduler is built upon an UnsafeCell instead of RefCell, we are sacrificing runtime safety checks for performance.
// It is safe since the events iteration allows the EventHandler to modify the queue.
let mut sched = holder.sched.clone();
holder
.sched
.schedule(EventType::Gpu(GpuEvent::VBlankHDraw), 240);
holder
.sched
.schedule(EventType::Apu(ApuEvent::Psg1Generate), 60);
holder.sched.schedule(EventType::Apu(ApuEvent::Sample), 512);
holder
.sched
.schedule(EventType::Apu(ApuEvent::Psg2Generate), 13);
holder
.sched
.schedule(EventType::Apu(ApuEvent::Psg4Generate), 72);
println!("all events");
for e in sched.events.iter() {
let typ = e.get_type();
println!("{:?}", typ);
}
macro_rules! run_for {
($cycles:expr) => {
println!("running the scheduler for {} cycles", $cycles);
sched.run($cycles, &mut holder);
if (!sched.is_empty()) {
println!(
"cycles for next event: {}",
sched.get_cycles_to_next_event()
);
}
};
}
run_for!(100);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Psg1Generate)),
true
);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Psg2Generate)),
true
);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Psg4Generate)),
true
);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Sample)),
false
);
assert_eq!(
holder.is_event_done(EventType::Gpu(GpuEvent::VBlankHDraw)),
false
);
run_for!(100);
assert_eq!(
holder.is_event_done(EventType::Gpu(GpuEvent::VBlankHDraw)),
false
);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Sample)),
false
);
run_for!(100);
assert_eq!(
holder.is_event_done(EventType::Gpu(GpuEvent::VBlankHDraw)),
true
);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Sample)),
false
);
run_for!(211);
assert_eq!(
holder.is_event_done(EventType::Apu(ApuEvent::Sample)),
false
);
run_for!(1);
assert_eq!(holder.is_event_done(EventType::Apu(ApuEvent::Sample)), true);
println!("all events (holder)");
for e in holder.sched.events.iter() {
let typ = e.get_type();
println!("{:?}", typ);
}
println!("all events (cloned again)");
let sched_cloned = holder.sched.clone();
for e in sched_cloned.events.iter() {
let typ = e.get_type();
println!("{:?}", typ);
}
}
}

View file

@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize};
use super::dma::DmaController; use super::dma::DmaController;
use super::iodev::consts::*; use super::iodev::consts::*;
use super::sched::*;
use crate::{AudioInterface, StereoSample}; use crate::{AudioInterface, StereoSample};
@ -62,6 +63,10 @@ type AudioDeviceRcRefCell = Rc<RefCell<dyn AudioInterface>>;
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SoundController { pub struct SoundController {
#[serde(skip)]
#[serde(default = "Scheduler::new_shared")]
scheduler: SharedScheduler,
cycles: usize, // cycles count when we last provided a new sample. cycles: usize, // cycles count when we last provided a new sample.
mse: bool, mse: bool,
@ -101,9 +106,13 @@ pub struct SoundController {
} }
impl SoundController { impl SoundController {
pub fn new(audio_device_sample_rate: f32) -> SoundController { pub fn new(mut scheduler: SharedScheduler, audio_device_sample_rate: f32) -> SoundController {
let resampler = CosineResampler::new(32768_f32, audio_device_sample_rate); let resampler = CosineResampler::new(32768_f32, audio_device_sample_rate);
let cycles_per_sample = 512;
scheduler.schedule(EventType::Apu(ApuEvent::Sample), cycles_per_sample);
SoundController { SoundController {
scheduler,
cycles_per_sample,
cycles: 0, cycles: 0,
mse: false, mse: false,
left_volume: 0, left_volume: 0,
@ -127,7 +136,6 @@ impl SoundController {
sqr1_cur_vol: 0, sqr1_cur_vol: 0,
sound_bias: 0x200, sound_bias: 0x200,
sample_rate: 32_768f32, sample_rate: 32_768f32,
cycles_per_sample: 512,
dma_sound: [Default::default(), Default::default()], dma_sound: [Default::default(), Default::default()],
resampler: resampler, resampler: resampler,
@ -135,6 +143,10 @@ impl SoundController {
} }
} }
pub fn set_scheduler(&mut self, scheduler: SharedScheduler) {
self.scheduler = scheduler;
}
pub fn handle_read(&self, io_addr: u32) -> u16 { pub fn handle_read(&self, io_addr: u32) -> u16 {
let value = match io_addr { let value = match io_addr {
REG_SOUNDCNT_X => cbit(7, self.mse), REG_SOUNDCNT_X => cbit(7, self.mse),
@ -277,6 +289,11 @@ impl SoundController {
self.resampler.in_freq = self.sample_rate; self.resampler.in_freq = self.sample_rate;
} }
self.cycles_per_sample = 512 >> resolution; self.cycles_per_sample = 512 >> resolution;
info!(
"bias - setting sample frequency to {}hz",
self.cycles_per_sample
);
// TODO this will not affect the currently scheduled sample event
} }
_ => { _ => {
@ -317,46 +334,47 @@ impl SoundController {
} }
} }
pub fn update( #[inline]
&mut self, fn on_sample(&mut self, extra_cycles: usize, audio_device: &AudioDeviceRcRefCell) {
cycles: usize, let mut sample = [0f32; 2];
cycles_to_next_event: &mut usize,
audio_device: &AudioDeviceRcRefCell,
) {
self.cycles += cycles;
while self.cycles >= self.cycles_per_sample {
self.cycles -= self.cycles_per_sample;
// time to push a new sample! for channel in 0..=1 {
let mut dma_sample = 0;
let mut sample = [0f32; 2]; for dma in &mut self.dma_sound {
if dma.is_stereo_channel_enabled(channel) {
for channel in 0..=1 { let value = dma.value as i16;
let mut dma_sample = 0; dma_sample += value * (2 << dma.volume_shift);
for dma in &mut self.dma_sound {
if dma.is_stereo_channel_enabled(channel) {
let value = dma.value as i16;
dma_sample += value * (2 << dma.volume_shift);
}
} }
apply_bias(&mut dma_sample, self.sound_bias.bit_range(0..10) as i16);
sample[channel] = dma_sample as i32 as f32;
} }
let stereo_sample = (sample[0], sample[1]); apply_bias(&mut dma_sample, self.sound_bias.bit_range(0..10) as i16);
self.resampler.feed(stereo_sample, &mut self.output_buffer); sample[channel] = dma_sample as i32 as f32;
let mut audio = audio_device.borrow_mut();
self.output_buffer.drain(..).for_each(|(left, right)| {
audio.push_sample(&[
(left.round() as i16) * (std::i16::MAX / 512),
(right.round() as i16) * (std::i16::MAX / 512),
]);
});
} }
if self.cycles_per_sample < *cycles_to_next_event {
*cycles_to_next_event = self.cycles_per_sample; let stereo_sample = (sample[0], sample[1]);
self.resampler.feed(stereo_sample, &mut self.output_buffer);
let mut audio = audio_device.borrow_mut();
self.output_buffer.drain(..).for_each(|(left, right)| {
audio.push_sample(&[
(left.round() as i16) * (std::i16::MAX / 512),
(right.round() as i16) * (std::i16::MAX / 512),
]);
});
self.scheduler
.add_apu_event(ApuEvent::Sample, self.cycles_per_sample - extra_cycles);
}
pub fn on_event(
&mut self,
event: ApuEvent,
extra_cycles: usize,
audio_device: &AudioDeviceRcRefCell,
) {
match event {
ApuEvent::Sample => self.on_sample(extra_cycles, audio_device),
_ => debug!("got {:?} event", event),
} }
} }
} }