Skip to content

Comments

Decouple audio generation from CPU loop and add APU lock for thread safety#8

Merged
rafael84 merged 8 commits intomainfrom
codex/improve-apu-parallelism-for-audio-processing
Feb 3, 2026
Merged

Decouple audio generation from CPU loop and add APU lock for thread safety#8
rafael84 merged 8 commits intomainfrom
codex/improve-apu-parallelism-for-audio-processing

Conversation

@rafael84
Copy link
Owner

@rafael84 rafael84 commented Feb 3, 2026

Motivation

  • Audio sample generation ran inside the per-frame / CPU loop which blocks sound playback while the VM executes, preventing parallel audio processing during note playback.
  • The previous ring-buffer approach in the emulator added complexity and still tied audio production to the CPU path.
  • MMIO access to the APU can now race with audio generation running on the audio thread, so lightweight synchronization is needed.

Description

  • Move APU sample production into the audio callback by calling tiny16_apu_generate_samples directly from tiny16_audio_callback in emulator/tiny16_core.c, removing the per-frame production path and the tiny16_emu_audio_produce usage.
  • Remove the emulator-side ring buffer and its fields (audio_ring, audio_read, audio_write) and helper functions from emulator/tiny16_core.c / emulator/tiny16_core.h, simplifying runtime audio buffering.
  • Add a volatile int lock to the Tiny16APU structure in vm/apu.h and implement apu_lock / apu_unlock (spinlock using GCC atomic intrinsics) in vm/apu.c.
  • Guard APU MMIO and sample functions with the new lock: tiny16_apu_mmio_write, tiny16_apu_mmio_read, tiny16_apu_samples_for_cycles, and tiny16_apu_generate_samples now acquire the lock while touching shared APU state.
  • Initialize the APU lock in tiny16_apu_reset and adapt read paths to return values while holding/releasing the lock safely.

Testing

  • No automated tests were run on the modified code in this change set.

Codex Task

@rafael84 rafael84 merged commit 0d97b75 into main Feb 3, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant