Audio System
PixelRoot32 provides a NES-like audio subsystem: a dynamic 8-voice pooling system (supporting Pulse, Triangle, Noise, Sine, and Saw waveforms), mono 16-bit output, event-driven playback (AudioEvent), and sample-accurate timing decoupled from the game frame rate. There is no DMC/sample channel in the current engine.
For implementation details, see Audio subsystem (authoritative).
Architecture Overview
AudioEngineforwards commands andgenerateSamplesto the activeAudioScheduler, which delegates toApuCore: SPSC queue, dynamic 8-voice pool, music sequencer, mixing, and (on the FPU path) a one-pole output HPF. Synthesis is not duplicated across three scheduler copies.- On ESP32, core affinity and task priority are applied when the backend creates its FreeRTOS task (
PlatformCapabilities), not insideESP32AudioSchedulerconstruction arguments (those parameters are reserved for API stability).
Key Features
| Feature | Description |
|---|---|
| 8 voices | Dynamic voice pooling with stealing logic. Supports Pulse, Triangle, Noise, Sine, and Saw. |
| Sample-accurate | Channel lifetime in samples; independent of FPS |
| Schedulers | NativeAudioScheduler (PC), ESP32AudioScheduler (firmware), DefaultAudioScheduler (tests / callback-driven) |
| Command path | Lock-free SPSC ring buffer, 64 entries (32–64; one slot stays free, so 63 commands); one producer / one consumer |
| Mixer | Soft saturation (FPU) or LUT (no-FPU, e.g. ESP32-C3) |
| Multi-track music | Up to MAX_MUSIC_TRACKS (4): main MusicTrack + optional secondVoice, thirdVoice, percussion; MusicPlayer::play packs them into AudioCommand::subTracks |
| NES-style timing | Sequencer in ApuCore uses tick steps derived from sample time and BPM (default 150 BPM, 4 ticks per beat); not tied to render FPS |
| BPM & tempo | MusicPlayer::setBPM / getBPM and setTempoFactor → MUSIC_SET_BPM / MUSIC_SET_TEMPO |
| Percussion presets | INSTR_KICK, INSTR_SNARE, INSTR_HIHAT (duty == 0, WaveType::NOISE, noisePeriod / defaultDuration in InstrumentPreset); INSTR_KICK_TRI, a triangle kick for a WaveType::TRIANGLE track |
| Sound profiles | Legacy (default, frozen) / Nes / Famicom (Hybrid is a deprecated alias of Famicom), switched with SET_SOUND_PROFILE; see Sound profiles |
Quick start: sound effects
Use AudioEngine::playEvent with an AudioEvent (#include <audio/AudioEngine.h>, <audio/AudioTypes.h>):
#if PIXELROOT32_ENABLE_AUDIO
#include <audio/AudioEngine.h>
#include <audio/AudioTypes.h>
void playCoin(pr32::core::Engine& engine) {
pr32::audio::AudioEvent evt{};
evt.type = pr32::audio::WaveType::PULSE;
evt.frequency = 1500.0f;
evt.duration = 0.12f;
evt.volume = 0.8f;
evt.duty = 0.5f;
engine.getAudioEngine().playEvent(evt);
}
#endifWave types (WaveType)
| Type | Role |
|---|---|
PULSE | Square wave; use duty (e.g. 0.125, 0.25, 0.5) |
TRIANGLE | Triangle wave; duty unused |
NOISE | See Noise channel semantics below |
Noise channel semantics
frequencyon a NOISE event does not set musical pitch inApuCore. It drives the noise clock: default period in samples issample_rate / max(frequency, 1 Hz)whennoisePeriod == 0. Lower values → coarser / more “hit-like”; higher values → denser noise. UsenoisePeriodfor fixed percussion periods.- All platforms share the same 15-bit NES-style LFSR inside
ApuCore; step rate followsnoisePeriodSamples/noiseCountdown(andAudioEvent), notrand(). - Period sweep: with
sweepDurationSec > 0andsweepEndHz > 0,NOISEinterpolates the LFSR clock from the initial period toward the period implied bysweepEndHz(descending “scream” / boom effects).
Linear sweep and loop (AudioEvent)
| Field | Melodic waves | NOISE |
|---|---|---|
sweepEndHz | Target frequency (Hz) | Target LFSR clock (Hz) |
sweepDurationSec | Sweep length (seconds) | Same |
loop | Hold voice until STOP_CHANNEL or steal | Same |
- One-shots:
duration > 0andloop == false(default). - Continuous:
loop == true; duration is not used as a finite gate. duration <= 0withloop == falsedisables the voice immediately (safe no-op).
Arpeggios and fanfares are not built into the Engine: schedule multiple playEvent calls at time offsets (Tool Suite exported banks provide sequenceStepCount / sequenceStep helpers — see Tool Suite SFX_ENGINE_ABI_REFERENCE.md).
Master volume
engine.getAudioEngine().setMasterVolume(0.75f);
float v = engine.getAudioEngine().getMasterVolume();Per-channel volume is set per AudioEvent::volume; there are no separate setChannelVolume APIs in the core engine.
Music (MusicPlayer)
Sequencing is sample-accurate and tick-based inside ApuCore. MusicPlayer only enqueues AudioCommands (MUSIC_PLAY, tempo/BPM, pause/resume, stop). See Music Player API and the long-form Music player guide.
Multi-track layout
Point optional MusicTrack pointers from the main track: secondVoice, thirdVoice, percussion. Each sub-track has its own notes, loop, channelType, and duty (e.g. melody on PULSE, drums on NOISE). MusicPlayer::getActiveTrackCount() returns how many layers were requested on the last play() (1–4).
Example project
The music_sequencer demo showcases multi-track arrangements, instrument presets, and live transport: audio/music_sequencer in PixelRoot32-Demo-Projects. Its src/assets/songs/ also carries four complete exported pieces. For effect playback see audio/sfx_bank; for lighter in-game music use see games/2048.
#include <audio/MusicPlayer.h>
#include <audio/AudioMusicTypes.h>
using namespace pixelroot32::audio;
static const MusicNote MELODY[] = {
makeNote(INSTR_PULSE_LEAD, Note::C, 0.20f),
makeNote(INSTR_PULSE_LEAD, Note::E, 0.20f),
makeRest(0.10f),
};
static const MusicTrack GAME_MUSIC = {
MELODY,
sizeof(MELODY) / sizeof(MusicNote),
true, // loop
WaveType::PULSE,
0.5f // duty for pulse tracks
};
void MyScene::init(pr32::core::Engine& engine) {
engine.getMusicPlayer().play(GAME_MUSIC);
}The music sequencer lives in ApuCore. If the audio consumer stops running for a long time (debugger, host suspend), the next generateSamples may advance many ticks in one block (more CPU in that step; there is no fixed per-quantum note cap).
Sound profiles
The engine ships three profiles. Legacy is the default and a frozen contract — its rendered PCM is pinned by immutable goldens and does not change between releases, so a game keeps the sound it was tuned against. Nes and Famicom are opt-in characters.
| Profile | What changes |
|---|---|
Legacy (default) | Nothing: the historical rational mix curve, bipolar noise, continuous PULSE duty, ideal SAW ramp, single-pole HPF |
Nes | Linear envelope plus the 4-bit nesEnvelope, NES-weighted mix, unipolar noise on the NES period LUT, PULSE duty snapped to the four NES steps, ideal SAW ramp, and the front-loading NES output stage: HPF 90 Hz → HPF 440 Hz → Butterworth LPF at min(14 kHz, 0.45·fs), trim +1.10 dB |
Famicom | The Nes character with the Famicom output stage instead: a single HPF 37 Hz → the same LPF, trim −0.27 dB. It keeps the bass and kick fundamentals the NES chain removes (at 65 Hz the APU measures −1.2 dB against −21.1 dB for Nes) |
Famicom is value 2, the value earlier APU releases called Hybrid. SoundProfile::Hybrid still compiles as a deprecated alias of Famicom, but since APU 2.3.0 value 2 sounds different: decays are linear, SAW is the ideal ramp, the low end is kept and the master level is lower. Replace Hybrid with Famicom to silence the warning, and re-check content tuned for the old Hybrid by ear.
Switch it with a command, from the game thread:
#include <audio/AudioTypes.h>
pr32::audio::AudioCommand cmd{};
cmd.type = pr32::audio::AudioCommandType::SET_SOUND_PROFILE;
cmd.soundProfile = static_cast<uint8_t>(pr32::audio::SoundProfile::Nes);
engine.getAudioEngine().submitCommand(cmd);Or call setSoundProfile() directly on the audio thread through getApuCore(). Both produce identical state; the command is the documented path from the game loop, and it is queued like any other command. init() does not reset the profile, so restarting the audio stream keeps your choice.
What to expect when you switch:
- The level is matched; the peaks are not. Both audible profiles carry a trim matched on crest-weighted loudness against
Legacy, so a switch changes character rather than volume. Their transients are hotter: roughly 37 % (Nes) and 20 % (Famicom) of full scale on the APU's canonical track against 18 % forLegacy, and about 52 % (Nes) against 36 % on a dense mix (the APU has not measuredFamicomon a dense mix). A game that mixes by peak should re-check its master level. NesandFamicomrender the integer core on every platform — desktop, ESP32, ESP32-S3 and ESP32-C3 alike. That is what makes them identical across targets, and it is why their CPU cost is the integer cost.- Every profile renders the ideal SAW ramp, aliasing included; the NES profiles keep it on purpose, because their character deliberately reproduces the NES's own artefacts. The APU's band-limited SAW is dormant.
SINEis untouched on every profile. - The default envelope is linear under every profile. A note gets the exponential DECAY/RELEASE only when its preset asks for
EnvelopeCurve::Exponential. - Drums under the NES profiles.
INSTR_KICKandINSTR_SNAREkeep their authored noise period (60 and 15 samples) underNesandFamicom, so the kick keeps its body and the snare its crack;INSTR_HIHATtakes NES period LUT index 0, the bright NES hi-hat.Legacyplays all three at their authored period.INSTR_KICK_TRIon a TRIANGLE track glides from 196 Hz to 50 Hz in 45 ms; double it with a short NOISE hit on the same step for the classic NES attack. - An explicit
setHpfCutoffHz()wins over the profile chain and suppresses the level trim with it: that call asks for the historical one-pole, level included. - On
esp32-c3-devkitm-1, 32 kHz is not viable forNes/Famicom: at eight voicesNesmeasures 50.1 % of the block against the half-block rule the scheduler needs, whileLegacykeeps it at 48.7 %.Famicomdoes the same per-sample work asNes; it was not measured on that board, so it is not expected to fit at 32 kHz either. Stay at 22 050 Hz on that board, or stay onLegacy.
Hear all three side by side in examples/apu_profiles, which renders the same track under each profile.
Command queue and thread safety
- Only one thread should call
playEvent,setMasterVolume,MusicPlayer, andsubmitCommand(SPSC contract). The ring holds 64 commands, 63 of them usable. - If the queue is full, the newest command is dropped.
ApuCoreincrements an atomic drop counter and may emit a throttled warning whenPIXELROOT32_DEBUG_MODEis defined. Avoid enqueue storms without the audio thread draining the queue.
Audio configuration
Backends are concrete objects passed by pointer on AudioConfig, not an enum:
#include <audio/AudioConfig.h>
#include <drivers/esp32/ESP32_I2S_AudioBackend.h>
pr32::drivers::esp32::ESP32_I2S_AudioBackend audioBackend(26, 25, 22, 22050);
pr32::audio::AudioConfig audioConfig;
audioConfig.backend = &audioBackend;
audioConfig.sampleRate = 22050;
// Render block in samples: a multiple of 128, at most PR32_AUDIO_MAX_BLOCK_SAMPLES
// (1024). Leave it alone unless you are trading latency for wake-ups:
// the default is 512 on FPU platforms and 1024 on no-FPU platforms.
// audioConfig.blockSize = 512;
pr32::core::Engine engine(displayConfig, inputConfig, audioConfig);Block size, latency and underruns
AudioConfig::blockSize is the render unit: the backend asks AudioEngine::generateSamples() for exactly that many samples per iteration, and the I2S and DAC backends validate it in init() (rejecting with an error log anything that is not a positive multiple of 128, or that exceeds PR32_AUDIO_MAX_BLOCK_SAMPLES = 1024). The render buffer is a member of that size, not a stack array.
The DMA depth is derived from the block, never hard-coded: dma_buf_len = 128 stays fixed and dma_buf_count = clamp(blockSize / 128, 2, 8).
| Platform | blockSize | DMA ring | Latency @22 050 Hz | Latency @32 000 Hz |
|---|---|---|---|---|
| Dual-core (FPU) | 512 | 128 × 4 | 23.2 ms | 16 ms |
| Single-core (no FPU) | 1024 | 128 × 8 | 46.4 ms | 32 ms |
Because the block is also the command granularity, a queued command may be applied up to one block later than it was submitted — that is the trade for the lower wake-up rate.
Underruns are counted, not guessed: an iteration counts as an underrun when the i2s_write barely waited (writeUs < budgetUs / 10, i.e. the DMA ring was already empty), or when the write failed or came back short. The first 10 iterations are discarded because they fill the ring; a healthy write normally blocks for most of the block period. getUnderrunCount() reports the accumulated count, and getWorstRenderUs() reports the worst synthesis time per block, which is what tells you whether the voices you asked for are the voices being rendered.
One backend instance is ~2 KB: sizeof(ESP32_I2S_AudioBackend) and sizeof(ESP32_DAC_AudioBackend) are 2 096 B each on esp32dev (1 024-sample render buffer plus the counters). Give it file scope or heap — never a local inside a small-stack task; the audio task it creates itself runs with 4 KB.
See AudioEngine for AudioConfig fields and architecture links.
Platform differences
| Platform | Mixer | Noise (typical) | Audio execution |
|---|---|---|---|
| ESP32 (FPU) | Float + soft clip + HPF | Clocked LFSR | Backend task; core from PlatformCapabilities |
| ESP32-C3 (no FPU) | LUT + Q15 Fixed-Point HPF | Clocked LFSR + Q15 LFO | Same; integer path with Q15 LFO and HPF, static function pointer dispatch for wave generation |
| PC (native) | Float + soft clip + HPF | Same LFSR as firmware | std::thread + ring buffer → SDL2 callback |
That table describes the default Legacy profile. Nes and Famicom render the integer core on every platform — the FPU row included — and add their output stage on top of the summed mix.
Best practices
- Keep SFX
durationshort when possible; only four logical channels exist, with voice stealing among channels of the sameWaveType. - Use NOISE
frequency/noisePeriodto shape percussion vs hiss (see above); for authored drums preferINSTR_*presets on apercussionsub-track. - Do not rely on multiple threads calling
playEventwithout a different queue design. - Test on real hardware; buffer sizes and backend (I2S vs DAC) affect latency.
Next steps
- Audio architecture — Subsystem narrative (kept in sync with the engine)
- AudioEngine & types — Methods,
AudioEvent,AudioCommand,AudioConfig, music transport queries - AudioScheduler — Schedulers vs
ApuCore - MusicPlayer — Tracks, presets, tempo/BPM
examples/apu_profiles— The three profiles on one track; the shortest way to hear whatNesandFamicomchange- Engine source:
ApuCore.h/ApuCore.cpp— authoritative implementation
