The engine consumes AudioExtractor schema-3 assets without loading a ROM,
Snes9x, FFmpeg or the extractor assembly. WAV, FLAC and MP3 use one playback
API. XSharp.Audio.NAudio contains the Windows decoder/output backend;
Direct3D9 and SDL (and therefore Direct3D11/OpenGL) reference it instead of
compiling separate audio implementations inside renderers. Portable metadata,
cache contracts and loop/cursor logic remain in XSharp.Engine.Sound.
Register sounds in an entity’s [Precache] method or LevelDefinition.OnLoaded,
inside level loading. Call PlaySound/PlayOST later during gameplay. Registration
that would open/decode an asset after LevelAssetsPrecached is rejected.
Paths are relative to engine.SoundAssetsDirectory, which defaults to
Assets/Sounds. Keep the generated game directories in that asset tree.
Executable hosts opt in by importing build/NativeAudioAssets.targets, as
XSharpDemo and XSharp.LevelSandbox do. This copies locally present assets to
that application’s build/publish output. The engine library does not export
native audio as transitive content: libraries and tests must not receive a
complete copy merely because they reference the engine. An external asset
root can be supplied with the XSharpNativeAudioRoot MSBuild property.
engine.PrecacheSoundFromManifest("Native Track", @"Native\X2\Music\manifest.json", 0x19);
engine.PlayOST("Native Track");
The ID is the original native command/preset, not an ordinal in the manifest. Aliases share the cached file; reserved/silent entries cannot be played and produce a clear missing-audible-entry error. The same API accepts an effect context’s manifest and follows its relative reference into the shared Clips directory. Engine asset references must remain inside the sound asset root.
Direct file registration also reads a sibling manifest.json automatically:
engine.PrecacheSound("Native Track", @"Native\X2\Music\x2-music-19.flac");
engine.PlayOST("Native Track");
Use manifest registration for shared effect files, whose context manifest is not in their Clips directory. Format selection follows the file referenced by the manifest; regenerate with the extractor’s desired format to switch it. Existing authored sound names/legacy OST registrations are not automatically remapped to unidentified native song IDs. The game/level registers its intended track explicitly, as in the examples above.
Playback without time arguments uses the manifest’s loop start and exclusive
end. A finite entry plays once. Existing PlaySound/PlayOST overloads with
explicit time arguments override the manifest, preserving authored custom
loops. Do not reuse time offsets from an older OST recording for a newly
extracted track. Clearing the stop point restores the decoded file endpoint.
The loader verifies the encoded SHA256, actual decoded rate/frame count and, for WAV/FLAC, the decoded lossless PCM SHA256 before caching the sound. Manifest frames convert to bytes using the actual decoded block alignment: there is no round trip through seconds or encoded-file offsets. Loop start and end are enforced inside an audio callback, including callbacks that cross the boundary repeatedly. The intro is played once; subsequent passes start at the declared loop start. Explicit invalid/empty loop ranges are rejected.
WAV uses its PCM/float reader; FLAC decodes sequentially through Windows Media Foundation. Its reported duration is not trusted: actual PCM EOF determines the length. Windows needs its FLAC decoder (validated on this computer). MP3 uses pinned NLayer 3.0.0 with gapless delay/padding handling. The backend also reads FFmpeg’s Lavc-identified LAME-layout Xing/Info fields, which that NLayer version does not otherwise recognize. It removes encoder/decoder latency and tail padding so extractor loop coordinates retain their origin. MP3 is lossy and is checked for decoded timing/alignment and numeric tolerance, not for equality with the original lossless samples. The cached MP3 output remains PCM16, preserving the byte layout used for existing MP3 channel positions rather than changing those units to float32.
Decoding happens once at precache time. Subsequent seeks address cached PCM, avoiding compressed-codec keyframe approximations or decoder restarts at each loop. Caches up to 8 MiB stay in memory; larger songs spill into temporary PCM files marked delete-on-close. Unloading/disposal removes those temporary files. This trades initial decoding and temporary storage for exact cached-PCM seeks. No encoder executable or persistent decoded-file library is needed at runtime.
Explicit OnLoaded declarations remain roots of the final precache pass even if
their actors are not yet placed. Optional enemy definitions prepare their source
game’s Common bank directly, independently of the host assembly name. This covers
mixed-game content and data-selected children such as the two weather-capsule
creatures. XSharp.LevelSmoke --penguin 0 --mixed-content-audio --content-root=...
exercises X2 capsules/children and an X3 volley inside the imported X1 stage.
Older native SFX states can contain filenames from before semantic renaming.
While restoring, the engine resolves their stable Native/<game>/<context>/<ID>
cache aliases against the current manifests and temporarily redirects saved file
references. PCM positions and explicit loop/stop coordinates retain their existing
serialization; no duplicate media or state-format change is required. The redirect
scope ends before gameplay. Ambiguous aliases mapping to different current clips
are rejected, and legacy/different-game paths are not guessed. This supports
filename-only changes with a compatible decoded asset collection; it does not
certify playback equivalence after replacing the underlying audio content.
The level remains in loading until its placed actors, their statically created
projectiles/effects/drops, the Ready HUD and relevant native Common SFX banks are
prepared. Managed metadata inspection follows entity creation calls, typed factory
helpers and compiler-generated callbacks without instantiating actors or executing
their AI/RNG. It does not scan and load every installed content module. Explicit
PrecacheEntityAssets<T>() / PrecacheEntityAssets(Type) declarations cover factory
types selected from data or opaque external callbacks; the common enemy profile’s
ChildType and DeathChildType use that path. A custom level declares those dependencies
in OnLoaded; a content module can declare them from its actor’s [Precache] method.
PrecacheNativeSoundContext(game, context = "Common") prepares every audible ID
in the selected bank and deduplicates shared files through the existing decoded
cache. Missing optional banks are remembered. HasNativeSoundAssets and
PlayNativeSound subsequently consult dictionaries only. Non-Common contexts and
extra music tracks need explicit declarations during loading. Music is not decoded
wholesale just because a game’s SFX bank is used.
The native bridge previously loaded/hashed/decoded its first requested clip from
inside PlayNativeSound; player projectiles could also first run Weapon.Precache
when firing. Both operations now finish during level precache. Cached legacy file
registration also skips sibling-manifest probing. The engine rejects a new sound,
image asset or uncalled [Precache] action during gameplay with a dependency error.
Device recreation and save-state restoration have explicit loading scopes; after
restoration native aliases are rebuilt before simulation resumes, including for
older states that omitted those clips. This does not change source PCM or loop points.
The regression tests remove all WAV/FLAC/MP3 source files after precache and then
play each for the first time. The DX9 Penguin smoke fires normal/charged busters,
spawns an explosion, plays a native command and round-trips a state while checking
that gameplay did not grow the audio cache or discover additional entity actions.
It also forces all five ordinary enemy drops through Enemy.OnBroke before and
after restoring the state: small/large ammo, small/large health and a life-up.
Concrete entity return types are recognized regardless of the helper method’s
name, including DropSmallAmmoRecover; property getters/conversions that merely
return an existing actor do not by themselves declare a child. The original smoke
did not kill enemies and missed this drop dependency regression; the expanded
smoke reproduces the reported exception before the fix.
Run it with:
dotnet run --project tests/XSharp.LevelSmoke -c Release -- --penguin 0 --asset-precache --content-root='C:/path/to/XSharpDemo/bin/Release/net9.0-windows7.0'
The content-root option shares an existing host asset directory, avoiding another copy of regenerable native audio in test output. This smoke checks those paths; new scripted content must still declare dependencies selected dynamically.
Every channel has an independent PCM position, including in save states. Shared-source reads are synchronized. A channel does not own or dispose the engine’s cached audio. Finished finite clips release their playback guards; ignored updates preserve the active channel cursor/device. The Windows output device is reinitialized when switching rates or PCM sample formats, preserving volume and avoiding playback at the preceding track’s rate.
Device stops are asynchronous in NAudio 2.2.1. The backend joins the previous
output worker before changing the source, restarting, restoring a save state,
replacing a device or disposing it. Merely observing PlaybackState.Stopped
is insufficient: the old worker can still be executing its final state write.
Outputs are created without a UI synchronization context so joining from the
game/UI thread does not depend on a notification posted back to that thread.
Control operations on a channel are serialized; callbacks signal completion
without acquiring the channel control lock. PlaybackCompletion describes the
latest device run, including draining queued audio; the PCM reader’s Playing
flag alone does not describe that drain. LastPlaybackException exposes an
asynchronous output failure. See restart regression.
The runtime follows the manifest precisely; it does not improve the extractor’s source-level timing estimate. Current music loops have a roughly 16 ms native sequencer-grid precision, not sample-exact recurrence of the complete SNES DSP state. See loop analysis.
dotnet test XSharp.Audio.Tests -c Release
$env:XSHARP_TEST_NATIVE_AUDIO = (Resolve-Path XSharp/Assets/Sounds/Native).Path
$env:XSHARP_TEST_NATIVE_AUDIO_REPORT = "$PWD/docs/native-audio-playback-validation.json"
$env:XSHARP_TEST_AUDIO_DEVICE = '1'
# Optional: set XSHARP_TEST_NATIVE_MP3_MANIFEST to a real extracted MP3 manifest.
dotnet test XSharp.Audio.Tests -c Release
The default tests use small original synthetic fixtures, not game audio, and need no ROM, encoder, graphics or playback device. Optional environment settings enable complete real-asset decoding, a real extracted MP3 and a muted physical output smoke test. The real collection report covers all 555 unique files, their lossless PCM hashes and all 80 unique looping files (82 preset loop references through aliases). The output smoke switches WAV/FLAC/MP3/WAV across 32040/44100 Hz, followed by a synthetic 48000 Hz float32 source to exercise sample-type switching too. Neither test is an acoustic capture/comparison with the original console.
The general engine suite also ran: 1,854 passed, 19 skipped and 32 failed in
CommonEnemyIntegrationTests. The identical 32 cases reproduce with the previous
BaseEngine implementation, whose original PrecacheSound also reaches missing
sound-cache fields in that headless fixture. The comparison isolates the engine
precache/manifest integration while retaining the current shared sound helpers;
it is not a full historical-checkout validation. See
native-audio-playback-regression.json for the bounded comparison. The focused
audio suite and 49 boss music dispatch tests pass. Desktop demo Release builds
with DX9, DX11 and OpenGL references also pass.
Primary implementation references:
The Lavc header adapter is an independent implementation of those format fields; upstream source files are not copied into the engine. NuGet dependencies retain their own licenses. The backend has no dependency on the extraction toolset.
Actor/object command routing and semantic asset naming are documented in native content sounds.
Extracted effects retain the unnormalized native PCM level, whereas legacy effects
were already louder. Six X1 reference pairs showed a median active-sample RMS gap
of 8.68 dB (measurement threshold abs(sample)>0.001, not integrated loudness).
BaseEngine.NativeSoundGain defaults to 2.75 (+8.79 dB) for paths under
Native/<game>/Sfx/. Set it to 1 for unmodified capture-level playback, or 0 to mute
that category. Legacy sounds and Native/<game>/Music/ keep unity gain.
NAudio applies this multiplier in each stream, separately from the logical channel volume: the normal 0.25 effect channel produces 0.6875 output volume. The effective software level is bounded to [0,1]; WaveOut hardware volume stays at unity. A real-device regression showed that this driver shares hardware volume between WaveOut handles, so device-level amplification would also change the music. Software PCM attenuation keeps channels independent and supports PCM8/16/24/32 and float32/64 output without editing the shared decoded cache. The adjustment is set before playback, resets when a channel is reused for legacy audio and survives format/device replacement without multiplying twice. Save-state channel volume retains its original layout; source gain is derived again on restore using the current mix setting. PCM caches, encoded files, manifest hashes, frame counts and loop positions remain unchanged. This balances the existing mixed asset collection; it is not an SPC mixer or a per-effect loudness normalization pass.
Measurements are reproducible with
python tools/Measure-NativeEffectLevels.py --ffmpeg <ffmpeg.exe>.
Declared non-Common native banks are rebuilt during save-state loading alongside Common banks. Unavailable optional contexts retain their declaration too; restoration must not turn a silent optional asset into an undeclared first-use load. The mixed-game DX9 smoke covers X2 Overlay-5B through a real full-state round trip inside X1 Penguin, including live generic projectile owners.
Native sustained effects may request a host-owned channel with the optional
PlayNativeSound(..., channelIndex: 5) argument. Short actor effects continue to
use only 4/6/7. Optional same-frame deduplication distinguishes explicit channels
from the shared pool. StopNativeSound(channel, game, command, context) uses the
prepared stable alias, checks the current source and stops its provider/device tail
without loading assets or stopping a different replacement source. The channel
count and serialized audio layout are unchanged. Penguin’s native 72 breath is a
finite clip on channel 5; it does not inherit the old WAV’s manually authored loop.
A fixed-source actor can declare [NativeSoundGame(OriginalGame.X2)] independently
of its assembly name. The default Enemy.SoundGame getter and final entity precache
share that identity; preparing a declared actor for a later spawn does not require
constructing it. Fixed metadata may also declare an object’s bank. Owner/data-driven
overrides continue to declare their context through [Precache]/EnemyDefinition;
the engine does not instantiate an entity to evaluate such a property during loading.
Native context aliases preserve equivalent preset/overlay names without another recording or PCM cache. Prepare aliases explicitly during loading. Their canonical command map and declaration survive state restoration; gameplay performs no alias-manifest or filesystem probes.