Finding the sound files

Retail reads sound data by PROT.DAT entry number. A dev-station path (h:\...) survives in the same functions but is never taken on a retail disc: the split is the build-mode global _DAT_8007B8C2, and the dev arm opens files through a host trap that has no disc to read.

PieceWhat it does
Path-string clusterThe extensions the sound code appends to scene-asset paths - .spk, .LZS, .dpk, .MAP, .PCH, .pac, STR - plus the master file bse.dat. Layout on sound-driver outputs. The .MAP / .PCH / .spk / .pac SoundArtist intermediates are not present as separate retail chunks
Sound init FUN_8001FA88Loads bse.dat - the battle occupant of the >= 0x200 SFX descriptor bank - at battle-scene setup; its only caller is battle init FUN_800513F0
Streaming loader FUN_8001FC00Builds paths under sound\; the XA / .pac / STR consumer and the streamer every bank install goes through
Bank installer FUN_8001E54CWalks the streamed chunk list: takes the header buffer and the VAB slot from the 12-byte mixer record at 0x80091508 + category*12, opens the bank (SsVabOpenHead + SsVabTransBody), and opens a type-2 chunk as the slot's score with SsSeqOpen
Monster bank loader FUN_8003E104Reads monster.snd's per-monster TOC ([start_lba, end_lba + 1] pairs) and streams one bank into slot 7 or 8; also streams the victory-voice tail clips at results time

The victory-voice pick, in the results sequencer FUN_8004E568: a pose tier from the pose actor's HP (≥ 3/4, ≥ 1/2, ≥ 1/4, below; a status in mask 0x107B forces tier 4), a pose action id from the per-character table at 0x800788A0, then a clip byte at 0x80078867 + action + char_id*8. Per-character clip bands: Vahn 0xB8..0xBC, Gala 0xBD..0xC3, Noa 0xC4..0xCB. The clip lands in VAB slot 7 over the formation's monster bank, and the win-pose clip's own cue track keys it: every pose fires cue 0xA1, a party cue that sounds in slot 7.

A third “mode-aware extension dispatcher” that turns up in call graphs is not a sound consumer at all - it is the character-mesh equipment group-transform swap (character mesh).

The track-swap handshake

The BGM poller FUN_800243F0 runs a stage counter through a seven-entry jump table while a track change is in flight: wait for CD idle and arm a 30-frame settle; tear down and close the BGM slot unless bit 0 below is set, then kick the async load; count the settle down; install the score; re-attach the slot unless bit 1 is set; latch. The sound-flag word _DAT_8007B750 coordinates it with the script:

Scriptop 0x35 Flag word0x8007B750 PollerFUN_800243F0 sub-op 9: store the new id, set bit 0 wait for CD idle, arm a 30-frame settle bit 0 set: the old track keeps the slot kick the payload load, count the settle down set bit 3 - load settled stall while bit 0 is set and bit 4 is clear sub-op 0xA sees bit 3 detach and close the old track set bit 4, clear bit 1 install the score, re-attach the slot clear bits 0, 3, 4; latch the loaded index
A swap started by sub-op 9 and committed by sub-op 0xA: the old score holds its slot until the script releases it, so a cutscene picks the exact beat the outgoing music dies on.
BitMeaningSet byCleared by
0script-owned start pending (defer the slot teardown)sub-op 9poller commit, scene entry
1BGM slot paused / detachedsub-op 2, 3, the dance overlaysub-op 1, 4, 0xA, scene entry, game over
2"music not change": keep the audio across the next scene load. The scene initializer skips its music fade-and-close and its effect-voice cut, and the poller marks any track request as loaded without loading itsub-op 6field overlay
3load settled - payload staged and delay elapsedthe pollerpoller commit
4release-ack - the script has released the old occupantsub-op 0xApoller commit

After setting bit 3 the poller stalls while bit 0 is set and bit 4 is not, so a swap started by sub-op 9 keeps the old track until the script commits with sub-op 0xA, which detaches and closes the old occupant, sets bit 4 and clears bit 1. A port that honours the sub-op 2 pause but drops the 0xA commit leaves the music paused after the cutscene.

A door keeps its music only behind sub-op 6. Every scene load decides the music on bit 2. With it clear, the initializer fades the field track out while the map reads, closes it, and loads the new scene's track afresh - even the same one, so a plain door restarts the score. With it set, the track keeps playing and the new scene's start is marked as loaded without loading: the track word names the new scene's music while the old one plays on. The new scene's first script slice runs inside the load, before the bit is cleared, so its opening start is the one that gets marked. The disc uses it as the "same area" mark: town interiors, the kingdom maps' doors and the Sol tower floors raise it on their doors, and so do some overworld entrances: walking into Son from the overworld keeps the overworld theme playing under Son's own parked word. A retail state leaving the opening shows it: on the overworld the word is the overworld theme while the opening's track still plays.

The walk takes time on screen. One stage runs per game frame, the 30-vsync settle counts down from the first, and stage 3 waits on the CD read of the track's bank. Measured on retail from a field state, the read is the longer of the two: about 56 vsyncs whatever the bank's length, so a track started mid-scene is first heard 66 to 69 vsyncs (a little over a second) after the op, with the old track's slot closed about six vsyncs in. The commit 0xA re-runs its own instruction until bit 3 rises, and a second sub-op 9 waits while a swap is in flight, so the script stalls on the same clock. A scene's entry track is the exception: the field init calls the poller in a loop with no vsync wait, so the settle runs out at once and the read is part of the load. The port runs the same walk on its vsync clock.

010203040506070 vsyncs after the op's store (frame step 2) op 0x35 sub-op 1 stores the track word old track slot closed at stage 2 stages 0..2 CD idle, arm the settle, kick the read settle 30 vsyncs, run out long before the read stage 3 CD read of the new bank: about 56 vsyncs, whatever its length stages 4..6 settle check, install, re-attach at +66 new track silence: no slot sounds between the close and the first note at +69
One mid-scene start, measured on retail from retock (word 2001); town01 with 2045 lands within a vsync of it. The read, not the settle, sets the wait, and a script that commits with sub-op 0xA or issues a second sub-op 9 stalls on the same clock.

The libsnd calls under the control words settle their meaning: the pause raises a status flag and keeps the cursor; the play core rewinds the cursor to the start for every mode before it plays - which is why sub-op 4 is a replay from the first event, not a resume.

Sony's sequencer and SPU driver

libsnd (0x80061B18..0x800681D8) walks the SEQ bytes, keeps per-channel state in 16 slots of 0xB0-byte records, and turns note events into key-ons; Legaia installs two function-pointer hooks to wire the script VM's sequence context in. libspu (0x80068..0x8006D) pokes the chip's registers, runs the four-mode DMA transfer engine and the block allocator. Being the same libraries every PsyQ game shipped is what lets the functions be named.

libsnd functions

AddressPsyQ nameRole
FUN_80062340SsSeqOpenWalks the 16-bit slot bitmap at _DAT_801CD2B8, marks the first free slot, initialises it
FUN_80062410_SsSeqInitValidates magic + version, reads PPQN base, BPM, ticks-per-quarter
FUN_80061D18SsSeqCloseKey-off, clears the bitmap bit, resets the 16 channel records
FUN_8006275C / FUN_800628F0 / FUN_800641ECpause / play / stopFlag edits on the per-slot status word at +0x98: the pause raises 0x2 and keeps the cursor; the play core rewinds the cursor for every mode, then plays; the stop kills the notes and rewinds
FUN_80061C68_SsSeqGetVarVarint delta-time decode into the running tick at +0x88
FUN_80061EDC / FUN_8006206CSsSeqSetVol / _SsSetSlideVolumeVolume fetch and N-tick ramp
FUN_80067550_SsVoNoteOnThe key-on volume chain
FUN_80067E9C_SsSeqNoteOnSequence-driven key-on; calls the program-change
FUN_80065978_SsVoKeyOnDirectVoice allocation, region lookup, pitch + base note
FUN_80066E50 / FUN_8006C6E4_SsPitchFromKey / _SsKey2Pitch12-entry key table at _DAT_8007A940; two-octave table
FUN_80068B98VAB program-changeInstalls the current-bank globals, reads the packed tone-page index
FUN_80068D94SsVabOpenHeadBank open (see above)
FUN_800684CCKey-off by ownerKeys off every 0x36-stride voice record at 0x801CDB60 whose owner key equals the argument (seq | track << 8) - not a VAB-id search
FUN_8006CA7C / FUN_8006CDB0 / FUN_8006DDC8SsSeqGetStatus / SetCallback / SetMarkCallbackResolve the context through the Legaia hook _DAT_801CE564
FUN_80062AA0 / FUN_80065440SPU command shims×0x81 scaling, 0..127 to 0..16383

libspu globals, primitives and the transfer engine

AddressPsyQ nameRole
_DAT_8007AF40SPU register baseMMIO 0x1F801C00; +0x180 main volume, +0x1AA SPUCNT, +0x184 reverb output volume, +0x1B0 CD input volume, +0x1C0..0x1FE reverb block
_DAT_8007AFA4 / _DAT_8007AFF8Block table / master attribute structFree bit 0x80000000, end bit 0x40000000; 10 modes × 0x44
FUN_8006ACBC / FUN_8006C048SpuSetVoiceAttrMask-driven dispatcher; 24-voice broadcaster over 1 << i
FUN_8006BCB4SpuSetCommonAttrMaster volume, reverb registers, SPUCNT bits
FUN_8006B1B4SpuSetReverbModeParam30-attribute reverb commit
FUN_80069B18_spu_tFour-mode transfer state machine (arm read, arm write, stage address, commit); 0xF00-poll timeout
FUN_800697E0 / FUN_80069DA8_SpuTransfer / SpuWriteCPU-copy path in 0x40-byte chunks; DMA-vs-CPU pick
FUN_8006A158 / FUN_8006A728 / FUN_8006A420SsSpuMalloc / SpuFree / compactorFirst-fit walk, high-bit free, coalesce

An earlier “SsSepOpen / VAP SEP loader” reading of the bank open is falsified - the magic is the VAB's. See do-not-re-walk.

The port's audio model

crates/engine-audio is a from-scratch model; engine-session's AudioDirector turns field-VM sound events into sequencers and fires SFX cues against the banks their category names, generic over the output so the native window (cpal) and the browser (WebAudio) share it.

ModuleModels
spu::Spu, spu::voice24 voices with sample address, loop point, pitch, ADSR, L/R volume and reverb send; 4-point Gaussian resampling as the hardware does
spu::adsr, spu::adpcmFive-phase envelope with linear / exponential modes; streaming 28-samples-per-block decoder, one per voice
spu::reverbRegister-driven network (same / different-side IIR, 4-tap comb, 2 all-pass) with the nine standard presets
spu::ram512 KB model, libspu-shaped transfer engine, block allocator
vab_bind::VabBankUploads every VAG into SPU RAM; turns a MIDI key into voice config + key-on. Programs are slot-indexed
SequencerThe SsSeqOpen / Play / Close / SetVol / Rewind surface; round-robin voice allocation tracking (channel, key); a pitch bend that re-pitches what is sounding within per-tone limits and is then forgotten; loop markers from CC99 (20 = start, a data entry = its count, 30 = loop end)
sfxThe cue catalog built from the disc's descriptor table, fired against the bank each cue's category names, through a frame-accurate scheduler
AudioOut / WebAudioOutOne output stream draining the SPU at 44.1 kHz; hard-cut track swaps with a few frames of click guard; CD-XA clips mixed outside the 24 voices. The browser mixes on the page's main thread and posts blocks to an AudioWorkletProcessor, its queue set by how deep the page's own frames drain it (25 to 190 ms), with a ScriptProcessorNode fallback; a cue fired from a frame lands in about 80 ms against about 160 ms through the script processor alone.

Measuring the port against retail

The audio-trace oracle compares which SPU voices are active, frame by frame, against a real emulator running the retail disc. Two retail capture shapes feed it: a single-cycle snapshot lifted from a mednafen save state's SPU section, and a multi-frame trace captured in PCSX-Redux. A retail frame converges when some engine frame's active-voice set covers it with every start address matching; a start-address or master-volume mismatch is a hard failure, and so is an engine trace that sounded nothing where retail had voices. CLI: legaia-engine audio-trace.

Real retail PCM

The trace compares registers and notes; this compares sound. scripts/ci/audio-pcm.py (CLI legaia-engine pcm-retail) takes mednafen’s own output, recorded while it plays on from a library state, against the engine’s mix of the same bars. No listening is involved: every statement is a number off two waveforms, and “retail” here is an emulator’s model, since no real-console recording has been compared. Three channels split the blame: core is the SPU model alone with the sequences silenced, track adds the sequencer from the state’s own cursor, and xa isolates the CD input. A fourth, cast, scores a battle state mid-cast: the engine is seeded into the fight, its own mix is recorded from that instant with the music silent, and the recording is laid over the track render. Its first run found Zeto’s Call Wave playing Big Wave’s voice and landing as a hit on Zeto himself, both read off the module’s disassembly and both heard in the recording; with them fixed the cast reads correlation 0.999 at +0.01 dB. On the summons it found the drive: a summon module seeks the CD to its voice’s file and waits for the seek before it speaks, behind a seek the battle had just issued for the caster’s fanfare, and the port passed both waits at once, so Orb spoke a second early. The port now runs that drive on the seek law mednafen’s controller follows, and Orb’s and Swordie’s voices land within 64 and 6 ms of retail’s, at retail’s level: the summon’s audio duck, still ramping when the voice starts, lifts the CD input to full. Because a drive’s seek time varies across drives and emulators and the port keeps one model of it, the channel accepts the voice anywhere in a seek window: the part of the engine’s recording after the drive wait is aligned on its own, from the engine’s whole wait earlier to max(8, wait / 2) vsyncs later, and the shift and window are printed per state (Nighto 0.326 to 0.973, Theeder 0.722 to 0.904). The cast’s own offset reaches as far as the fight’s frame step, because the engine’s gate is a game-frame boundary and a step-3 fight puts the state’s instant up to three vsyncs from one: Cort’s Guilty Cross went from 0.859 to 0.981, Mystic Shield from 0.937 to 0.995 and Gilium from 0.852 to 0.991. Five of the summon states were saved with the options screen’s Sound row on Monaural, where libsnd plays every voice at its louder side on both; the oracle now renders them that way.

The battle frame step is the emulated machine’s measure of what a frame cost, and the port’s step tables are read off PCSX-Redux, while these recordings are mednafen’s. Stepped frame by frame, mednafen runs Guilty Cross’s and Zenoir’s arms at 2 or 3 where PCSX-Redux runs them at 4. A sixth channel, cast_steps, replays the cast on the recording’s own steps: Guilty Cross reads 0.981 there against 0.859 on the engine’s, so its whole loss is the two emulators’ frame costs, and Zenoir 0.893 against 0.855. Part of the gap is the GPU: mednafen times the drawing and PCSX-Redux does not, and a model of the GPU's draw time reads mednafen's waits closely. Which emulator's CPU cost a real console matches is still open (battle stage and camera).

The track channel reads correlation above 0.995 on the measured battle, town, title and minigame states, with every band’s level right where no retail cue is in the window. A low correlation with level right is timing, and scripts/ci/audio-note-fit.py gives it a cause: it splits the render into one stem per note and fits each note’s own offset and gain against the recording. Plotted against pitch, voice count and the vsync grid, each defect below read as a straight line or a clean cluster.

Below these, what the track channel still reads is a fraction of a sample per flush and retail’s own cues. ADPCM’s rounding is the open difference on the core channel: the port rounds the predictor, mednafen floors each term, and this oracle cannot say which the hardware does. A track reaches any bar 0.29% early because the port’s frame is a flat 60 Hz against the console’s 59.8261 Hz, the same factor the whole simulation runs ahead by, so the music stays locked to the game.

The output stage below the mix is the same on both hosts: a device not at 44.1 kHz goes through a windowed-sinc converter that is flat within 0.1 dB to 15 kHz. In Chromium the blocks the browser posts match a native-side render of the same session with no differing sample once aligned, so the browser differs from the desktop in latency and not in level.

History: “the engine is much the quieter side”

The comparison once read as the engine routing no reverb and sounding about half retail's voices. Both were instrument defects: the reverb figure was read from the SPU control register rather than the per-voice reverb-enable mask, and the oracle had built a bare SPU where the shipped host sets retail reverb. The voice-count gap was two different pieces of music - a town save reached from the world map still holds the overworld track.

Retail's own sound code beside the port

Two differentials run retail's routines off a library state's RAM in the R3000 interpreter and compare them with the port, so neither needs an emulator's audio output. legaia-engine seq-differential runs retail's sequencer tick FUN_80062F98 over a whole score beside the port's Sequencer and compares every sounding voice's registers at every vsync. legaia-engine cue-differential keys every sound-effect cue both ways in one state per scene, retail's side through FUN_80016B6C, and compares what each staged. Both are in a --features oracles build.

How we know

FunctionAddressWhat it proves
Sound initFUN_8001FA88bse.dat at battle init (caller FUN_800513F0), dev / retail split on _DAT_8007B8C2
Streaming loaderFUN_8001FC00The sound\ path builder every bank install goes through
Bank installerFUN_8001E54C / FUN_8002630CCategory to mixer record to slot; open through SsVabOpenHead
Record initialiser / SPU basesFUN_8001D424 / FUN_800265E8Twelve records, four pairs sharing a header and a base
Monster bank loaderFUN_8003E104monster.snd TOC and LBA range; slots 7 / 8
Per-actor SFX helperFUN_800250D4 / FUN_80065034Descriptor decode; program-change before program lookup
BGM pollerFUN_800243F0Resolver arithmetic, the seven-stage swap ladder, sound-flag bits
Op 0x35FUN_801DE840 case 0x35Sub-op semantics 1 / 2 / 3 / 4 / 6 / 9 / 0xA (script VM)
Arts shout selectorFUN_8004C140 / FUN_8003D53CChannel pool pick; CD-XA clip player; confirmed by PCSX-Redux call-site traces
Melee roll pairFUN_801EC3E4The blocked-strike grunt (gated on the defender's +0x1F3 block entry) and the 0x10C impact cue
Victory spoilsFUN_8004E568Pose tier, clip byte, reward bank slot 11
ReverbSPU register fileStudio C in every captured state

Full write-up: docs/subsystems/audio.md.