Skip to content

Commit

Permalink
Fix laggy audio
Browse files Browse the repository at this point in the history
  • Loading branch information
tomm committed Sep 26, 2023
1 parent f941db4 commit cec4c01
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
16 changes: 16 additions & 0 deletions src/audio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use sdl2::audio::AudioCallback;

#[allow(non_snake_case)]
pub struct VdpAudioStream {
pub getAudioSamples: libloading::Symbol<'static, unsafe extern fn(out: *mut u8, length: u32)>,
}

impl AudioCallback for VdpAudioStream {
type Channel = u8;

fn callback(&mut self, out: &mut[u8]) {
unsafe {
(*self.getAudioSamples)(&mut out[0] as *mut u8, out.len() as u32);
}
}
}
25 changes: 11 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use crate::parse_args::parse_args;
mod sdl2ps2;
mod parse_args;
mod vdp_interface;
mod audio;

const AUDIO_BUFLEN: usize = 2000;
const AUDIO_BUFLEN: u16 = 256;

pub fn main() -> Result<(), pico_args::Error> {
let args = parse_args()?;
Expand Down Expand Up @@ -100,20 +101,24 @@ pub fn main() -> Result<(), pico_args::Error> {
let desired_spec = sdl2::audio::AudioSpecDesired {
freq: Some(16384), // real VDP uses 16384Hz
channels: Some(1),
samples: None,
samples: Some(AUDIO_BUFLEN),
};

let device: sdl2::audio::AudioQueue<u8> = audio_subsystem.open_queue(None, &desired_spec).unwrap();
device.resume();
let audio_device = audio_subsystem.open_playback(None, &desired_spec, |_spec| {
audio::VdpAudioStream {
getAudioSamples: vdp_interface.getAudioSamples
}
}).unwrap();

// start playback
audio_device.resume();

let mut is_fullscreen = args.fullscreen;
// large enough for any agon video mode
let mut vgabuf: Vec<u8> = Vec::with_capacity(1024*768*3);
unsafe { vgabuf.set_len(1024*768*3); }
let mut mode_w: u32 = 640;
let mut mode_h: u32 = 480;
let mut audio_buf: Vec<u8> = Vec::with_capacity(AUDIO_BUFLEN);
unsafe { audio_buf.set_len(AUDIO_BUFLEN); }

'running: loop {

Expand Down Expand Up @@ -171,14 +176,6 @@ pub fn main() -> Result<(), pico_args::Error> {
last_frame_time = std::time::Instant::now();
}

// fill audio buffer
if device.size() < AUDIO_BUFLEN as u32 {
unsafe {
(*vdp_interface.getAudioSamples)(&mut audio_buf[0] as *mut u8, AUDIO_BUFLEN as u32);
};
device.queue_audio(&audio_buf).unwrap();
}

// Present a frame
last_frame_time = last_frame_time.checked_add(frame_duration).unwrap_or(std::time::Instant::now());

Expand Down

0 comments on commit cec4c01

Please sign in to comment.