From 8ed8a2273ae927b81af64290d0f52f81ca7d7b3b Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sat, 14 Nov 2026 09:24:22 +0100 Subject: [PATCH 1/2] oto: report when frames are played on Windows with WASAPI After each write, the WASAPI driver reports the frame of the mix that IAudioClock::GetPosition says is played, at the moment the position was read. The position counts from the stream's start, and keeps counting while the stream runs dry. So the driver fills the buffer before Start, stops the stream while the context is suspended, and when it finds the buffer empty, it stops, resets and fills the stream again. Each time, the stream's position 0 is a known frame of the mix. WinMM still reports nothing. Updates #311 Co-Authored-By: Claude Opus 5.5 --- api_wasapi_windows.go | 79 +++++++++++++++++++++++ driver_wasapi_windows.go | 131 ++++++++++++++++++++++++++++++++++++--- driver_windows.go | 5 +- 3 files changed, 205 insertions(+), 10 deletions(-) diff --git a/api_wasapi_windows.go b/api_wasapi_windows.go index 0e8ce15..14afb6e 100644 --- a/api_wasapi_windows.go +++ b/api_wasapi_windows.go @@ -21,6 +21,8 @@ import ( "unsafe" "golang.org/x/sys/windows" + + "github.com/ebitengine/oto/v3/internal/mathutil" ) var ( @@ -29,11 +31,16 @@ var ( var ( procCoCreateInstance = ole32.NewProc("CoCreateInstance") + + kernel32 = windows.NewLazySystemDLL("kernel32") + procQueryPerformanceCounter = kernel32.NewProc("QueryPerformanceCounter") + procQueryPerformanceFrequency = kernel32.NewProc("QueryPerformanceFrequency") ) type _REFERENCE_TIME int64 var ( + uuidIAudioClock = windows.GUID{0xcd63314f, 0x3fba, 0x4a1b, [...]byte{0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7}} uuidIAudioClient2 = windows.GUID{0x726778cd, 0xf60a, 0x4eda, [...]byte{0x82, 0xde, 0xe4, 0x76, 0x10, 0xcd, 0x78, 0xaa}} uuidIAudioRenderClient = windows.GUID{0xf294acfc, 0x3146, 0x4483, [...]byte{0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}} uuidIMMDeviceEnumerator = windows.GUID{0xa95664d2, 0x9614, 0x4f35, [...]byte{0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}} @@ -387,6 +394,78 @@ func (i *_IAudioClient2) Stop() (bool, error) { return uint32(r) == uint32(windows.S_OK), nil } +func (i *_IAudioClient2) Reset() error { + r, _, _ := syscall.Syscall(i.vtbl.Reset, 1, uintptr(unsafe.Pointer(i)), 0, 0) + if uint32(r) != uint32(windows.S_OK) && uint32(r) != uint32(windows.S_FALSE) { + if isAudclntErr(uint32(r)) { + return fmt.Errorf("oto: IAudioClient2::Reset failed: %w", _AUDCLNT_ERR(r)) + } + return fmt.Errorf("oto: IAudioClient2::Reset failed: HRESULT(%d)", uint32(r)) + } + return nil +} + +type _IAudioClock struct { + vtbl *_IAudioClock_Vtbl +} + +type _IAudioClock_Vtbl struct { + QueryInterface uintptr + AddRef uintptr + Release uintptr + + GetFrequency uintptr + GetPosition uintptr + GetCharacteristics uintptr +} + +func (i *_IAudioClock) GetFrequency() (uint64, error) { + var freq uint64 + r, _, _ := syscall.Syscall(i.vtbl.GetFrequency, 2, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(&freq)), 0) + if uint32(r) != uint32(windows.S_OK) { + if isAudclntErr(uint32(r)) { + return 0, fmt.Errorf("oto: IAudioClock::GetFrequency failed: %w", _AUDCLNT_ERR(r)) + } + return 0, fmt.Errorf("oto: IAudioClock::GetFrequency failed: HRESULT(%d)", uint32(r)) + } + return freq, nil +} + +// GetPosition returns the device position, and the performance counter in 100-nanosecond units at that position. +func (i *_IAudioClock) GetPosition() (uint64, uint64, error) { + var pos, qpc uint64 + r, _, _ := syscall.Syscall(i.vtbl.GetPosition, 3, uintptr(unsafe.Pointer(i)), uintptr(unsafe.Pointer(&pos)), uintptr(unsafe.Pointer(&qpc))) + // S_FALSE means the position is less accurate, which is still usable. + if uint32(r) != uint32(windows.S_OK) && uint32(r) != uint32(windows.S_FALSE) { + if isAudclntErr(uint32(r)) { + return 0, 0, fmt.Errorf("oto: IAudioClock::GetPosition failed: %w", _AUDCLNT_ERR(r)) + } + return 0, 0, fmt.Errorf("oto: IAudioClock::GetPosition failed: HRESULT(%d)", uint32(r)) + } + return pos, qpc, nil +} + +func (i *_IAudioClock) Release() uint32 { + r, _, _ := syscall.Syscall(i.vtbl.Release, 1, uintptr(unsafe.Pointer(i)), 0, 0) + return uint32(r) +} + +// queryPerformanceCounter100ns returns the performance counter in 100-nanosecond units, as IAudioClock::GetPosition does. +func queryPerformanceCounter100ns() (int64, error) { + var counter, freq int64 + if r, _, err := procQueryPerformanceFrequency.Call(uintptr(unsafe.Pointer(&freq))); r == 0 { + return 0, fmt.Errorf("oto: QueryPerformanceFrequency failed: %w", err) + } + if r, _, err := procQueryPerformanceCounter.Call(uintptr(unsafe.Pointer(&counter))); r == 0 { + return 0, fmt.Errorf("oto: QueryPerformanceCounter failed: %w", err) + } + v, ok := mathutil.MulDiv(counter, 1e7, freq) + if !ok { + return 0, fmt.Errorf("oto: the performance counter is unrepresentable") + } + return v, nil +} + type _IAudioRenderClient struct { vtbl *_IAudioRenderClient_Vtbl } diff --git a/driver_wasapi_windows.go b/driver_wasapi_windows.go index d240a2f..addf381 100644 --- a/driver_wasapi_windows.go +++ b/driver_wasapi_windows.go @@ -116,12 +116,20 @@ type wasapiContext struct { client *_IAudioClient2 bufferFrames uint32 renderClient *_IAudioRenderClient + audioClock *_IAudioClock + clockFrequency uint64 currentDeviceID string enumerator *_IMMDeviceEnumerator oomRetryCount int buf []float32 + // mixed counts the frames of the mix read so far, across every stream. + mixed int64 + + // streamStart is the frame of the mix at the stream's position 0. + streamStart int64 + m sync.Mutex } @@ -276,8 +284,14 @@ func (c *wasapiContext) releaseOnCOMThread() { if c.client != nil { _, _ = c.client.Stop() } + // The report holds only for the stream released here. + c.mux.ClearPlayed() // The render service must be released on the thread that acquired it, // before releasing the audio client that owns it. + if c.audioClock != nil { + c.audioClock.Release() + c.audioClock = nil + } if c.renderClient != nil { c.renderClient.Release() c.renderClient = nil @@ -403,15 +417,41 @@ func (c *wasapiContext) startOnCOMThread() (ferr error) { return err } + // The audio clock tells which frame of the stream is played. Without it, + // the stream plays and nothing is reported. + if audioClock, err := c.client.GetService(&uuidIAudioClock); err == nil { + c.audioClock = (*_IAudioClock)(audioClock) + freq, err := c.audioClock.GetFrequency() + if err != nil || freq == 0 { + c.audioClock.Release() + c.audioClock = nil + } + c.clockFrequency = freq + } + // TODO: Should some errors be allowed? See WASAPIManager.cpp in the official example SimpleWASAPIPlaySound. - if err := c.client.Start(); err != nil { + // Fill the buffer before starting, so that the stream's position 0 is a + // known frame of the mix. + c.m.Lock() + defer c.m.Unlock() + if err := c.startFilled(); err != nil { return err } return nil } +// startFilled fills the empty buffer and starts the stream from position 0. +// c.m must be held. +func (c *wasapiContext) startFilled() error { + c.streamStart = c.mixed + if err := c.fill(c.bufferFrames); err != nil { + return err + } + return c.client.Start() +} + func (c *wasapiContext) loop() error { runtime.LockOSThread() defer runtime.UnlockOSThread() @@ -433,11 +473,9 @@ func (c *wasapiContext) loop() error { func (c *wasapiContext) loopOnRenderThread() error { last := time.Now() for { - c.suspendedCond.L.Lock() - for c.suspended { - c.suspendedCond.Wait() + if err := c.waitUntilResumed(); err != nil { + return err } - c.suspendedCond.L.Unlock() // Keep checking suspension and device changes even if the endpoint stops // signaling its sample-ready event. @@ -470,6 +508,27 @@ func (c *wasapiContext) loopOnRenderThread() error { } } +// waitUntilResumed blocks while the context is suspended. The stream is +// stopped meanwhile, so that its position stays at the frame it plays. +func (c *wasapiContext) waitUntilResumed() error { + c.suspendedCond.L.Lock() + suspended := c.suspended + c.suspendedCond.L.Unlock() + if !suspended { + return nil + } + + if _, err := c.client.Stop(); err != nil { + return err + } + c.suspendedCond.L.Lock() + for c.suspended { + c.suspendedCond.Wait() + } + c.suspendedCond.L.Unlock() + return c.client.Start() +} + func (c *wasapiContext) writeOnRenderThread() error { c.m.Lock() defer c.m.Unlock() @@ -479,14 +538,37 @@ func (c *wasapiContext) writeOnRenderThread() error { return err } + // An empty buffer means the stream ran dry. Its position kept counting the + // silence played meanwhile, so start the stream again from position 0. + if paddingFrames == 0 && c.audioClock != nil { + if _, err := c.client.Stop(); err != nil { + return err + } + if err := c.client.Reset(); err != nil { + return err + } + if err := c.startFilled(); err != nil { + return err + } + c.oomRetryCount = 0 + return nil + } + // Defensive check: WASAPI should never report more padding than the buffer size, // but if it did, the uint32 subtraction below would wrap around to a huge frame // count and GetBuffer would fail, so skip the write instead. if paddingFrames >= c.bufferFrames { return nil } - frames := c.bufferFrames - paddingFrames + if err := c.fill(c.bufferFrames - paddingFrames); err != nil { + return err + } + c.oomRetryCount = 0 + return c.reportPlayed() +} +// fill writes frames of the mix to the buffer. c.m must be held. +func (c *wasapiContext) fill(frames uint32) error { // Get the destination buffer. dstBuf, err := c.renderClient.GetBuffer(frames) if err != nil { @@ -502,6 +584,7 @@ func (c *wasapiContext) writeOnRenderThread() error { // Read the buffer from the players. c.mux.ReadFloat32s(c.buf) + c.mixed += int64(frames) // Copy the read buf to the destination buffer. copy(unsafe.Slice((*float32)(unsafe.Pointer(dstBuf)), len(c.buf)), c.buf) @@ -512,13 +595,46 @@ func (c *wasapiContext) writeOnRenderThread() error { } c.buf = c.buf[:0] - c.oomRetryCount = 0 + return nil +} + +// reportPlayed reports to the mux which frame of the mix is played, from the +// stream's position. +func (c *wasapiContext) reportPlayed() error { + if c.audioClock == nil { + return nil + } + pos, qpc, err := c.audioClock.GetPosition() + if err != nil { + return err + } + // The position stays 0 until the first frame plays. + if pos == 0 { + return nil + } + now, err := queryPerformanceCounter100ns() + if err != nil { + return err + } + frames, ok := mathutil.MulDiv(int64(pos), int64(c.sampleRate), int64(c.clockFrequency)) + if !ok { + return nil + } + at := time.Now().Add(time.Duration(int64(qpc)-now) * 100) + + c.suspendedCond.L.Lock() + defer c.suspendedCond.L.Unlock() + // Suspend clears the report, so a report made since is dropped. + if !c.suspended { + c.mux.SetPlayed(c.streamStart+frames, at) + } return nil } func (c *wasapiContext) Suspend() error { c.suspendedCond.L.Lock() c.suspended = true + c.mux.ClearPlayed() c.suspendedCond.L.Unlock() c.suspendedCond.Signal() @@ -603,6 +719,7 @@ func (c *wasapiContext) restart() error { } c.mux.ReadFloat32s(buf[:framesPerRead*c.channelCount]) + c.mixed += int64(framesPerRead) time.Sleep(perRead) } } diff --git a/driver_windows.go b/driver_windows.go index a866c3f..97ee688 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -46,9 +46,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI mux: mux.New(sampleRate, channelCount, format), ready: make(chan struct{}), } - // TODO: Report when the frames are played with ctx.mux.SetPlayed, from the - // delay: on WASAPI, the frames written less the position IAudioClock reports; - // on WinMM, the frames written less the position waveOutGetPosition reports. + // TODO: Report when the frames are played with ctx.mux.SetPlayed on WinMM, + // from the frames written less the position waveOutGetPosition reports. // Initializing drivers might take some time. Do this asynchronously. go func() { From 47332642879532fff60fc3ef57a2e5c973f67bb4 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sat, 14 Nov 2026 09:27:51 +0100 Subject: [PATCH 2/2] oto: restart a dry WASAPI stream only after silence played Clear the report when a dry stream restarts, as the frames it named belong to the old stream. Restart only when a whole buffer's time has passed since the last fill: an empty buffer sooner than that can be the engine taking the last period, with no silence played. A clock error other than a lost device now skips the report. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_wasapi_windows.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/driver_wasapi_windows.go b/driver_wasapi_windows.go index addf381..a4fc0a9 100644 --- a/driver_wasapi_windows.go +++ b/driver_wasapi_windows.go @@ -130,6 +130,9 @@ type wasapiContext struct { // streamStart is the frame of the mix at the stream's position 0. streamStart int64 + // filledAt is when the buffer was last filled. + filledAt time.Time + m sync.Mutex } @@ -538,9 +541,13 @@ func (c *wasapiContext) writeOnRenderThread() error { return err } - // An empty buffer means the stream ran dry. Its position kept counting the - // silence played meanwhile, so start the stream again from position 0. - if paddingFrames == 0 && c.audioClock != nil { + // An empty buffer a whole buffer's time after the last fill means the stream + // ran dry. Its position kept counting the silence played meanwhile, so start + // the stream again from position 0. An empty buffer sooner than that can be + // the engine taking the last period just now, with no silence played yet. + bufferTime := time.Duration(int64(c.bufferFrames) * int64(time.Second) / int64(c.sampleRate)) + if paddingFrames == 0 && c.audioClock != nil && time.Since(c.filledAt) >= bufferTime { + c.mux.ClearPlayed() if _, err := c.client.Stop(); err != nil { return err } @@ -585,6 +592,7 @@ func (c *wasapiContext) fill(frames uint32) error { // Read the buffer from the players. c.mux.ReadFloat32s(c.buf) c.mixed += int64(frames) + c.filledAt = time.Now() // Copy the read buf to the destination buffer. copy(unsafe.Slice((*float32)(unsafe.Pointer(dstBuf)), len(c.buf)), c.buf) @@ -606,7 +614,11 @@ func (c *wasapiContext) reportPlayed() error { } pos, qpc, err := c.audioClock.GetPosition() if err != nil { - return err + // A lost device restarts the stream. Other errors only skip this report. + if isWASAPIDeviceTransientError(err) { + return err + } + return nil } // The position stays 0 until the first frame plays. if pos == 0 { @@ -614,7 +626,7 @@ func (c *wasapiContext) reportPlayed() error { } now, err := queryPerformanceCounter100ns() if err != nil { - return err + return nil } frames, ok := mathutil.MulDiv(int64(pos), int64(c.sampleRate), int64(c.clockFrequency)) if !ok {