diff --git a/driver_alsa_unix.go b/driver_alsa_unix.go index 57abf42..a57677b 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 @@ -255,9 +261,19 @@ 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:] + 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 +287,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..0df6769 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,26 @@ 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 + 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 +104,72 @@ 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 + } + + gen, ok := c.reportState() + if !ok { + 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.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) + } +} + +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 @@ -113,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() @@ -126,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 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() {