From 8575c6dbe434e4c83fe0314e89390a970c8402a8 Mon Sep 17 00:00:00 2001 From: Skyth <19259897+blueskythlikesclouds@users.noreply.github.com> Date: Sat, 21 Dec 2024 15:28:08 +0300 Subject: [PATCH] Implement audio timing with integer math. --- UnleashedRecomp/apu/driver/sdl2_driver.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/UnleashedRecomp/apu/driver/sdl2_driver.cpp b/UnleashedRecomp/apu/driver/sdl2_driver.cpp index 7c8777e7..be0acd94 100644 --- a/UnleashedRecomp/apu/driver/sdl2_driver.cpp +++ b/UnleashedRecomp/apu/driver/sdl2_driver.cpp @@ -40,10 +40,8 @@ static void AudioThread() GuestThreadContext ctx(0); size_t channels = g_downMixToStereo ? 2 : XAUDIO_NUM_CHANNELS; - - constexpr double INTERVAL = double(XAUDIO_NUM_SAMPLES) / double(XAUDIO_SAMPLES_HZ); auto start = std::chrono::steady_clock::now(); - size_t iteration = 1; + int64_t iteration = 1; while (true) { @@ -57,15 +55,14 @@ static void AudioThread() g_clientCallback(ctx.ppcContext, reinterpret_cast(g_memory.base)); } - auto next = start + std::chrono::duration(iteration * INTERVAL); + auto next = start + std::chrono::nanoseconds((iteration * XAUDIO_NUM_SAMPLES * 1000000000ll) / XAUDIO_SAMPLES_HZ); auto now = std::chrono::steady_clock::now(); - if ((next - now) > 1s) - next = now; + if ((next - now) < 1s) + std::this_thread::sleep_until(next); - std::this_thread::sleep_until(next); - - iteration = std::chrono::duration(std::chrono::steady_clock::now() - start).count() / INTERVAL + 1; + int64_t elapsed = std::chrono::nanoseconds(std::chrono::steady_clock::now() - start).count(); + iteration = ((elapsed * XAUDIO_SAMPLES_HZ) / (XAUDIO_NUM_SAMPLES * 1000000000ll)) + 1; } }