Skip to content

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

Done

Description

@giansalvo

Summary

WaveOutEvent.Stop() / Dispose() do not wait for the playback thread. A buffer can be queued again after waveOutReset, and WaveOutBuffer.Dispose then releases its memory while the driver still owns it. The process dies with an access violation (0xC0000005) on a driver thread, or later with unrelated-looking errors (ExecutionEngineException / Internal CLR error 0x80131506, AccessViolationException in code that has nothing to do with audio).

PR #1502 stops the crash on main (the buffer is leaked when waveOutUnprepareHeader returns WaveStillPlaying). Two things remain:

  1. release/2.x (2.4.0) does not have that fix and still crashes.
  2. The cause is still there: a buffer can be queued after the reset during an ordinary Stop(), so the "still playing" path, described in Harden file parsers against malformed input #1502 as one that normal shutdown should not hit, can be hit.

Results

Windows 11, .NET 10.0.12, one machine and one audio driver, default output device.

NAudio slow (forced interleaving) fast (no artificial delay)
2.2.1 crashed 3 / 3 crashed 4 / 5 runs
2.4.0 crashed 3 / 3 crashed 1 / 4 runs
3.3.0 crashed (every run, see note below the program) no crash in 4 runs
3.4.0-preview.1 no crash, 3 / 3 not tested

A fast run lasts up to about two minutes; the runs that did not crash were stopped after 1250–1750 cycles. With an in-memory silent source instead of a file, fast did not crash in about 2000 cycles per run (4 runs).

The faulting address in all the crashes we looked up in the Windows event log was inside memcpy in ucrtbase.dll. In a dump of a real crash (same address), the faulting thread was a wdmaud.drv thread copying from an address in a part of the managed heap that was no longer allocated.

Repro

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="NAudio" Version="2.4.0" />
  </ItemGroup>
</Project>
using System.Diagnostics;
using NAudio.Wave;

// Usage: repro [slow|fast]
//   slow: forces the interleaving (Stop while the playback thread is inside Read)
//   fast: no artificial delay: a Windows sound file at volume zero, Dispose 0-5 ms after Play, with the CPU busy
var slow = args.Length == 0 || args[0] == "slow";
var random = new Random(1);

if (!slow)
    for (var i = 0; i < Environment.ProcessorCount; i++)
        new Thread(() => { while (true) { } }) { IsBackground = true }.Start();

for (var cycle = 1; cycle <= (slow ? 50 : 10000); cycle++)
{
    var source = new Silence(60);
    using var file = slow ? null : new AudioFileReader(@"C:\Windows\Media\Alarm01.wav") { Volume = 0 };
    var output = new WaveOutEvent();
    using var stopped = new ManualResetEventSlim();
    output.PlaybackStopped += (_, _) => stopped.Set();
    output.Init((IWaveProvider?)file ?? source);
    output.Play();

    if (slow)
    {
        source.Reading.Wait();
        output.Stop();          // waveOutReset, while the playback thread is inside Read...
        stopped.Wait();         // ...which then calls waveOutWrite, after the reset
    }
    else
    {
        var watch = Stopwatch.StartNew();
        var microseconds = random.Next(0, 5000);
        while (watch.Elapsed.TotalMicroseconds < microseconds) { }
    }

    output.Dispose();

    // reuse the memory that has just been released
    for (var k = 0; k < 600; k++) Array.Fill(new byte[random.Next(1000, 60000)], (byte)0xCD);
    GC.Collect(2, GCCollectionMode.Aggressive, true, true);
    if (slow) Thread.Sleep(100);
    if (slow || cycle % 250 == 0) Console.WriteLine($"cycle {cycle} survived");
}
Console.WriteLine("completed without crashing");

sealed class Silence(int readDelayMilliseconds) : IWaveProvider
{
    public ManualResetEventSlim Reading { get; } = new();
    public WaveFormat WaveFormat { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);

    public int Read(byte[] buffer, int offset, int count)
    {
        Reading.Set();
        if (readDelayMilliseconds > 0) Thread.Sleep(readDelayMilliseconds);
        Array.Clear(buffer, offset, count);
        return count;
    }
}

Note for 3.x: replace new WaveOutEvent() with new WaveOut() and implement Read(Span<byte> buffer).

What happens (2.2.1 / 2.4.0 source)

  1. DoPlayback checks playbackState == Playing, then refills and queues buffers (OnDone → waveOutWrite).
  2. Stop() sets the state to Stopped and calls waveOutReset while the playback thread is between that check and waveOutWrite.
  3. The write succeeds after the reset: the buffer is in the queue again.
  4. Dispose → Stop() does nothing the second time. WaveOutBuffer.Dispose frees the GCHandles of the data buffer and of the header before calling waveOutUnprepareHeader, and ignores its result.
  5. The driver keeps reading the data buffer (and writing the header flags) in memory the GC is now free to reuse or decommit.

Inspecting the header flags through reflection after Stop() and PlaybackStopped, WHDR_INQUEUE was still set in 40 of 40 iterations of the slow scenario, on 2.2.1, 2.4.0 and also on 3.4.0-preview.1 (InQueue there). So waiting for PlaybackStopped before Dispose, as suggested when #339 was closed, is not enough in this case.

On main, from reading the code (not measured): when the new path is taken, the buffer stays pinned, the header is leaked and waveOutClose would be called with a buffer still queued.

Possible fixes

  • Have Stop() (or at least Dispose()) join the playback thread, then call waveOutReset again before unpreparing the buffers.
  • Or make the state check and waveOutWrite atomic with respect to the reset: check playbackState inside waveOutLock, in the same lock that Stop() holds while it changes the state and calls waveOutReset.
  • For 2.x: at least backport the WaveStillPlaying handling of Harden file parsers against malformed input #1502, calling waveOutUnprepareHeader before freeing the handles.

We have not tried these changes in NAudio.

Related

Workaround

We are moving to WasapiOut, whose Stop() joins its playback thread: a stress test with the same timing (stop 0-5 ms after play, CPU busy) ran without crashes.

Context

Found in a desktop app using NAudio 2.2.1, where it first showed up as random crashes of the test suite. Analysis and fix are tracked in giansalvo/GGCalendar#105 (written in Italian).

Activity

  1. markheath commented on Nov 26, 2026

    @markheath
    Contributor

    Thanks for reporting. Any reason why you are not using NAudio 3? We are not actively developing on NAudio 2 at the moment

  2. markheath commented on Nov 26, 2026

    @markheath
    Contributor

    I've pushed fixes for this to v2 and v3 and I've made some improvements to the v2 release process so in due course we can more easily release versions of the 2.x branch. Some notes from Claude...

    Fixes are now available in pre-release packages for both versions:

    NAudio 3: 3.4.0-preview.2 (#1516)

    • Stop() can no longer queue a buffer again after the device has been reset. The state check and waveOutWrite now happen under the same lock that Stop() holds for waveOutReset, which was the second fix you suggested.
    • Dispose() now waits for the playback thread before releasing buffers and closing the device. So does a Play() straight after Stop(), so the old thread can't carry on queueing buffers or set the state back to Stopped.
    • The device is reset again before buffers are unprepared, and the callback event is now closed after the device rather than before it.

    NAudio 2: 2.4.1-preview.1 (#1517)

    • The same lock-based check for WaveOutEvent.
    • WaveOutBuffer.Dispose now unprepares the header before freeing the pinned handles. If the driver still reports the buffer as playing, it deliberately leaks the handles rather than freeing memory the driver might still be reading. This is the crash you were seeing.

    If you get a chance, could you rerun your repro (both slow and fast) against these two previews? Your reflection check for InQueue after Stop() would be especially useful, since it's the most direct check that the requeue can't happen any more.

    <PackageReference Include="NAudio" Version="2.4.1-preview.1" />
    <PackageReference Include="NAudio" Version="3.4.0-preview.2" />

    Let me know if this meets your needs and they can go live in the next full release of NAudio

  3. giansalvo commented on Nov 27, 2026

    @giansalvo
    Author

    Thanks for reporting. Any reason why you are not using NAudio 3? We are not actively developing on NAudio 2 at the moment

    1. Crash: Version 3.3.0—the latest stable version tested—still exhibits an issue with WaveOut (the new name for WaveOutEvent). Only version 3.4.0-preview.1 avoids this crash. The fix for random crashes—caused by audio memory being freed while sound is still playing —utilizes WasapiOut and is not affected by this issue.
    2. Compatibility: The 3.x series introduces breaking changes—for instance, to the sound-reading signature—which must also be verified in the mock output used for testing.
  4. markheath commented on Nov 27, 2026

    @markheath
    Contributor

    OK, well hopefully 3.4.0 is out soon. Also WASPI is the recommended approach going forwards for audio playback in Windows as it replaced the old winmm APIs that WaveOut/WaveOutEvent usess as the preferred audio API in Windows 20 years ago! In NAudio 3 there is a new WasapiPlayer class that is designed to be easier to configure and exposes more capabilities, but WasapiOut is still there if you need it.

  5. added a commit that references this issue on Nov 28, 2026
    18a5be8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions