r/EmuDev • • 13d ago

Extended my GB emulator built in pygame, python to GBC

AI disclaimer: AI was used only for debugging and disassembly, no AI generated code was used ever, and no agentic code as well

Hello everyone, today I wanted to showcase my GBC emulator that I derived from my earlier GB implementation: https://github.com/atifcodesalot/hazelnut-gb-emu. It was a fun (and buggy) experience. The pypy runtime gracefully shouldered the double speed mode! It is also backwards compatible with the GameBoy. Did you know that the DMG compatibility mode introduces actual three new palettes for the original DMG games? Anyways it currently supports MBC 1, 2, 3 and 5. I have no idea how to implement MBC7 for the Kirby Tilt 'n' Tumble 😭 not because of the EEPROM but also the accelerometer emulation. Also, still working on the sound! I also plan on implementing serial functions for LAN play (hopefully). What do you think? Would love to discuss technical stuff and implementation details! Enjoy. Oh, and don't forget to clone the repo and play some stuff yourself I recommend Pokemon Yellow

13 Upvotes

6 comments sorted by

2

u/HowziCanReddit 13d ago

Are you implementing the APU from scratch, or porting a known-good mixing model?

Also, the accelerometer is the hard part. It relies on the cartridge’s PHI clock, and if the CPU enters HALT during a latch read, the clock stops and the sensor returns garbage data. This means your emulator can’t just treat it as a simple memory-mapped register—you’d need to model the latching timing and keep the clock running for at least ~1.2 ms after a latch trigger.

2

u/Creepy_Sherbert_1179 13d ago

well no, I am implementing the APU with my "own model". It is actually very straightforward, as the APU ticks with the master clock, I dumb down 4mhz to 44100 samples per second and write to buffers 0.1 ms buffers. I agree with the accelerometer part, I will try my best lol

3

u/HowziCanReddit 13d ago

0.1 ms at 44.1 kHz is ~4.4 samples per buffer — that's ~4,410 buffer writes per second. That's a lot of synchronization overhead. Unless you have a specific reason for that chunk size, a ring buffer with the emulator thread pushing larger chunks (say 256–512 samples ≈ 6–12 ms) and the audio callback draining it is usually the sweet spot: low enough latency to feel responsive, high enough to absorb jitter. Then handle the slow emulator-vs-audio-clock drift with a tiny level-based resample (drop/dupe a sample when the ring buffer level wanders).

Also, 4194304 / 44100 ≈ 95.1097. If you decimate by a fixed 95, you drift: over one second you'd emit ~44,150 samples, not 44,100 — about 0.1% fast, which is audible over a few minutes as pitch creep and buffer drift.

2

u/Creepy_Sherbert_1179 13d ago

Wow! You are experienced at this huh? :D You basically listed everything I went through so far trying to implement the APU very accurately! Thanks for the suggestions! I am currently struggling with the ring buffer underrunning (not able to keep up with emulation) mostly because wave RAM is cycle stepped :D I also need to implement some kind of buffer ownership so overruns don't happen as well. If you want (and care enough to bother), you are free to contribute by the way!

2

u/HowziCanReddit 13d ago edited 13d ago

Haha I actually did a lot of work on a GB emu in Python awhile ago but had no time to work on hobby projects because of university lol.

Anyways your suspicion about cycle-stepped wave RAM is probably right, cycle-stepping is almost certainly your throughput killer (record min(fill_level) and underrun_count over a 10-second window, and log samples produced per wall-clock second. If produced ≈ 44,100 and you still underrun, it's jitter — buffer size. If produced < 44,100, it's throughput). Also, stepping wave RAM every master cycle is ~4.19M iterations/sec just for one channel. You don't need cycle resolution there. You need sample resolution because the wave output only changes when the wave position changes and you only observe it at 44.1 kHz. Move it to an accumulator inside the per-sample loop (At max frequency (~1 MHz step rate) that's still ≤2 iterations per 44.1 kHz sample), do the same accumulator trick for pulse duty (4 * (2048 - X) cycles/step), noise LFSR (16 * (divisor << shift) cycles/clock), while envelope/sweep/length stay on the 512 Hz frame sequencer (free). One note, NRx4 trigger resets wave_pos and reloads the accumulator so handle those at the write not in the hot loop. Next, you should also batch the whole APU into ~738-sample frame chunks (right now you're writing 0.1 ms buffers (~4.4 samples) — that's 4,410 tiny push operations per second, each with lock/visibility overhead, and each one is a chance to starve. Flip it: produce one frame's worth of audio per emulated frame, into a local buffer, then push one chunk), and push once per frame into an SPSC ring with monotonic indices (single producer (emulator thread), single consumer (audio callback), monotonic 64-bit counters, power-of-two capacity so & mask replaces modulo. Producer only ever writes write; consumer only ever writes read. Bump write last after the data is in). As for ring buffer ownership; drop-oldest on overrun policy (advanced read from producer; dropping oldest causes a brief glitch but keeps the buffer's time-to-play bounded), pad-silence on underrun policy (don't move read past write, a one-pole fade from the last sample to zero over ~32 samples hides the click). Now prefill the ring with ~1 frame of silence at startup so PyPy's first-frame JIT stall doesn't cause an immediate underrun. After that, if the emulator is paced to real-time (sleep/yield to 59.7275 Hz), drift is tiny. If you don't pace (run as fast as possible), the ring will eventually overrun — the drop-oldest policy handles it, but you'll hear periodic glitches. Either pace, or add the classic dynamic rate control: when fill > 0.75 * cap, skip pushing a frame occasionally; when fill < 0.25 * cap, duplicate a frame.

Typed this all out while on the toilet, hopefully it helps xd

1

u/HowziCanReddit 13d ago

I forgot to mention reads/writes of Python ints are atomic and write published last gives you the needed ordering — the callback only touches samples < write. If your audio library's callback runs with the GIL released, wrap just the index bumps in a tiny threading.Lock, or use numpy + a shared multiprocessing ring. Since you're in Python the callback almost certainly holds the GIL so verify once and you can skip the lock.