A GameCube/Wii emulator and debugger written in Rust.
frame pacing
Layle32c14b03f396
diff --git a/README.md b/README.mdindex 2c8ee19..1bf3df4 100644--- a/README.md+++ b/README.md@@ -22,6 +22,7 @@ Gecko is still in development. Support may vary, while many games work very well- IPL skip patches for NTSC and PAL- `wgpu` based renderer backend- `wesl` based specialized shader compiler+- Frame pacing- Modular audio backend, defaults to `cpal`- Core speed synced to the audio rate- Supports mixing audio sinksdiff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex 1cc56b5..1893b1e 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -4,9 +4,12 @@ use crossbeam_channel::{Receiver, Sender, bounded};use gecko::host::EfbWriteback;use gecko::host::{DrawData, GxAction, RenderSink};use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, Mutex};+use std::sync::{Arc, Mutex, OnceLock};#[cfg(feature = "renderdoc-capture")]use std::time::Duration;+use std::time::Instant;++pub type FrameReadyCallback = Box<dyn Fn(Instant) + Send + Sync>;const CHANNEL_CAPACITY: usize = 65536;const RECYCLE_CAPACITY: usize = 8192;@@ -58,6 +61,7 @@ fn worker(shared: Arc<Shared>,rx: Receiver<WorkerMsg>,recyclers: Recyclers,+ frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,) {#[cfg(feature = "renderdoc-capture")]let mut renderdoc = crate::renderdoc_capture::RenderDocCapture::new();@@ -105,8 +109,11 @@ fn worker(match action {GxAction::PresentXfb { .. } => {- let mut output = shared.output.lock().unwrap();- *output = gx.xfb_view.clone();+ let view = gx.xfb_view.clone();+ *shared.output.lock().unwrap() = view;+ if let Some(cb) = frame_ready_cb.get() {+ cb(Instant::now());+ }}GxAction::Draw(mut boxed) => {boxed.vertices.clear();@@ -154,6 +161,7 @@ pub struct Renderer {blit_sampler: wgpu::Sampler,target_aspect: TargetAspect,actions_sent: Arc<AtomicU64>,+ frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,/// Receiver end of the EFB-to-texture writeback channel. Taken by the/// emulator setup code (via [`Renderer::take_writeback_rx`]) and/// installed into `GraphicsProcessor::efb_writeback_rx`. Wrapped in@@ -266,13 +274,15 @@ impl Renderer {batches: batches_tx,};- // Spawn the worker.+ let frame_ready_cb: Arc<OnceLock<FrameReadyCallback>> = Arc::new(OnceLock::new());+let worker_shared = shared.clone();let worker_device = device.clone();let worker_queue = queue.clone();+ let worker_cb = frame_ready_cb.clone();std::thread::Builder::new().name("gx-renderer".into())- .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx, recyclers))+ .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx, recyclers, worker_cb)).expect("failed to spawn renderer worker");Renderer {@@ -284,6 +294,7 @@ impl Renderer {blit_sampler,target_aspect,actions_sent: Arc::new(AtomicU64::new(0)),+ frame_ready_cb,#[cfg(feature = "efb-writeback")]writeback_rx: Arc::new(Mutex::new(Some(writeback_rx))),recycle_rx: Arc::new(Mutex::new(Some(recycle_rx))),@@ -291,6 +302,13 @@ impl Renderer {}}+ pub fn set_frame_ready_callback<F>(&self, cb: F)+ where+ F: Fn(Instant) + Send + Sync + 'static,+ {+ let _ = self.frame_ready_cb.set(Box::new(cb));+ }+/// Take the writeback receiver once. Returns `Some` on the first call,/// `None` thereafter. The caller installs it into/// `GraphicsProcessor::efb_writeback_rx`. Only available when thediff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex c45bde1..fcb5478 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -202,6 +202,14 @@ impl GraphicsProcessor {}pub fn present_xfb<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {+ sys.vi_present_seen_this_frame = true;+ sys.vsync_pending = true;++ #[cfg(feature = "fps-counter")]+ {+ sys.fps_counter.vsync_count += 1;+ }+if sys.gx.xfb_copies.is_empty() {return;}diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rsindex d285bad..4d5939c 100644--- a/crates/gecko/src/scheduler.rs+++ b/crates/gecko/src/scheduler.rs@@ -164,11 +164,16 @@ impl<const SYSTEM: SystemId> Scheduler<SYSTEM> {/// Reschedules itself every frame.pub fn vsync_handler<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {- sys.vsync_pending = true;- #[cfg(feature = "fps-counter")]- {- sys.fps_counter.vsync_count += 1;+ if !sys.vi_present_seen_this_frame {+ sys.vsync_pending = true;++ #[cfg(feature = "fps-counter")]+ {+ sys.fps_counter.vsync_count += 1;+ }}++ sys.vi_present_seen_this_frame = false;let rate = sys.vi.dcr.video_format().refresh_rate();sys.scheduler.schedule_in(rate.cycles_per_frame(SYSTEM), self::vsync_handler::<SYSTEM>);diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex 2975a32..7ddd242 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -30,6 +30,7 @@ pub const WII: SystemId = 1;pub struct System<const SYSTEM: SystemId> {pub vsync_pending: bool,+ pub vi_present_seen_this_frame: bool,pub gekko: Gekko,pub scheduler: Scheduler<SYSTEM>,pub mmio: Mmio<SYSTEM>,@@ -85,6 +86,7 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {pub(crate) fn with_scheduler(entrypoint: u32, scheduler: Scheduler<SYSTEM>) -> Self {System {vsync_pending: false,+ vi_present_seen_this_frame: false,gekko: Gekko::new(entrypoint),scheduler,mmio: Mmio::new(),diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rsindex a77ac3d..b6b8dfa 100644--- a/crates/tinyapp/src/app.rs+++ b/crates/tinyapp/src/app.rs@@ -4,16 +4,24 @@ use gecko::HostInput;#[cfg(feature = "fps-counter")]use gecko::fps::{self, FpsShared};use gecko::hollywood::ipc::usb;+use spin_sleep::SpinSleeper;+use std::collections::VecDeque;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};-#[cfg(not(feature = "fps-counter"))]-use std::time::Instant;+use std::time::{Duration, Instant};use winit::application::ApplicationHandler;use winit::event::{MouseButton, WindowEvent};use winit::event_loop::ActiveEventLoop;use winit::keyboard::{KeyCode, PhysicalKey};use winit::window::{Window, WindowId};+const PACER_OFFSET: Duration = Duration::from_millis(1);+const FRAME_PERIOD_60HZ: Duration = Duration::from_nanos(16_666_667);+const CADENCE_WINDOW: usize = 16;+const CADENCE_MIN_SAMPLES: usize = 4;+const CADENCE_MIN: Duration = Duration::from_micros(500);+const CADENCE_MAX: Duration = Duration::from_millis(200);+pub struct State {surface: wgpu::Surface<'static>,surface_config: wgpu::SurfaceConfiguration,@@ -29,6 +37,12 @@ pub struct State {screenshots: ScreenshotControl,#[cfg(feature = "fps-counter")]fps_shared: FpsShared,+ intended_present_time: Option<Instant>,+ frame_period: Duration,+ pacer_offset: Duration,+ pacer_sleeper: SpinSleeper,+ last_frame_ready_at: Option<Instant>,+ recent_intervals: VecDeque<Duration>,}impl State {@@ -60,7 +74,45 @@ impl State {screenshots: ScreenshotControl::new(),#[cfg(feature = "fps-counter")]fps_shared,+ intended_present_time: None,+ frame_period: FRAME_PERIOD_60HZ,+ pacer_offset: PACER_OFFSET,+ pacer_sleeper: SpinSleeper::default(),+ last_frame_ready_at: None,+ recent_intervals: VecDeque::with_capacity(CADENCE_WINDOW),+ }+ }++ pub fn observe_frame_ready(&mut self, at: Instant) {+ let Some(prev) = self.last_frame_ready_at.replace(at) else {+ return;+ };++ let Some(delta) = at.checked_duration_since(prev) else {+ return;+ };++ if !(CADENCE_MIN..=CADENCE_MAX).contains(&delta) {+ return;+ }++ if self.recent_intervals.len() == CADENCE_WINDOW {+ self.recent_intervals.pop_front();+ }++ self.recent_intervals.push_back(delta);+ let n = self.recent_intervals.len();+ if n < CADENCE_MIN_SAMPLES {+ return;+ }++ let mut buf = [Duration::ZERO; CADENCE_WINDOW];+ for (slot, d) in buf.iter_mut().zip(self.recent_intervals.iter()) {+ *slot = *d;}+ buf[..n].sort();++ self.frame_period = buf[n / 2];}fn resize(&mut self, window: &Window, width: u32, height: u32) {@@ -80,6 +132,14 @@ impl State {}fn render(&mut self, window: &Window, waiting: bool) {+ if !waiting && let Some(intended) = self.intended_present_time {+ let target = intended + self.pacer_offset;+ let now = Instant::now();+ if target > now {+ self.pacer_sleeper.sleep(target - now);+ }+ }+let frame = match self.surface.get_current_texture() {Ok(f) => f,Err(e) => {@@ -229,6 +289,13 @@ impl State {}frame.present();++ if !waiting {+ let now = Instant::now();+ let base = self.intended_present_time.unwrap_or(now);+ let next = (base + self.frame_period).max(now);+ self.intended_present_time = Some(next);+ }}}@@ -260,7 +327,7 @@ pub struct AppInit {pub surface_format: wgpu::TextureFormat,}-impl ApplicationHandler for App {+impl ApplicationHandler<crate::UserEvent> for App {fn resumed(&mut self, event_loop: &ActiveEventLoop) {let initial_size = self.init@@ -412,14 +479,26 @@ impl ApplicationHandler for App {}}- fn user_event(&mut self, event_loop: &ActiveEventLoop, _event: ()) {- if self.shutdown_requested.load(Ordering::Relaxed) {- event_loop.exit();- return;- }+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: crate::UserEvent) {+ match event {+ crate::UserEvent::Shutdown => {+ self.shutdown_requested.store(true, Ordering::Relaxed);+ event_loop.exit();+ }+ crate::UserEvent::FrameReady { at } => {+ if self.shutdown_requested.load(Ordering::Relaxed) {+ event_loop.exit();+ return;+ }- if let Some(window) = &self.window {- window.request_redraw();+ if let Some(state) = self.state.as_mut() {+ state.observe_frame_ready(at);+ }++ if let Some(window) = &self.window {+ window.request_redraw();+ }+ }}}}diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex fc2a623..4ddc853 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -19,9 +19,16 @@ use gecko::wii::Wii;use image::Dol;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};+use std::time::Instant;use winit::event_loop::EventLoop;use winit::keyboard::KeyCode;+#[derive(Debug, Clone, Copy)]+pub enum UserEvent {+ FrameReady { at: Instant },+ Shutdown,+}+#[derive(Parser)]#[command(about = "GameCube/Wii emulator",@@ -330,9 +337,16 @@ fn run<const SYSTEM: SystemId>(let input = Arc::new(Mutex::new(HostInput::neutral_for(SYSTEM)));- let event_loop = EventLoop::new().unwrap();+ let event_loop = EventLoop::<UserEvent>::with_user_event().build().unwrap();let proxy = event_loop.create_proxy();+ {+ let cb_proxy = proxy.clone();+ renderer.set_frame_ready_callback(move |at| {+ let _ = cb_proxy.send_event(UserEvent::FrameReady { at });+ });+ }+// Ctrl+C / SIGINT routes through the winit event loop so it tears down// through the same path as the window close button. Crucial for the// WAV dump: hound only patches the RIFF header sizes when the writer@@ -348,7 +362,7 @@ fn run<const SYSTEM: SystemId>(}tracing::info!("Ctrl+C received, requesting graceful shutdown");- let _ = proxy.send_event(());+ let _ = proxy.send_event(UserEvent::Shutdown);}) {tracing::warn!(?err, "failed to install Ctrl+C handler");}@@ -375,18 +389,11 @@ fn run<const SYSTEM: SystemId>(let start_gate = Arc::new(AtomicBool::new(!args.wait));let emu_start_gate = start_gate.clone();let emu_shutdown = shutdown_requested.clone();+ drop(proxy);let emu_handle = std::thread::Builder::new().name("emu".into()).spawn(move || {- thread::emu_thread::<SYSTEM>(- emulator,- emu_input,- proxy,- game_id,- throttle,- emu_start_gate,- emu_shutdown,- )+ thread::emu_thread::<SYSTEM>(emulator, emu_input, game_id, throttle, emu_start_gate, emu_shutdown)}).expect("failed to spawn emulator thread");diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rsindex da8389e..7b73f49 100644--- a/crates/tinyapp/src/thread.rs+++ b/crates/tinyapp/src/thread.rs@@ -4,12 +4,10 @@ use spin_sleep::SpinSleeper;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;-use winit::event_loop::EventLoopProxy;pub fn emu_thread<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>,input: Arc<Mutex<HostInput>>,- proxy: EventLoopProxy<()>,game_id: Option<String>,throttle: bool,start_gate: Arc<AtomicBool>,@@ -25,18 +23,17 @@ pub fn emu_thread<const SYSTEM: SystemId>(sleeper.sleep(Duration::from_millis(10));}- loop {+ while !shutdown.load(Ordering::Relaxed) {while throttle && emulator.audio_sink.should_throttle() {+ if shutdown.load(Ordering::Relaxed) {+ break;+ }sleeper.sleep(throttle_step);}let input = *input.lock().unwrap();emulator.apply_host_input(&input);emulator.run_until_vsync();-- if proxy.send_event(()).is_err() {- break;- }}if let Some(game_id) = game_id.as_deref() {