Skip to content

Stop WaveOut queueing a buffer again after Stop() resets the device - #1516

Merged
markheath merged 1 commit into
mainfrom
fix/1515-waveout-requeue-after-reset
Nov 26, 2026
Merged

markheath merged 1 commit into
mainfrom
fix/1515-waveout-requeue-after-reset

Conversation

@markheath

Copy link
Copy Markdown
Contributor

Summary

Fixes #1515 on main. 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. #1502 already stops this from crashing, but it still caused:

  • up to one buffer (BufferMilliseconds) of audio playing after Stop() returned;
  • Dispose() leaking that buffer and its header (the WaveStillPlaying path), and waveOutClose failing with WAVERR_STILLPLAYING (result ignored), so the device stayed open;
  • the callback event being closed while the device could still signal it;
  • Dispose() not waiting for the playback thread, so the thread could fail a write on a disposed buffer (a spurious MmException in PlaybackStopped) or read from a source the caller had already disposed.

Changes:

  • Gate the write under the lock. WaveOutBuffer takes an optional canQueue check, evaluated under waveOutLock immediately before waveOutWrite. WaveOut passes playbackState != Stopped. Stop() sets Stopped before taking that lock to call waveOutReset, so no write can follow the reset. This doesn't make Stop() block, so it leaves WasapiOut.Stop should probably not block until playback thread joined #1248 open.
  • Wait for the playback thread (with a self-join guard for calls from a PlaybackStopped handler on that thread) in Dispose(), in Init() when re-initialising, and in Play() after Stop(). Without that last one, the old thread could finish its Read, see Playing again and keep queueing, then set the state back to Stopped under the new thread on its way out.
  • Dispose ordering: reset the device before unpreparing buffers, and close the callback event after waveOutClose rather 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 the Playing check in the buffer-done callback inside waveOutLock, for the same reason. It only uses window callbacks, which arrive through the message loop rather than synchronously inside waveOutReset, so taking the lock there can't deadlock against Stop().

One remaining edge case, the same one as #970: with no synchronization context, PlaybackStopped runs on the playback thread. A handler that makes a blocking call to a thread that is itself inside Dispose()/Play() would deadlock. That isn't a concern when the WaveOut is 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

  • I've added a one-line bullet to the ### Unreleased section of RELEASE_NOTES.md
  • This PR doesn't need a release-notes entry (internal refactor, test-only, or docs fix)
  • Leave the release-notes entry for the maintainer to write

Testing

New WaveOutStopRaceTests in NAudio.Windows.Tests, tagged IntegrationTest because they need a real WinMM output device (CI skips them):

  • Stop_WhileSourceIsReading_LeavesNoBufferQueued: the reporter's slow interleaving, then checks that no buffer is queued, using a new internal WaveOut.AnyBufferQueued
  • Dispose_WhileSourceIsReading_WaitsForThePlaybackThread
  • Play_ImmediatelyAfterStop_KeepsPlaying
  • Dispose_FromPlaybackStoppedHandler_DoesNotDeadlock

Not yet run: this was developed on Linux. NAudio.Windows.Tests builds (-p:EnableWindowsTargeting=true), NAudio.Core.Tests passes (1779 passed, 0 failed, 3 skipped), and dotnet pack of NAudio.WinMM and NAudio.WinForms passes 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

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
@markheath markheath added the bug label Nov 26, 2026 — with Claude
@markheath

Copy link
Copy Markdown
Contributor Author

Tested on Windows with a real audio device

Windows 11 Pro (build 26300), .NET SDK 10.0.400, default output device. Branch head 8f719246.

Integration tests (NAudio.Windows.Tests, including IntegrationTest):

  • New WaveOutStopRaceTests: 4/4 pass.
  • To check they detect the bug, I ran the same test file against unfixed main (3beac704), adding only the internal AnyBufferQueued property: 3 of 4 fail (Stop_WhileSourceIsReading_LeavesNoBufferQueued: buffer still queued; Dispose_WhileSourceIsReading_WaitsForThePlaybackThread: a Read still in progress; Play_ImmediatelyAfterStop_KeepsPlaying: state reverted to Stopped). Dispose_FromPlaybackStoppedHandler_DoesNotDeadlock passes on both, as expected.
  • Full suite: 476 passed, 1 failed, 5 skipped. The one failure, DirectSoundTests.CanPlayWavFileWhoseFormatCarriesExtraData, fails the same way on unfixed main, so it's unrelated to this PR.

Repro program from #1515 (with new WaveOut() and Read(Span<byte>), referencing this branch):

  • slow: 3/3 runs completed all 50 cycles.
  • fast (2000 cycles per run, all cores busy): 3/3 runs completed without crashing. Runs took 319–384s, compared with ~210s for the same loop on 2.x. That's consistent with Dispose() now waiting for the playback thread to finish its current Read.

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

@markheath
markheath merged commit 18a5be8 into main Nov 26, 2026
5 checks passed
@markheath
markheath deleted the fix/1515-waveout-requeue-after-reset branch November 26, 2026 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WaveOutEvent: disposing during playback can free buffers the driver still owns (access violation in wdmaud.drv); 2.x not fixed

1 participant