From ad1f89540d0f25f6983ea1a0f17f6f69d798145e Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sun, 8 Nov 2026 13:53:22 +0100 Subject: [PATCH 1/2] oto: report when frames are played on Linux and the BSDs The PulseAudio and ALSA backends now call Mux.SetPlayed, so UnplayedSize counts the frames the server or the device holds and the audio hardware's delay. PulseAudio: every 100 ms, a GetPlaybackLatency request for the stream gives the read index, the frame the sink takes next, and the sink's latency, after which that frame is played. The reply's moment is taken as halfway between sending the request and the reply. ALSA: after each write, snd_pcm_delay gives how many of the frames written are not played yet. Suspend clears the report, as does a failed query, or a stream the server reports as not running. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_alsa_unix.go | 16 ++++++++++ driver_pulseaudio_unix.go | 65 +++++++++++++++++++++++++++++++++++++-- driver_unix.go | 4 --- 3 files changed, 78 insertions(+), 7 deletions(-) diff --git a/driver_alsa_unix.go b/driver_alsa_unix.go index 57abf42..b5a292a 100644 --- a/driver_alsa_unix.go +++ b/driver_alsa_unix.go @@ -20,6 +20,7 @@ import ( "fmt" "strings" "sync" + "time" "unsafe" "github.com/ebitengine/purego" @@ -50,6 +51,7 @@ var ( _snd_pcm_hw_params func(pcm, params uintptr) int32 _snd_pcm_writei func(pcm uintptr, buf []float32, size uint) int _snd_pcm_recover func(pcm uintptr, err int32, silent int32) int32 + _snd_pcm_delay func(pcm uintptr, delay *int) int32 _snd_device_name_hint func(card int32, iface string, hints *unsafe.Pointer) int32 _snd_device_name_free_hint func(hints unsafe.Pointer) int32 @@ -99,6 +101,7 @@ func loadALSA() error { purego.RegisterLibFunc(&_snd_pcm_hw_params, handle, "snd_pcm_hw_params") purego.RegisterLibFunc(&_snd_pcm_writei, handle, "snd_pcm_writei") purego.RegisterLibFunc(&_snd_pcm_recover, handle, "snd_pcm_recover") + purego.RegisterLibFunc(&_snd_pcm_delay, handle, "snd_pcm_delay") purego.RegisterLibFunc(&_snd_device_name_hint, handle, "snd_device_name_hint") purego.RegisterLibFunc(&_snd_device_name_free_hint, handle, "snd_device_name_free_hint") purego.RegisterLibFunc(&_snd_device_name_get_hint, handle, "snd_device_name_get_hint") @@ -116,6 +119,9 @@ type alsaContext struct { handle uintptr + // written counts the frames written to the device. + written int64 + cond *sync.Cond mux *mux.Mux @@ -258,6 +264,15 @@ func (c *alsaContext) readAndWrite(buf32 []float32) bool { return false } buf = buf[n*c.channelCount:] + c.written += int64(n) + } + + // snd_pcm_delay gives how many of the frames written are not played yet. + var delay int + if _snd_pcm_delay(c.handle, &delay) < 0 { + c.mux.ClearPlayed() + } else { + c.mux.SetPlayed(c.written-int64(delay), time.Now()) } return true } @@ -271,6 +286,7 @@ func (c *alsaContext) Suspend() error { } c.suspended = true + c.mux.ClearPlayed() // Do not use snd_pcm_pause as not all devices support this. // Do not use snd_pcm_drop as this might hang (https://github.com/libsdl-org/SDL/blob/a5c610b0a3857d3138f3f3da1f6dc3172c5ea4a8/src/audio/alsa/SDL_alsa_audio.c#L478). diff --git a/driver_pulseaudio_unix.go b/driver_pulseaudio_unix.go index e3ca3b0..7f45ce3 100644 --- a/driver_pulseaudio_unix.go +++ b/driver_pulseaudio_unix.go @@ -21,8 +21,10 @@ import ( "os" "path/filepath" "sync" + "time" "github.com/jfreymuth/pulse" + "github.com/jfreymuth/pulse/proto" "github.com/ebitengine/oto/v3/internal/mux" ) @@ -34,14 +36,22 @@ type pulseContext struct { suspended bool cond *sync.Cond + // frameSize is the byte size of a frame of the stream. + frameSize int + mux *mux.Mux err atomicError } +// pulseReportInterval is how often the PulseAudio backend asks the server which +// frame of the stream it plays. +const pulseReportInterval = 100 * time.Millisecond + func newPulseContext(sampleRate int, channelCount int, mux *mux.Mux, bufferSizeInBytes int, applicationName string) (*pulseContext, error) { c := &pulseContext{ - cond: sync.NewCond(&sync.Mutex{}), - mux: mux, + cond: sync.NewCond(&sync.Mutex{}), + frameSize: channelCount * 4, + mux: mux, } if applicationName == "" { @@ -90,9 +100,54 @@ func newPulseContext(sampleRate int, channelCount int, mux *mux.Mux, bufferSizeI c.stream = stream c.stream.Start() + go c.reportPlayed() + return c, nil } +// reportPlayed reports to the mux which frame of the stream is played, every +// pulseReportInterval, until the stream fails. +func (c *pulseContext) reportPlayed() { + t := time.NewTicker(pulseReportInterval) + defer t.Stop() + + for range t.C { + if c.Err() != nil { + c.mux.ClearPlayed() + return + } + + c.cond.L.Lock() + suspended := c.suspended + c.cond.L.Unlock() + if suspended { + continue + } + + sent := time.Now() + var reply proto.GetPlaybackLatencyReply + err := c.client.RawRequest(&proto.GetPlaybackLatency{ + StreamIndex: c.stream.StreamIndex(), + Time: protoTime(sent), + }, &reply) + if err != nil || !reply.Running { + c.mux.ClearPlayed() + continue + } + // When the server replies, the sink takes the frame at ReadIndex next, and + // plays it after the sink's latency. + replied := sent.Add(time.Since(sent) / 2) + c.mux.SetPlayed(reply.ReadIndex/int64(c.frameSize), replied.Add(time.Duration(reply.Latency)*time.Microsecond)) + } +} + +func protoTime(t time.Time) proto.Time { + return proto.Time{ + Seconds: uint32(t.Unix()), + Microseconds: uint32(t.Nanosecond() / 1000), + } +} + func (c *pulseContext) read(buf []float32) (int, error) { if err := c.waitUntilResumed(); err != nil { return 0, err @@ -134,7 +189,11 @@ func (c *pulseContext) setSuspended(suspended bool) error { // Suspend stops the playback. Audio that the server has already buffered still plays. func (c *pulseContext) Suspend() error { - return c.setSuspended(true) + if err := c.setSuspended(true); err != nil { + return err + } + c.mux.ClearPlayed() + return nil } func (c *pulseContext) Resume() error { diff --git a/driver_unix.go b/driver_unix.go index 91eb501..83ff190 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -47,10 +47,6 @@ 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: PulseAudio's latency query for its stream, and snd_pcm_delay on ALSA, - // plus what the driver has read and not yet written. - // Initializing a driver might take some time, so do it asynchronously. // PulseAudio is the default; if no server is reachable, fall back to ALSA. go func() { From 6e43fe1423f07030c47b91dcf335f24b789c698f Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Mon, 9 Nov 2026 22:06:53 +0100 Subject: [PATCH 2/2] oto: drop a PulseAudio report measured before Suspend A Suspend during the latency request's round trip let the report land after the Suspend cleared it. Each Suspend now bumps a report generation, and a report from an older generation is dropped, as the Android driver does. ALSA now clears the report on a write error. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_alsa_unix.go | 1 + driver_pulseaudio_unix.go | 46 +++++++++++++++++++++++++++++---------- 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/driver_alsa_unix.go b/driver_alsa_unix.go index b5a292a..a57677b 100644 --- a/driver_alsa_unix.go +++ b/driver_alsa_unix.go @@ -261,6 +261,7 @@ func (c *alsaContext) readAndWrite(buf32 []float32) bool { } if n < 0 { c.err.Join(alsaError("snd_pcm_writei or snd_pcm_recover", int32(n))) + c.mux.ClearPlayed() return false } buf = buf[n*c.channelCount:] diff --git a/driver_pulseaudio_unix.go b/driver_pulseaudio_unix.go index 7f45ce3..0df6769 100644 --- a/driver_pulseaudio_unix.go +++ b/driver_pulseaudio_unix.go @@ -36,6 +36,10 @@ type pulseContext struct { suspended bool cond *sync.Cond + // reportGen is guarded by cond.L. It changes on every Suspend, so that a + // playback report measured before a Suspend is dropped. + reportGen int + // frameSize is the byte size of a frame of the stream. frameSize int @@ -117,10 +121,8 @@ func (c *pulseContext) reportPlayed() { return } - c.cond.L.Lock() - suspended := c.suspended - c.cond.L.Unlock() - if suspended { + gen, ok := c.reportState() + if !ok { continue } @@ -137,7 +139,27 @@ func (c *pulseContext) reportPlayed() { // When the server replies, the sink takes the frame at ReadIndex next, and // plays it after the sink's latency. replied := sent.Add(time.Since(sent) / 2) - c.mux.SetPlayed(reply.ReadIndex/int64(c.frameSize), replied.Add(time.Duration(reply.Latency)*time.Microsecond)) + c.setPlayed(gen, reply.ReadIndex/int64(c.frameSize), replied.Add(time.Duration(reply.Latency)*time.Microsecond)) + } +} + +// reportState returns the current report generation, and whether a report +// should be made, which is while the context plays. +func (c *pulseContext) reportState() (int, bool) { + c.cond.L.Lock() + defer c.cond.L.Unlock() + + return c.reportGen, !c.suspended +} + +// setPlayed reports a frame and its playing time to the mux, if no Suspend has +// come since the report generation gen. +func (c *pulseContext) setPlayed(gen int, frame int64, at time.Time) { + c.cond.L.Lock() + defer c.cond.L.Unlock() + + if gen == c.reportGen { + c.mux.SetPlayed(frame, at) } } @@ -168,7 +190,8 @@ func (c *pulseContext) waitUntilResumed() error { return c.err.Load() } -// setSuspended updates the suspended state and wakes up a waiting reader. +// setSuspended updates the suspended state. Suspending clears the playback +// report, and resuming wakes up a waiting reader. func (c *pulseContext) setSuspended(suspended bool) error { c.cond.L.Lock() defer c.cond.L.Unlock() @@ -181,7 +204,10 @@ func (c *pulseContext) setSuspended(suspended bool) error { } c.suspended = suspended - if !suspended { + if suspended { + c.reportGen++ + c.mux.ClearPlayed() + } else { c.cond.Signal() } return nil @@ -189,11 +215,7 @@ func (c *pulseContext) setSuspended(suspended bool) error { // Suspend stops the playback. Audio that the server has already buffered still plays. func (c *pulseContext) Suspend() error { - if err := c.setSuspended(true); err != nil { - return err - } - c.mux.ClearPlayed() - return nil + return c.setSuspended(true) } func (c *pulseContext) Resume() error {