# Audio ## The render driver A title plays sound as a client of the kernel's audio render driver: ```c XAUDIORENDERDRVCLIENT client = { callback, context }; XAudioRegisterRenderDriverClient(&client, &driver); // the kernel then calls callback(&data) every 5.33 ms; in it: XAudioSubmitRenderDriverFrame(driver, frame); ``` These facts are confirmed on hardware, by xsdk and by us: - The callback runs on a **kernel thread** (hardware thread 4), **187.5 times a second**: one frame per 256 samples at 48 kHz. Our log shows 187/s steadily. - A frame is **6 channels x 256 big-endian floats**, one channel after the other: front left, front right, centre, LFE, back left, back right. The same layout works with the console set to stereo or to 5.1. - Frames live in **cached physical memory** (`MmAllocatePhysicalMemoryEx(0, size, PAGE_READWRITE, 0, 0xFFFFFFFF, 0)`). - The callback may submit straight away. It should use **integers only** and return fast. - It is called with the console ABI, so wrap it with `xbox360_entry` (see [Toolchain and ABI](Toolchain-and-ABI.md)). - `NtSetEvent` on a title's handle fails from the callback (a different process context); `KeSetEvent` on the referenced object works. ## xexkit's API `xex_audio.h` keeps a 16-frame ring. The callback takes the oldest frame, or a silent one when the ring is empty: ```c xex_audio_open(); while (xex_audio_queued() < N) { float *f = xex_audio_next(); // 6 x 256 floats, other channels silent // f[0..255] front left, f[256..511] front right xex_audio_queue(); } ``` `xex_audio_callbacks()` and `xex_audio_underruns()` count the driver's calls and the silent frames. ## Latency The system's own delay is about 21 ms: Xbox 360 games report 1024 samples through XAudio2, or 512 in low-latency mode. A title adds its queue on top. - **Short queues crackle.** If the program fills once per 16.7 ms video frame, each fill must cover more than 3 audio frames, so a queue of 2-4 runs dry and the driver plays silence. Our test heard it as "raspy" at 2. - **Fill several times a frame.** FAKE-08 makes core audio before the vblank wait, after the flip, and in 4 ms slices of its timer waits. Then 5 frames (27 ms) never ran dry. Before that it queued 8 frames, made once a frame after the vblank wait, and the delay was noticeable. - For reference, RetroArch defaults to 64 ms. Broadcast standards call audio late by about 125 ms detectable. `tests/audio` plays a click and a white flash in the same frame every second. Up/down set the queue depth, so you can judge the delay by eye and ear. ## Resampling PICO-8 makes 22050 Hz mono. FAKE-08 resamples linearly to 48 kHz and writes the same samples to front left and front right. That costs about 4-5 ms of CPU per frame in its first form; doubles in the inner loop are slow on the in-order core, so prefer integer or float steps.