foxygit / fake-08-xbox360 Log in
commit f8a6f8bc94b72e82afbef29acbfb303347740ad4
Author:     mrfox <jens.se@icloud.com>
AuthorDate: Wed Nov 25 17:39:16 2026 +0100
Commit:     mrfox <jens.se@icloud.com>
CommitDate: Wed Nov 25 17:39:16 2026 +0100

    xex: sound through the kernel's audio render driver (step 4)

    runtime/audio.c registers an XAudio render driver client; the kernel's
    callback takes 256-sample 48 kHz frames (6 channels of big-endian floats,
    as xsdk found on hardware) from a 16-frame ring, or plays silence. Kernel
    callbacks (audio, fault handler) enter through kernel_entries.S, which
    keeps r14-r31 in full 64 bits. The FAKE-08 host resamples the core's
    22050 Hz mono to the front left and right channels, ~43 ms ahead, and
    logs queue/underrun/drop counts with the perf line.

    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
 platform/xex/Makefile                 |   2 +-
 platform/xex/README.md                |   9 ++-
 platform/xex/runtime/audio.c          | 100 ++++++++++++++++++++++++++++++++++
 platform/xex/runtime/fault.c          |   8 ++-
 platform/xex/runtime/kernel_entries.S |   7 +++
 platform/xex/runtime/xex_audio.h      |  47 ++++++++++++++++
 platform/xex/source/XexHost.cpp       |  86 +++++++++++++++++++++++++++--
 7 files changed, 249 insertions(+), 10 deletions(-)

diff --git a/platform/xex/Makefile b/platform/xex/Makefile
index fef4636..a2b20d1 100644
--- a/platform/xex/Makefile
+++ b/platform/xex/Makefile
@@ -25,7 +25,7 @@ LDFLAGS  := $(MACH) -nostartfiles -nostdlib -T $(CURDIR)/runtime/link.ld -Wl,--g
 LIBS     := -L$(DEVKITXENON)/xenon/lib/32 -Wl,--start-group -lstdc++ -lm -lc -lgcc -Wl,--end-group

 RUNTIME_SRC := runtime/crt0.S runtime/crt.c runtime/sys.c runtime/fs.c runtime/posix.c \
-               runtime/video.c runtime/input.c runtime/fault.c \
+               runtime/video.c runtime/input.c runtime/fault.c runtime/audio.c runtime/kernel_entries.S \
                runtime/extra_imports.S sdk/thunks/ppc32.S
 RUNTIME_OBJ := $(patsubst %,$(BUILD)/%.o,$(RUNTIME_SRC))

diff --git a/platform/xex/README.md b/platform/xex/README.md
index 65eb79e..b12f705 100644
--- a/platform/xex/README.md
+++ b/platform/xex/README.md
@@ -60,7 +60,8 @@ folder is read-only).
 | Xbox button | Guide; Xbox Home leaves to Aurora |
 | Back+Start | quit (some dashboard plugins use it for screenshots) |

-Controllers 2-4 are players 2-4. Sound is not implemented yet.
+Controllers 2-4 are players 2-4. Sound goes through the kernel's audio render
+driver at 48 kHz (front left and right).

 The source is `source/XexHost.cpp`, the same logic as the libxenon host
 (`platform/xenon/source/XenonHost.cpp`) on this platform's runtime.
@@ -100,6 +101,12 @@ The source is `source/XexHost.cpp`, the same logic as the libxenon host
   scaling back afterwards), and XAM is told the title's display size
   (graphics notification event 1). As found by xsdk. A title must not end by
   itself while the Guide shows (`xex_video_guide_visible()`).
+- **Audio** (`xex_audio.h`): an XAudio render driver client. The kernel
+  calls back every 5.33 ms for a frame of 256 samples at 48 kHz, 6 channels
+  of big-endian floats one after the other (xsdk's findings); the title
+  queues frames into a 16-frame ring, and the callback plays silence when
+  it is empty. Kernel callbacks enter through `kernel_entries.S`, which
+  keeps r14-r31 whole.
 - **Input** (`xex_input.h`): `XamInputGetState` per port.

 ## Tests
diff --git a/platform/xex/runtime/audio.c b/platform/xex/runtime/audio.c
new file mode 100644
index 0000000..a486f64
--- /dev/null
+++ b/platform/xex/runtime/audio.c
@@ -0,0 +1,100 @@
+/*
+ * Sound through the kernel's audio render driver; see xex_audio.h.
+ * Facts from xsdk's hardware runs (docs/HARDWARE.md, "Runtime, milestone
+ * 2" and "Audio's feeding, milestone 58"): the callback runs on a kernel
+ * thread every 5.33 ms and may submit the frame itself; frames are in
+ * cached physical memory; the callback uses integers only.
+ */
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <xbox360/xboxkrnl.h>
+
+#include "xex_audio.h"
+
+#define FRAME_FLOATS (XEX_AUDIO_FRAME_SAMPLES * XEX_AUDIO_CHANNELS)
+#define SILENCE_SLOT XEX_AUDIO_RING_FRAMES
+
+static float *frames;              /* ring + one silent frame */
+static PVOID volatile driver;      /* 0 while closed */
+static volatile uint32_t queued;   /* written by the title */
+static volatile uint32_t taken;    /* written by the callback */
+static volatile uint32_t silent;
+static XAUDIORENDERDRVCLIENT client;
+
+/* Kernel thread, once per frame. Called through xex_audio_callback_entry
+ * (kernel_entries.S), which keeps r14-r31 whole for the kernel. */
+void xex_audio_callback(PXAUDIORENDERDRVCALLBACKDATA data)
+{
+    (void)data;
+    PVOID d = driver;
+    if (!d) return;
+    uint32_t t = taken;
+    const float *frame;
+    if (queued != t) {
+        frame = frames + (t % XEX_AUDIO_RING_FRAMES) * FRAME_FLOATS;
+        __asm__ volatile("lwsync" ::: "memory");
+        taken = t + 1;
+    } else {
+        frame = frames + SILENCE_SLOT * FRAME_FLOATS;
+        if (queued) silent = silent + 1;
+    }
+    XAudioSubmitRenderDriverFrame(d, frame);
+}
+
+extern void xex_audio_callback_entry(PXAUDIORENDERDRVCALLBACKDATA data);
+
+int xex_audio_open(void)
+{
+    if (driver) return 0;
+    if (!frames) {
+        uint32_t bytes = (XEX_AUDIO_RING_FRAMES + 1) * FRAME_FLOATS * sizeof(float);
+        frames = (float *)MmAllocatePhysicalMemoryEx(0, bytes, PAGE_READWRITE, 0, 0xffffffffu, 0);
+        if (!frames) return -1;
+        memset(frames, 0, bytes);   /* every channel silent */
+    }
+    queued = 0;
+    taken = 0;
+    silent = 0;
+    client.Callback = xex_audio_callback_entry;
+    client.Context = NULL;
+    PVOID d = NULL;
+    HRESULT hr = XAudioRegisterRenderDriverClient(&client, &d);
+    if (hr < 0 || !d) return -1;
+    __asm__ volatile("lwsync" ::: "memory");
+    driver = d;
+    atexit(xex_audio_close);
+    return 0;
+}
+
+unsigned xex_audio_queued(void)
+{
+    return queued - taken;
+}
+
+float *xex_audio_next(void)
+{
+    if (!driver || queued - taken >= XEX_AUDIO_RING_FRAMES - 1) return NULL;
+    return frames + (queued % XEX_AUDIO_RING_FRAMES) * FRAME_FLOATS;
+}
+
+void xex_audio_queue(void)
+{
+    __asm__ volatile("lwsync" ::: "memory");
+    queued = queued + 1;
+}
+
+unsigned xex_audio_underruns(void)
+{
+    return silent;
+}
+
+void xex_audio_close(void)
+{
+    PVOID d = driver;
+    if (!d) return;
+    driver = NULL;
+    /* the frames stay allocated: a callback can still run after this */
+    XAudioUnregisterRenderDriverClient(d);
+}
diff --git a/platform/xex/runtime/fault.c b/platform/xex/runtime/fault.c
index 1931881..67d7c4d 100644
--- a/platform/xex/runtime/fault.c
+++ b/platform/xex/runtime/fault.c
@@ -94,7 +94,7 @@ static const char *code_name(uint32_t code)
     }
 }

-static long fault_handler(exception_pointers *pointers)
+long xex_fault_handler(exception_pointers *pointers)
 {
     static int inside;
     if (inside) XamLoaderTerminateTitle();   /* a fault while reporting */
@@ -136,7 +136,11 @@ static long fault_handler(exception_pointers *pointers)
     XamLoaderTerminateTitle();
 }

+/* kernel_entries.S: keeps r14-r31 whole for the kernel when the handler
+ * returns (faults outside the title's code are passed on). */
+extern long xex_fault_handler_entry(exception_pointers *pointers);
+
 void xex_install_fault_handler(void)
 {
-    RtlSetVectoredExceptionHandler((void *)fault_handler, (void *)fault_handler);
+    RtlSetVectoredExceptionHandler((void *)xex_fault_handler_entry, (void *)xex_fault_handler_entry);
 }
diff --git a/platform/xex/runtime/kernel_entries.S b/platform/xex/runtime/kernel_entries.S
new file mode 100644
index 0000000..e8eb82b
--- /dev/null
+++ b/platform/xex/runtime/kernel_entries.S
@@ -0,0 +1,7 @@
+/* Functions the kernel calls with the console calling convention, which
+ * expects r14-r31 back in full 64 bits (see sdk/crt/entry.inc): the audio
+ * render driver's callback and the vectored exception handler. */
+#include "../sdk/crt/entry.inc"
+
+xbox360_entry xex_audio_callback_entry, xex_audio_callback
+xbox360_entry xex_fault_handler_entry, xex_fault_handler
diff --git a/platform/xex/runtime/xex_audio.h b/platform/xex/runtime/xex_audio.h
new file mode 100644
index 0000000..7f9b508
--- /dev/null
+++ b/platform/xex/runtime/xex_audio.h
@@ -0,0 +1,47 @@
+/*
+ * Sound through the kernel's audio render driver (XAudio render driver
+ * client, as found on hardware by xsdk, https://github.com/jessenic/xsdk):
+ * the driver takes a frame every 5.33 ms, 256 samples at 48 kHz in 6
+ * channels (front left, front right, centre, LFE, back left, back right),
+ * each channel's 256 big-endian floats after the other.
+ *
+ * The title fills frames ahead into a ring; the driver's callback takes the
+ * oldest, or plays silence when the ring is empty.
+ */
+#ifndef XEX_AUDIO_H
+#define XEX_AUDIO_H
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define XEX_AUDIO_RATE           48000
+#define XEX_AUDIO_FRAME_SAMPLES  256
+#define XEX_AUDIO_CHANNELS       6
+#define XEX_AUDIO_RING_FRAMES    16
+
+/* Registers with the driver. 0 on success. */
+int xex_audio_open(void);
+
+/* Frames queued and not yet taken by the driver. */
+unsigned xex_audio_queued(void);
+
+/* The next frame to fill (6 x 256 floats, channel after channel; the
+ * centre, LFE and back channels start out silent and may stay so), or
+ * NULL when the ring is full. Call xex_audio_queue() once it is filled. */
+float *xex_audio_next(void);
+void xex_audio_queue(void);
+
+/* Frames the driver played silence for, because the ring was empty. */
+unsigned xex_audio_underruns(void);
+
+/* Unregisters (also done at exit). */
+void xex_audio_close(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/platform/xex/source/XexHost.cpp b/platform/xex/source/XexHost.cpp
index 6e2571c..f63ab54 100644
--- a/platform/xex/source/XexHost.cpp
+++ b/platform/xex/source/XexHost.cpp
@@ -8,7 +8,8 @@
  *   - input: XamInputGetState for four controllers,
  *   - files: game:/ (the XEX's folder), usb0:-usb2:, hdd:,
  *   - time: the CPU time base (49.875 MHz).
- * Audio is not implemented yet (step 4: the kernel's XAudio render driver).
+ *   - audio: xex_audio (the kernel's render driver, 48 kHz), resampled
+ *     from the core's 22050 Hz mono.
  *
  * Exit: Xbox button -> Xbox Home in the Guide, or Back+Start.
  */
@@ -34,6 +35,7 @@
 #include "xex_runtime.h"
 #include "xex_video.h"
 #include "xex_input.h"
+#include "xex_audio.h"

 // 8x16 console font from libxenon (headers of the free60/libxenon image)
 #include <console/font_8x16.h>
@@ -155,6 +157,59 @@ static bool vsyncMode = true;

 static inline uint64_t now() { return xex_timebase(); }

+// ---------------------------------------------------------------------------
+// Audio: 22050 Hz mono from the core -> 48 kHz float frames of 256 samples
+// for the render driver, the same sample on front left and right.
+// ---------------------------------------------------------------------------
+
+static const int CoreRate = 22050;
+static const int OutRate = XEX_AUDIO_RATE;
+static const unsigned TargetQueuedFrames = 8;   // 8 x 5.33 ms = ~43 ms ahead
+static const int MaxCoreFrames = 2048;
+
+static uint32_t coreBuf[MaxCoreFrames];
+static size_t coreFrames = 0;
+static float pendingOut[XEX_AUDIO_FRAME_SAMPLES];
+static int pendingCount = 0;          // samples of the frame being built
+static double resamplePos = 0.0;      // fractional position carried between chunks
+static int16_t resamplePrev = 0;      // last core sample of the previous chunk
+static bool audioOk = false;
+static unsigned audioDropped = 0;     // frames lost to a full ring
+
+static void audioSetup() {
+    audioOk = xex_audio_open() == 0;
+    Logger_Write("audio: %s\n", audioOk ? "render driver client registered" : "XAudio registration failed");
+}
+
+static void pushOutSample(float v) {
+    pendingOut[pendingCount++] = v;
+    if (pendingCount < XEX_AUDIO_FRAME_SAMPLES) return;
+    pendingCount = 0;
+    float *frame = xex_audio_next();
+    if (!frame) { audioDropped++; return; }
+    memcpy(frame, pendingOut, sizeof(pendingOut));                              // front left
+    memcpy(frame + XEX_AUDIO_FRAME_SAMPLES, pendingOut, sizeof(pendingOut));    // front right
+    xex_audio_queue();
+}
+
+static void audioPlayChunk() {
+    if (!audioOk || coreFrames == 0) return;
+
+    const double step = (double)CoreRate / OutRate;
+    size_t n = coreFrames;
+    double pos = resamplePos;   // index into [prev, s0, s1, ... s(n-1)]
+    while (pos + 1.0 <= (double)n) {
+        int i = (int)pos;
+        double frac = pos - i;
+        int16_t a = (i == 0) ? resamplePrev : (int16_t)(coreBuf[i - 1] & 0xffff);
+        int16_t b = (int16_t)(coreBuf[i] & 0xffff);
+        pushOutSample((float)(a + (b - a) * frac) * (1.0f / 32768.0f));
+        pos += step;
+    }
+    resamplePos = pos - (double)n;
+    resamplePrev = (int16_t)(coreBuf[n - 1] & 0xffff);
+}
+
 // ---------------------------------------------------------------------------
 // Storage
 // ---------------------------------------------------------------------------
@@ -255,7 +310,9 @@ static void perfFrameDone(uint64_t emuTb, uint64_t waitTb, uint64_t blitTb, uint
         snprintf(perfLines[3], 24, "wait %4.1f/%4.1f", tbToMs(accWait.sum / n), tbToMs(accWait.max));
         snprintf(perfLines[4], 24, "%dx%d %d", fbWidth, fbHeight, destW);
         if (t - perfLogStart >= 5 * tbFreq) {
-            Logger_Write("perf: %s | %s | %s | %s | %s (avg/max ms)\n", perfLines[0], perfLines[1], perfLines[2], perfLines[3], perfLines[4]);
+            Logger_Write("perf: %s | %s | %s | %s | %s (avg/max ms) | audio queued %u underruns %u dropped %u\n",
+                         perfLines[0], perfLines[1], perfLines[2], perfLines[3], perfLines[4],
+                         xex_audio_queued(), xex_audio_underruns(), audioDropped);
             perfLogStart = t;
         }
         accEmu = {0,0}; accBlit = {0,0}; accWait = {0,0};
@@ -344,6 +401,7 @@ void Host::oneTimeSetup(Audio *audio) {
     mouseOffsetX = destX;
     mouseOffsetY = destY;

+    audioSetup();
     lastFrameTb = now();
 }

@@ -541,20 +599,36 @@ void Host::drawFrame(uint8_t *picoFb, uint8_t *screenPaletteMap, uint8_t drawMod
     perfLastDrawEnd = now();
 }

-// Audio: not implemented yet (step 4). The core runs without sound.
 bool Host::shouldFillAudioBuff() {
-    return false;
+    if (!audioOk) return false;
+
+    unsigned queued = xex_audio_queued();
+    if (queued >= TargetQueuedFrames) {
+        coreFrames = 0;
+        return false;
+    }
+    int missingOut = (int)(TargetQueuedFrames - queued) * XEX_AUDIO_FRAME_SAMPLES - pendingCount;
+    if (missingOut <= 0) {
+        coreFrames = 0;
+        return false;
+    }
+    size_t frames = (size_t)missingOut * CoreRate / OutRate + 1;
+    if (frames > (size_t)MaxCoreFrames) frames = MaxCoreFrames;
+    coreFrames = frames;
+    return true;
 }

 void *Host::getAudioBufferPointer() {
-    return nullptr;
+    return coreBuf;
 }

 size_t Host::getAudioBufferSize() {
-    return 0;
+    return coreFrames;
 }

 void Host::playFilledAudioBuffer() {
+    audioPlayChunk();
+    coreFrames = 0;
 }

 bool Host::shouldRunMainLoop() {