XSharp

Intermittent SFX truncation after native-audio playback changes

The user reported nondeterministic cuts during the Penguin demo, including X’s teleport-out after defeating the boss. The new audio implementation added StopPlayer() before each source switch to protect sample-format changes. In NAudio 2.2.1, however, WaveOutEvent.Stop() resets the device and signals its worker without joining it. An immediate Play() reuses the same player while the old worker may still be unwinding. The old worker’s finally assigns playbackState = Stopped, potentially stopping the newer playback. Competing workers can also reach the shared provider. This depends on thread scheduling, not on the deterministic gameplay input alone.

Primary evidence: pinned WaveOutEvent implementation, particularly Play, Stop, PlaybackThread, and RaisePlaybackStoppedEvent. No external source implementation is copied into XSharp.

Controlled reproduction and fix

With only an injectable IWavePlayer seam added to the previous channel implementation, two deferred-worker tests failed: restarting during a requested stop and restarting after the device reported natural Stopped but before worker exit. A third test confirmed that the output factory captured a UI synchronization context. This is a bounded comparison of the channel algorithm, not a full historical-checkout or acoustic reproduction of the boss encounter.

The fix tracks each output run’s worker completion. The controlling thread waits for PlaybackStopped before touching the provider or reusing/disposing the device. Output construction temporarily clears and then restores the caller’s synchronization context; the completion callback therefore does not need the blocked UI thread to dispatch it. Channel control operations are serialized. A five-second timeout rejects a restart if the device fails to finish stopping. Callback failures remain observable through LastPlaybackException. Save-state restore also stops/joins before replacing the reader’s state. PCM cache ownership, manifest frames and loop selection are unchanged.

Validation

Reproduction tests are in XSharp.Audio.Tests/OutputRestartTests.cs. Physical tests are opt-in in DevicePlaybackTests.cs; enable XSHARP_TEST_AUDIO_DEVICE=1 and set XSHARP_TEST_NATIVE_AUDIO to the Native asset root for the real X1 files. The normal build keeps native assets restricted to executable output directories. Recorded counts are also available in audio-restart-validation.json.