Files
lilygo-t-deck/emulator/src/shim/driver/i2s.h
T
Dejvino 7df1a2d785 Fix short beeps silent on HW: i2s_zero_dma_buffer erased the unplayed DMA ring
The legacy I2S driver buffers i2s_write() data in a TX DMA ring
(8x64 samples = 64 ms @ 8 kHz) and hands a buffer back to i2s_write()
only after the DMA finished playing it. After the last queued event
the sound task called i2s_zero_dma_buffer(), which memsets the whole
ring instantly — erasing everything not yet played. Any sound <= 64 ms
was written into free ring space without ever blocking, so the zeroing
wiped it before the DMA reached a single sample: completely silent on
hardware. Longer tones force i2s_write() to block on a full ring,
pacing rendering to real-time playback — hence only long beeps were
audible, and the fade-envelope cap never moved the threshold. Every
game beep <= 80 ms (link-active 10, laser 30, sever 40, bleep/ICE 50,
feedback 80) sat in the dead zone. The emulator never showed it: its
i2s_write shim fed SDL directly and had no ring at all.

Fix: replace the instant zeroing with a paced silence purge — once the
queue drains, write one ring + one chunk of zero samples through
i2s_write(), reusing each DMA buffer only after the DMA played it. The
sound plays out fully and the ring then loops silence (still kills the
tail-replay bug the zeroing existed for). Keep the envelope cap at
total/4 so short tones keep a steady-state portion.

Emulator shim gains a TX DMA ring model (write/play cursors + bounded
DAC-emitted log) so the bug class reproduces headlessly: unit/
sound_short_tone_reaches_dac fails on the zero_dma code, passes on the
purge (A/B verified); shim_zero_dma_erases_unplayed pins model fidelity;
sound_long_tone_plays_out_fully guards against truncation. SoundEngine
gains a pumpOne() test seam and begin(spawnTask) for deterministic
driving. Full suite: 26 unit + 7 integration + 4 E2E, 0 failures.
2026-11-15 12:19:21 +01:00

169 lines
6.1 KiB
C++

/**
* I2S driver shim: routes i2s_write() output to an SDL audio device
* (8 kHz mono S16, queue-based, exactly what the sound engine feeds).
*/
#pragma once
#include <cstdint>
#include <cstddef>
#include <vector>
#include <algorithm>
#include <SDL3/SDL.h>
#include "../Arduino.h" // emu::claimPin — GPIO-matrix pin-ownership model
#define ESP_OK 0
#define ESP_FAIL -1
#define ESP_INTR_FLAG_LEVEL1 1
typedef int i2s_port_t;
typedef int i2s_mode_t;
enum { I2S_NUM_0 = 0, I2S_NUM_1 = 1 };
enum { I2S_MODE_MASTER = 0x01, I2S_MODE_TX = 0x04 };
enum { I2S_BITS_PER_SAMPLE_16BIT = 16 };
enum { I2S_CHANNEL_FMT_ONLY_LEFT = 0 };
enum { I2S_COMM_FORMAT_STAND_I2S = 0x01 };
#define I2S_PIN_NO_CHANGE (-1)
struct i2s_config_t {
int mode;
unsigned sample_rate;
int bits_per_sample;
int channel_format;
int communication_format;
int intr_alloc_flags;
int dma_buf_count;
int dma_buf_len;
bool tx_desc_auto_clear;
};
struct i2s_pin_config_t {
int mck_io_num; // mirrors the S3 header: GPIO0 is MCLK-capable, so a
// zero-initialized config silently claims GPIO0
int bck_io_num;
int ws_io_num;
int data_out_num;
int data_in_num;
};
inline SDL_AudioStream *&emuAudioStream()
{
static SDL_AudioStream *s = nullptr;
return s;
}
// --- TX DMA ring model (parity with the legacy ESP32 driver) ----------------
// The real legacy driver copies i2s_write() data into a ring of DMA buffers
// (dma_buf_count x dma_buf_len samples) and consumes it at the sample rate;
// a buffer is handed back to i2s_write() only after the DMA finished playing
// it, and i2s_zero_dma_buffer() memsets the WHOLE ring — erasing everything
// not yet played. The live SDL path below stays direct-fed (interactive audio
// keeps working with zero latency machinery), but this shadow model records
// what the DAC would actually have emitted, so headless tests can reproduce
// hardware-only sound bugs deterministically — e.g. the sound engine zeroing
// the ring right after rendering a short beep, wiping it before playback
// (every game beep ≤ 64 ms was silent on HW while the emulator sounded fine).
namespace emu {
struct DmaRing {
size_t cap = 0; // ring capacity in samples
std::vector<int16_t> buf; // ring contents
size_t ppos = 0, wpos = 0; // play / write cursors
size_t used = 0; // samples written but not yet played
std::deque<int16_t> played; // bounded log: what the DAC emitted
void reset(size_t capacity)
{
cap = capacity;
buf.assign(cap, 0);
ppos = wpos = used = 0;
played.clear();
}
bool full() const { return used == cap; }
void playOne() // DMA consumed the sample at ppos
{
played.push_back(buf[ppos]);
if (played.size() > 8192) played.pop_front();
ppos = (ppos + 1) % cap;
--used;
}
void writeOne(int16_t v)
{
buf[wpos] = v;
wpos = (wpos + 1) % cap;
++used;
}
};
inline DmaRing &emuDmaRing()
{
static DmaRing r;
return r;
}
} // namespace emu
inline int i2s_driver_install(i2s_port_t, const i2s_config_t *cfg, int, void *)
{
// Model the TX DMA ring with the configured geometry.
emu::emuDmaRing().reset((size_t)cfg->dma_buf_count * (size_t)cfg->dma_buf_len);
// SDL3 audio: open a stream on the default playback device with our
// spec (conversion to the device format is automatic) and feed it from
// i2s_write() via SDL_PutAudioStreamData().
SDL_AudioSpec want {};
want.freq = (int)cfg->sample_rate;
want.format = SDL_AUDIO_S16;
want.channels = 1;
emuAudioStream() = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK,
&want, nullptr, nullptr);
if (!emuAudioStream()) {
std::printf("[emu] no audio device: %s (running silent)\n", SDL_GetError());
return ESP_FAIL;
}
SDL_ResumeAudioStreamDevice(emuAudioStream());
std::printf("[emu] audio open: %d Hz\n", want.freq);
return ESP_OK;
}
inline int i2s_set_pin(i2s_port_t, const i2s_pin_config_t *pins)
{
// GPIO-matrix parity: the real driver routes every configured pin to the
// I2S peripheral and OWNS it from then on — inputs/ISRs on the same GPIO
// die. In particular a zero-initialized i2s_pin_config_t carries
// mck_io_num == 0, and GPIO0 is MCLK-capable on the ESP32-S3 — which is
// exactly how the NetDeck sound engine used to kill the trackball click
// line (HW.md). emu::claimPin() makes that visible here.
if (pins->mck_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->mck_io_num, "i2s MCLK");
if (pins->bck_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->bck_io_num, "i2s BCK");
if (pins->ws_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->ws_io_num, "i2s WS");
if (pins->data_out_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->data_out_num, "i2s DOUT");
if (pins->data_in_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->data_in_num, "i2s DIN");
return ESP_OK;
}
inline int i2s_write(i2s_port_t, const void *src, size_t size, size_t *written, unsigned)
{
// Shadow the legacy TX DMA ring: data lands at the write cursor and only
// pushes already-played samples out of the ring. When the ring is full
// the real driver blocks here until the DMA frees a buffer; the model
// advances playback instead (deterministic, no real-time waiting).
const int16_t *s = (const int16_t *)src;
size_t n = size / sizeof(int16_t);
emu::DmaRing &r = emu::emuDmaRing();
if (r.cap > 0) {
for (size_t i = 0; i < n; i++) {
if (r.full()) r.playOne();
r.writeOne(s[i]);
}
}
if (emuAudioStream()) SDL_PutAudioStreamData(emuAudioStream(), src, (int)size);
if (written) *written = size;
return ESP_OK;
}
inline void i2s_zero_dma_buffer(i2s_port_t)
{
// Faithful to the legacy driver: memset the ring contents. Every sample
// written but not yet played is erased and will never be heard.
auto &r = emu::emuDmaRing();
std::fill(r.buf.begin(), r.buf.end(), 0);
}