Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ the NuGet `PackageReleaseNotes` field, which has a hard 35,000-character
limit and fails the release build if exceeded.
-->

* Fixed `WaveOut` queueing a buffer again after `Stop()` had reset the device when `Stop()` ran while the playback thread was reading from the source, so audio no longer continues briefly after `Stop()` and `Dispose()` no longer leaks the buffer and device handle; `Dispose()` and a `Play()` straight after `Stop()` now wait for the previous playback thread to exit, and `WaveOutWindow` gets the same fix (#1515)
* `AiffFileReader` no longer reads the pad byte after an odd-sized SSND chunk as sound data, so 8-bit files with an odd number of sample bytes no longer gain an extra sample frame
* Fixed `BroadcastExtension.FormatOriginationDate` and `FormatOriginationTime` producing non-ISO text (for example a Buddhist-calendar year, or `.` as the time separator) when the current culture differs from the invariant one
* `AiffFileReader` now reads files that leave off the pad byte after an odd-sized SSND chunk at the end of the file, instead of throwing "No SSND chunk found"
Expand Down
6 changes: 4 additions & 2 deletions src/NAudio.WinForms/WaveOutWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -351,9 +351,11 @@ private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwIn
Interlocked.Decrement(ref queuedBuffers);

Exception? exception = null;
if (playbackState == PlaybackState.Playing)
// Check the state inside waveOutLock: Stop() sets Stopped before taking this lock to call
// waveOutReset, so a buffer can't be queued again after the reset (issue #1515).
lock (waveOutLock)
{
lock (waveOutLock)
if (playbackState == PlaybackState.Playing)
{
try
{
Expand Down
82 changes: 76 additions & 6 deletions src/NAudio.WinMM/WaveOut.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class WaveOut : IWavePlayer, IWavePosition, IWaveLatency
private IWaveProvider? waveStream;
private volatile PlaybackState playbackState;
private AutoResetEvent? callbackEvent;
private Thread? playbackThread;
private bool isDisposed;

/// <summary>
Expand Down Expand Up @@ -88,7 +89,8 @@ public void Init(IWaveProvider waveProvider)
{
// normally we don't allow calling Init twice, but as experiment, see if we can clean up and go again
// try to allow reuse of this waveOut device
// n.b. risky if Playback thread has not exited
WaitForPlaybackThread();
ResetDevice();
DisposeBuffers();
CloseWaveOut();
}
Expand Down Expand Up @@ -120,7 +122,7 @@ public void Init(IWaveProvider waveProvider)
playbackState = PlaybackState.Stopped;
for (var n = 0; n < NumberOfBuffers; n++)
{
buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock, CanQueueBuffer);
}
}

Expand All @@ -135,15 +137,20 @@ public void Play()
}
if (playbackState == PlaybackState.Stopped)
{
// After a Stop(), the previous playback thread can still be finishing a Read. Let it
// exit first: otherwise it would see Playing again and keep queueing buffers, and its
// exit would then set the state back to Stopped underneath the new thread.
WaitForPlaybackThread();
playbackState = PlaybackState.Playing;
callbackEvent.Set(); // give the thread a kick
var playbackThread = new Thread(PlaybackThread)
var thread = new Thread(PlaybackThread)
{
IsBackground = true,
Name = "NAudio WaveOut Playback",
Priority = ThreadPriority.AboveNormal
};
playbackThread.Start();
playbackThread = thread;
thread.Start();
}
else if (playbackState == PlaybackState.Paused)
{
Expand Down Expand Up @@ -171,6 +178,30 @@ private void PlaybackThread()
}
}

/// <summary>
/// Passed to each <see cref="WaveOutBuffer"/> and evaluated under <see cref="waveOutLock"/>
/// just before <c>waveOutWrite</c>. <see cref="Stop"/> sets <see cref="PlaybackState.Stopped"/>
/// before it takes that lock to call <c>waveOutReset</c>, so once the reset has happened no
/// buffer can be queued again. Without this, a buffer the playback thread was filling while
/// Stop() ran went back into the device queue after the reset (issue #1515).
/// Writes while paused stay allowed: they queue behind waveOutPause and play on resume.
/// </summary>
private bool CanQueueBuffer() => playbackState != PlaybackState.Stopped;

/// <summary>
/// Waits for the playback thread to exit, unless called from that thread
/// (e.g. from a <see cref="PlaybackStopped"/> handler with no synchronization context),
/// where waiting would deadlock. By then the thread has finished with the buffers.
/// </summary>
private void WaitForPlaybackThread()
{
var thread = playbackThread;
if (thread != null && thread != Thread.CurrentThread)
{
thread.Join();
}
}

private void DoPlayback()
{
// Cache the callback event and buffers in locals so a concurrent CloseWaveOut()
Expand Down Expand Up @@ -322,6 +353,24 @@ public TimeSpan CurrentLatency
/// </summary>
public PlaybackState PlaybackState => playbackState;

/// <summary>
/// True if any buffer is currently queued on the device. For tests: after <see cref="Stop"/>
/// has returned and the playback thread has exited, this must be false (issue #1515).
/// </summary>
internal bool AnyBufferQueued
{
get
{
var current = buffers;
if (current == null) return false;
foreach (var buffer in current)
{
if (buffer.InQueue) return true;
}
return false;
}
}

/// <summary>
/// Volume for this device 1.0 is full scale
/// </summary>
Expand Down Expand Up @@ -354,16 +403,34 @@ protected void Dispose(bool disposing)
if (disposing)
{
Stop();
// Don't release buffers or the device while the playback thread can still be using
// them, or reading from a source the caller is about to dispose.
WaitForPlaybackThread();
ResetDevice();
DisposeBuffers();
}

CloseWaveOut();
}

/// <summary>
/// Returns any buffer the device still holds, so unpreparing the buffers and closing the
/// device don't fail with WAVERR_STILLPLAYING (which leaks the buffer and leaves the
/// device open). Normally nothing is queued by now; this is a safety net.
/// </summary>
private void ResetDevice()
{
lock (waveOutLock)
{
if (hWaveOut != IntPtr.Zero)
{
WaveInterop.waveOutReset(hWaveOut);
}
}
}

private void CloseWaveOut()
{
callbackEvent?.Close();
callbackEvent = null;
lock (waveOutLock)
{
if (hWaveOut != IntPtr.Zero)
Expand All @@ -372,6 +439,9 @@ private void CloseWaveOut()
hWaveOut = IntPtr.Zero;
}
}
// Only now: the device signals this event as buffers complete, so close it after the device.
callbackEvent?.Close();
callbackEvent = null;
}

private void DisposeBuffers()
Expand Down
32 changes: 24 additions & 8 deletions src/NAudio.WinMM/WaveOutBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ internal class WaveOutBuffer : IDisposable
private readonly IWaveProvider waveStream;
private readonly Lock waveOutLock;
private readonly Lock waveStreamLock;
private readonly Func<bool>? canQueue;
private readonly int headerSize;
private GCHandle hBuffer;
private IntPtr hWaveOut;
Expand All @@ -36,8 +37,15 @@ internal class WaveOutBuffer : IDisposable
/// <param name="bufferSize">Buffer size in bytes</param>
/// <param name="bufferFillStream">Stream to provide more data</param>
/// <param name="waveOutLock">Lock to protect WaveOut API's from being called on >1 thread</param>
public WaveOutBuffer(IntPtr hWaveOut, Int32 bufferSize, IWaveProvider bufferFillStream, Lock waveOutLock)
/// <param name="canQueue">
/// Optional check, evaluated while holding <paramref name="waveOutLock"/> immediately before
/// <c>waveOutWrite</c>. Returning false skips the write. The owner's <c>Stop()</c> changes its
/// state before calling <c>waveOutReset</c> under the same lock, so a buffer filled while
/// <c>Stop()</c> runs can never be queued again after the reset (issue #1515).
/// </param>
public WaveOutBuffer(IntPtr hWaveOut, Int32 bufferSize, IWaveProvider bufferFillStream, Lock waveOutLock, Func<bool>? canQueue = null)
{
this.canQueue = canQueue;
this.bufferSize = bufferSize;
buffer = new byte[bufferSize];
hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Expand Down Expand Up @@ -131,7 +139,11 @@ protected void Dispose(bool disposing)

#endregion

/// this is called by the WAVE callback and should be used to refill the buffer
/// <summary>
/// Refills the buffer from the source and queues it on the device.
/// Returns false if the source has ended, or if the buffer was not queued because the
/// owner is stopping.
/// </summary>
public bool OnDone()
{
int bytes;
Expand All @@ -151,8 +163,7 @@ public bool OnDone()
// driver, and a concurrent reader of CurrentLatency must never see the pair
// (InQueue = true, stale filledTimestamp from a previous cycle).
Volatile.Write(ref filledTimestamp, Stopwatch.GetTimestamp());
WriteToWaveOut();
return true;
return WriteToWaveOut();
}

/// <summary>
Expand All @@ -168,9 +179,9 @@ public bool InQueue
{
get
{
// WaveOut disposes its buffers without joining the playback thread, and the
// public IWaveLatency.CurrentLatency reads this from any thread, so the block may
// already be freed. Report "not queued" rather than dereferencing released memory.
// The public IWaveLatency.CurrentLatency reads this from any thread, so the block
// may already have been freed by Dispose. Report "not queued" rather than
// dereferencing released memory.
if (headerPtr == IntPtr.Zero) return false;
return (Header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;
}
Expand All @@ -181,12 +192,16 @@ public bool InQueue
/// </summary>
public int BufferSize => bufferSize;

private void WriteToWaveOut()
private bool WriteToWaveOut()
{
MmResult result;

lock (waveOutLock)
{
if (canQueue != null && !canQueue())
{
return false;
}
result = WaveInterop.waveOutWrite(hWaveOut, headerPtr, headerSize);
}
if (result != MmResult.NoError)
Expand All @@ -195,6 +210,7 @@ private void WriteToWaveOut()
}

GC.KeepAlive(this);
return true;
}

}
Loading