Skip to content
Open
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
79 changes: 79 additions & 0 deletions api_wasapi_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
"unsafe"

"golang.org/x/sys/windows"

"github.com/ebitengine/oto/v3/internal/mathutil"
)

var (
Expand All @@ -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}}
Expand Down Expand Up @@ -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
}
Expand Down
143 changes: 136 additions & 7 deletions driver_wasapi_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,23 @@ 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

// filledAt is when the buffer was last filled.
filledAt time.Time

m sync.Mutex
}

Expand Down Expand Up @@ -276,8 +287,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
Expand Down Expand Up @@ -403,15 +420,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()
Expand All @@ -433,11 +476,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.
Expand Down Expand Up @@ -470,6 +511,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()
Expand All @@ -479,14 +541,41 @@ func (c *wasapiContext) writeOnRenderThread() error {
return err
}

// 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
}
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 {
Expand All @@ -502,6 +591,8 @@ func (c *wasapiContext) writeOnRenderThread() 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)
Expand All @@ -512,13 +603,50 @@ 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 {
// 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 {
return nil
}
now, err := queryPerformanceCounter100ns()
if err != nil {
return nil
}
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()

Expand Down Expand Up @@ -603,6 +731,7 @@ func (c *wasapiContext) restart() error {
}

c.mux.ReadFloat32s(buf[:framesPerRead*c.channelCount])
c.mixed += int64(framesPerRead)
time.Sleep(perRead)
}
}
5 changes: 2 additions & 3 deletions driver_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading