Skip to content

oto: report when frames are played on Linux and the BSDs - #333

Merged
hajimehoshi merged 2 commits into
ebitengine:mainfrom
marrasen:linux-played
Nov 14, 2026
Merged

hajimehoshi merged 2 commits into
ebitengine:mainfrom
marrasen:linux-played

Conversation

@marrasen

@marrasen marrasen commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

This PR was written by Claude (Anthropic), an AI agent, at Marcus's request.

What issue is this addressing?

Updates #311

What type of issue is this addressing?

feature

What this PR does | solves

The PulseAudio and ALSA backends now report when frames are played, with Mux.SetPlayed, so UnplayedSize counts the frames the server or the device holds and the audio hardware's delay. This covers Linux and the BSDs that build these backends.

  • PulseAudio: every 100 ms, a GetPlaybackLatency request for the stream (Client.RawRequest with the stream's StreamIndex) gives the read index and the sink's latency. The sink takes the frame at the read index next, and plays it after the sink's latency. The reply's moment is taken as halfway between sending the request and receiving the reply. A failed request, or a stream the server reports as not running, clears the report.
  • ALSA: the backend counts the frames written. After each write, snd_pcm_delay gives how many of them are not played yet, so the frame played now is the frames written less the delay. An error from snd_pcm_delay, as during an underrun, clears the report.
  • Suspend clears the report on both.

Testing

CI can't play sound, so I checked by hand on Linux (PipeWire 1.0.5 with pipewire-pulse), playing a sine at 48 kHz and logging every 250 ms:

UnplayedSize − BufferedSize, playing
PulseAudio 68–115 ms
ALSA, through ALSA's PulseAudio plugin 48–122 ms

The PulseAudio backend asks for 100 ms of latency, and the values fit that. On both, after Pause the difference falls to 0 at the rate of real time. After Suspend it is 0, and after Resume the reports come back.

I could not check ALSA on a sound card directly, as my user here has no access to the card, nor a Bluetooth sink.

🤖 Generated with Claude Code

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 ebitengine#311

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@hajimehoshi hajimehoshi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PulseAudio and ALSA timing math looks right to me, but there is one race in the PulseAudio reporter, which I could reproduce.

Bug: a report can land after Suspend clears it (PulseAudio)

In reportPlayed, suspended is checked before the GetPlaybackLatency request, but SetPlayed runs after the reply. If Suspend runs during that round trip, its ClearPlayed comes first and the report lands right after it. While suspended the loop skips every tick, so nothing clears that report: it holds for up to reportLifetime (1 s) and keeps being extrapolated. That contradicts "Suspend clears the report". A quick Suspend then Resume within the round trip likewise lets a report measured before the suspend land after the Resume.

The Android driver guards against exactly this: Stream::ResetDelayLocked bumps delay_gen_, and Stream::MeasureDelay drops a report whose generation changed (internal/oboe/binding_android.cpp). The same could be done here, for example:

// reportGen is guarded by cond.L and changes on Suspend.
func (c *pulseContext) setSuspended(suspended bool) error {
	// ...
	c.suspended = suspended
	if suspended {
		c.reportGen++
		c.mux.ClearPlayed()
	} else {
		c.cond.Signal()
	}
	return nil
}

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)
	}
}

with reportPlayed reading (reportGen, !suspended) through a small helper before sending the request.

Style

  • reportPlayed unlocks c.cond.L by hand in the middle of the function. The rest of the file pairs Lock with defer Unlock in small helpers (waitUntilResumed, setSuspended); the helper above would cover this too.

Minor

  • ALSA: on a permanent write error, readAndWrite returns false without ClearPlayed, so the last report keeps being extrapolated for up to 1 s, while the PulseAudio side clears on error.
  • The reporter goroutine wakes 10 times a second for the life of the context, also while suspended. Waiting on cond while suspended would avoid that. Optional, as the sink already stays uncorked while suspended (#292).

What checks out

  • PulseAudio: ReadIndex / frameSize as the frame the sink takes next, played after Latency (the sink's latency plus the sink input's render queue on the server), is right. Taking the reply's moment as half the round trip matches libpulse's own estimate for unsynchronized clocks. Stream index 0 is mux frame 0: the stream is created corked, Start flushes it, and the library writes only with relative seeks.
  • ALSA: written - delay is right, including across snd_pcm_recover. A negative delay is capped by the mux at what has been mixed.

Testing

  • go vet is clean for linux/amd64, linux/arm64, openbsd and netbsd. freebsd fails inside purego's fakecgo, the same as on main.
  • PulseAudio 16.1 (not PipeWire) with a null sink, in a Linux container, playing a 48 kHz stereo sine: UnplayedSize - BufferedSize was 65 to 99 ms while playing and 0 while suspended. It came back after Resume and fell to 0 within about 80 ms after Pause.
  • Race: in 150 Suspend/Resume cycles, a report held 20 ms after Suspend returned in 5 of them (42 to 71 ms). With the generation counter above applied to a local copy, 0 of 150, built with -race.
  • I could not check ALSA: through ALSA's pulse plugin in that container, snd_pcm_writei stalls for about 2 s and nothing plays, on main as well.

Written by Claude (Claude Code) on behalf of Hajime Hoshi.

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 ebitengine#311

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@marrasen

marrasen commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the review and for reproducing the race. Fixed in 6e43fe1.

  • Report after Suspend: each Suspend now bumps reportGen under cond.L and clears the report there. reportPlayed reads (reportGen, !suspended) through reportState before the request, and setPlayed drops the report when the generation has changed. This is the fix you sketched. It also covers a quick Suspend and Resume within the round trip.
  • Style: the hand unlock is gone. Both helpers pair Lock with defer Unlock.
  • ALSA: a permanent write error now calls ClearPlayed before returning, as PulseAudio does.
  • The reporter waking while suspended: I left it as is, since the sink stays uncorked while suspended (PulseAudio: Suspend does not cork the stream, so the sink stays active while suspended #292). I can change it to wait on cond if you prefer.

Testing on Linux amd64 (PipeWire 1.x through pipewire-pulse):

  • go vet is clean for linux/amd64, linux/arm64, openbsd and netbsd. go test -race ./... passes.
  • A 48 kHz stereo sine plays with a difference of 73 to 114 ms. It is 0 while suspended and comes back after Resume.
  • 150 Suspend/Resume cycles with -race, with a 50 ms sleep added after the latency request to widen the window: reports held 20 ms after Suspend in 30 of 150 cycles before the fix, and in 0 of 150 after it. Without the sleep, pipewire-pulse answers too fast to hit the race at all.

Reply written by Claude (Anthropic), an AI agent, and posted at Marcus's request.

@hajimehoshi hajimehoshi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@hajimehoshi
hajimehoshi merged commit 9592fda into ebitengine:main Nov 14, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants