Repository navigation
Stop WaveOut queueing a buffer again after Stop() resets the device - #1516
Merged
Merged
Conversation
If Stop() ran while the playback thread was inside the source's Read, the thread then called waveOutWrite after waveOutReset, putting the buffer back in the device queue. The device kept playing it after Stop(), and Dispose() then unprepared a buffer the driver still owned: since #1502 that buffer is leaked rather than freed, and waveOutClose fails with WAVERR_STILLPLAYING, leaving the device open. - WaveOutBuffer takes an optional gate that is checked under waveOutLock just before waveOutWrite. WaveOut passes one that refuses once the state is Stopped. Stop() sets Stopped before taking that lock to reset, so no write can follow the reset. - WaveOut keeps its playback thread and waits for it in Dispose(), in Init() when re-initialising, and in Play() after a Stop() (otherwise the old thread could resume queueing and then set the state back to Stopped under the new one). It skips the wait when called from the playback thread itself, e.g. from a PlaybackStopped handler. - Dispose() resets the device before unpreparing buffers, and the callback event is closed after the device rather than before it. - WaveOutWindow checks its state inside waveOutLock in the callback, for the same reason. Fixes #1515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FffhFbNE3FjRzf35ztiVkA
Contributor
Author
Tested on Windows with a real audio deviceWindows 11 Pro (build 26300), .NET SDK 10.0.400, default output device. Branch head Integration tests (
Repro program from #1515 (with
Manual testing in NAudioDemo (Audio File Playback): repeated play/stop, stop-then-play, and closing the app while audio was playing, with both WaveOut and WaveOutWindow. Playback stopped promptly and nothing went wrong. 🤖 Generated with Claude Code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #1515 on
main. IfStop()ran while the playback thread was inside the source'sRead, the thread then calledwaveOutWriteafterwaveOutReset, putting the buffer back in the device queue. #1502 already stops this from crashing, but it still caused:BufferMilliseconds) of audio playing afterStop()returned;Dispose()leaking that buffer and its header (theWaveStillPlayingpath), andwaveOutClosefailing withWAVERR_STILLPLAYING(result ignored), so the device stayed open;Dispose()not waiting for the playback thread, so the thread could fail a write on a disposed buffer (a spuriousMmExceptioninPlaybackStopped) or read from a source the caller had already disposed.Changes:
WaveOutBuffertakes an optionalcanQueuecheck, evaluated underwaveOutLockimmediately beforewaveOutWrite.WaveOutpassesplaybackState != Stopped.Stop()setsStoppedbefore taking that lock to callwaveOutReset, so no write can follow the reset. This doesn't makeStop()block, so it leaves WasapiOut.Stop should probably not block until playback thread joined #1248 open.PlaybackStoppedhandler on that thread) inDispose(), inInit()when re-initialising, and inPlay()afterStop(). Without that last one, the old thread could finish itsRead, seePlayingagain and keep queueing, then set the state back toStoppedunder the new thread on its way out.waveOutCloserather than before. The Harden file parsers against malformed input #1502 leak path stays as a safety net that normal shutdown no longer reaches.WaveOutWindow: moved thePlayingcheck in the buffer-done callback insidewaveOutLock, for the same reason. It only uses window callbacks, which arrive through the message loop rather than synchronously insidewaveOutReset, so taking the lock there can't deadlock againstStop().One remaining edge case, the same one as #970: with no synchronization context,
PlaybackStoppedruns on the playback thread. A handler that makes a blocking call to a thread that is itself insideDispose()/Play()would deadlock. That isn't a concern when theWaveOutis created on a UI thread, because the handler is then posted.The 2.x backport is a separate PR against
release/2.x.Release notes
### Unreleasedsection of RELEASE_NOTES.mdTesting
New
WaveOutStopRaceTestsinNAudio.Windows.Tests, taggedIntegrationTestbecause they need a real WinMM output device (CI skips them):Stop_WhileSourceIsReading_LeavesNoBufferQueued: the reporter'sslowinterleaving, then checks that no buffer is queued, using a new internalWaveOut.AnyBufferQueuedDispose_WhileSourceIsReading_WaitsForThePlaybackThreadPlay_ImmediatelyAfterStop_KeepsPlayingDispose_FromPlaybackStoppedHandler_DoesNotDeadlockNot yet run: this was developed on Linux.
NAudio.Windows.Testsbuilds (-p:EnableWindowsTargeting=true),NAudio.Core.Testspasses (1779 passed, 0 failed, 3 skipped), anddotnet packofNAudio.WinMMandNAudio.WinFormspasses package validation. Before merging, the new integration tests (and ideally the repro program from #1515) need a run on a Windows machine with an audio device.Generated by Claude Code