From 638d6f0cbffbe0f641ec32daeede4d461cf48349 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sun, 4 Oct 2026 22:19:33 +0200 Subject: [PATCH 01/12] oto: add Context.OutputLatency, reported on Android OutputLatency returns how long the sound the context has read from its players takes to be heard: what the fifo queues, and what the stream holds, as its timestamp says. On Android the timestamp counts a Bluetooth headset's own delay where the headset reports it. LoopRead measures it every 100 ms. Other platforms report nothing yet. An application that shows the sound it plays, as a spectrum or a beat, needs it to show what is heard rather than what was read: over Bluetooth earbuds the difference is a quarter of a second. Co-Authored-By: Claude Opus 5.5 (1M context) --- driver_android.go | 15 +++++++++-- internal/oboe/binding_android.cpp | 45 +++++++++++++++++++++++++++++++ internal/oboe/binding_android.go | 7 +++++ internal/oboe/binding_android.h | 1 + outputlatency_android.go | 28 +++++++++++++++++++ outputlatency_other.go | 32 ++++++++++++++++++++++ 6 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 outputlatency_android.go create mode 100644 outputlatency_other.go diff --git a/driver_android.go b/driver_android.go index 17111e0..b9d3a44 100644 --- a/driver_android.go +++ b/driver_android.go @@ -16,13 +16,15 @@ package oto import ( "sync" + "time" "github.com/ebitengine/oto/v3/internal/mux" "github.com/ebitengine/oto/v3/internal/oboe" ) type context struct { - mux *mux.Mux + mux *mux.Mux + sampleRate int err atomicError @@ -33,7 +35,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI ready := make(chan struct{}) c := &context{ - mux: mux.New(sampleRate, channelCount, format), + mux: mux.New(sampleRate, channelCount, format), + sampleRate: sampleRate, } go func() { // The ready channel must close even if Play fails, or callers waiting on it block forever. @@ -61,6 +64,14 @@ func (c *context) Resume() error { return oboe.Resume() } +func (c *context) outputLatency() (time.Duration, bool) { + n, ok := oboe.Latency() + if !ok { + return 0, false + } + return time.Duration(n) * time.Second / time.Duration(c.sampleRate), true +} + func (c *context) Err() error { return c.err.Load() } diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 9fce54d..27a25cb 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -130,6 +130,7 @@ class Stream : public oboe::AudioStreamDataCallback, const char *Resume(); const char *Close(); const char *AppendBuffer(float *buf, size_t len); + int64_t Latency(); oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream, void *audio_data, @@ -215,6 +216,13 @@ class Stream : public oboe::AudioStreamDataCallback, std::atomic min_wait_us_{1000}; std::atomic max_callback_{0}; + // buffers_ready_ says fifo_ is made, and + // stream_latency_frames_ is how many frames the stream playing holds that are + // still to be heard, as its timestamp last said, or -1 while it has not said. + // LoopRead measures it every kLatencyEvery. + std::atomic buffers_ready_{false}; + std::atomic stream_latency_frames_{-1}; + // read_thread_ runs LoopRead, which reads from Go into fifo_. std::unique_ptr read_thread_; @@ -276,6 +284,7 @@ void Stream::PrepareBuffersLocked() { // One second of sound is more than any device's queue. fifo_ = std::make_unique(channel_num_ * sizeof(float), sample_rate_); + buffers_ready_.store(true); } // ConfigureRefillLocked sets how LoopRead refills fifo_ for the stream just @@ -312,6 +321,8 @@ Status Stream::EnsureStreamLocked() { return Status{}; } ConfigureRefillLocked(); + // The stream is new, and has not said how long it takes yet. + stream_latency_frames_.store(-1); // No callback can run before the stream is started, so the fifo can be // emptied here. Its contents were mixed for the device that went away and // would otherwise be played late on the new one. @@ -510,8 +521,40 @@ oboe::DataCallbackResult Stream::onAudioReady(oboe::AudioStream *oboe_stream, Stream::Stream() = default; +// kLatencyEvery is how often LoopRead measures how long the stream takes to +// play what it is given. +constexpr std::chrono::milliseconds kLatencyEvery{100}; + +// Latency returns how many frames read from Go are still to be heard: those +// queued in fifo_, and those the stream holds, which on Android includes a +// Bluetooth headset's own delay where the headset reports it. It returns -1 +// while the stream has not said yet. +int64_t Stream::Latency() { + if (!buffers_ready_.load()) { + return -1; + } + int64_t stream = stream_latency_frames_.load(); + if (stream < 0) { + return -1; + } + return stream + fifo_->getFullFramesAvailable(); +} + void Stream::LoopRead() { + auto measured = std::chrono::steady_clock::now(); for (;;) { + if (auto now = std::chrono::steady_clock::now(); now - measured >= kLatencyEvery) { + measured = now; + // The stream is reached under mutex_, which Pause and Resume hold only + // briefly; a measurement is skipped rather than waited for. + std::unique_lock lock{mutex_, std::try_to_lock}; + if (lock.owns_lock() && stream_ && state_ == State::kRunning) { + if (auto ms = stream_->calculateLatencyMillis(); ms) { + stream_latency_frames_.store( + static_cast(ms.value() * sample_rate_ / 1000)); + } + } + } // The queue is kept at the larger of the target and two of the largest // callbacks so far plus a read, for a device whose callbacks outgrow its // bursts, and at most the fifo's capacity less one read. @@ -577,4 +620,6 @@ const char *oto_oboe_Suspend() { return Stream::GetInstance().Pause(); } const char *oto_oboe_Resume() { return Stream::GetInstance().Resume(); } +int64_t oto_oboe_Latency() { return Stream::GetInstance().Latency(); } + } // extern "C" diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 86355ed..4601735 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -63,6 +63,13 @@ func Resume() error { return nil } +// Latency returns how many frames read from the read function are still to be +// heard, and whether the device has said yet. +func Latency() (int64, bool) { + n := int64(C.oto_oboe_Latency()) + return n, n >= 0 +} + //export oto_oboe_read func oto_oboe_read(buf *C.float, len C.size_t) { theReadFunc(unsafe.Slice((*float32)(unsafe.Pointer(buf)), len)) diff --git a/internal/oboe/binding_android.h b/internal/oboe/binding_android.h index 334ce5d..41678a7 100644 --- a/internal/oboe/binding_android.h +++ b/internal/oboe/binding_android.h @@ -27,6 +27,7 @@ const char *oto_oboe_Play(int sample_rate, int channel_num, int buffer_size_in_bytes); const char *oto_oboe_Suspend(); const char *oto_oboe_Resume(); +int64_t oto_oboe_Latency(); #ifdef __cplusplus } diff --git a/outputlatency_android.go b/outputlatency_android.go new file mode 100644 index 0000000..94a8ce7 --- /dev/null +++ b/outputlatency_android.go @@ -0,0 +1,28 @@ +// Copyright 2026 The Oto Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oto + +import "time" + +// OutputLatency returns how long the sound the context has read from its +// players takes to be heard, as the device last reported it, and whether it +// has. It counts what the context queues and what the device holds, which on +// Android includes a Bluetooth headset's own delay where the headset reports +// it. It leaves out what each player buffers: see Player.BufferedSize. +// +// OutputLatency is concurrent-safe. +func (c *Context) OutputLatency() (time.Duration, bool) { + return c.context.outputLatency() +} diff --git a/outputlatency_other.go b/outputlatency_other.go new file mode 100644 index 0000000..c21b773 --- /dev/null +++ b/outputlatency_other.go @@ -0,0 +1,32 @@ +// Copyright 2026 The Oto Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !android + +package oto + +import "time" + +// OutputLatency returns how long the sound the context has read from its +// players takes to be heard, as the device last reported it, and whether it +// has. It counts what the context queues and what the device holds, which on +// Android includes a Bluetooth headset's own delay where the headset reports +// it. It leaves out what each player buffers: see Player.BufferedSize. +// +// Only Android reports it so far; elsewhere it returns false. +// +// OutputLatency is concurrent-safe. +func (c *Context) OutputLatency() (time.Duration, bool) { + return 0, false +} From e478e38d1961e495422c6e0bc01bd7c6c3705976 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 7 Oct 2026 07:55:11 +0200 Subject: [PATCH 02/12] oto: give OutputLatency to every driver, as Suspend and Resume are OutputLatency is declared in context.go and calls the driver's context, as Suspend, Resume and Err do. Android reports the latency, and the other drivers report none for now; each is where a later change adds its platform. outputlatency_android.go and outputlatency_other.go are gone. TestOutputLatency asks the test's context: a latency reported is zero or more, and one not reported is zero. Co-Authored-By: Claude Opus 5.5 (1M context) --- context.go | 10 ++++++++++ driver_android.go | 2 +- driver_console.go | 6 ++++++ driver_darwin.go | 4 ++++ driver_js.go | 5 +++++ driver_unix.go | 5 +++++ driver_windows.go | 4 ++++ internal/oboe/binding_android.cpp | 8 ++++---- oto_test.go | 10 ++++++++++ outputlatency_android.go | 28 --------------------------- outputlatency_other.go | 32 ------------------------------- 11 files changed, 49 insertions(+), 65 deletions(-) delete mode 100644 outputlatency_android.go delete mode 100644 outputlatency_other.go diff --git a/context.go b/context.go index 5706954..3b11ab6 100644 --- a/context.go +++ b/context.go @@ -207,6 +207,16 @@ func (c *Context) Err() error { return c.context.Err() } +// OutputLatency returns how long the sound the context has read from its +// players takes to be heard, and whether the device reports it. It counts what +// the context queues and what the device holds, and leaves out what each +// player buffers: see Player.BufferedSize. Only Android reports it so far. +// +// OutputLatency is concurrent-safe. +func (c *Context) OutputLatency() (time.Duration, bool) { + return c.context.OutputLatency() +} + type atomicError struct { err error m sync.Mutex diff --git a/driver_android.go b/driver_android.go index b9d3a44..67f0bfe 100644 --- a/driver_android.go +++ b/driver_android.go @@ -64,7 +64,7 @@ func (c *context) Resume() error { return oboe.Resume() } -func (c *context) outputLatency() (time.Duration, bool) { +func (c *context) OutputLatency() (time.Duration, bool) { n, ok := oboe.Latency() if !ok { return 0, false diff --git a/driver_console.go b/driver_console.go index 76adb04..6e6fce3 100644 --- a/driver_console.go +++ b/driver_console.go @@ -29,6 +29,8 @@ package oto // } import "C" +import "time" + import ( "unsafe" @@ -72,3 +74,7 @@ func (c *context) Resume() error { func (c *context) Err() error { return nil } + +func (c *context) OutputLatency() (time.Duration, bool) { + return 0, false +} diff --git a/driver_darwin.go b/driver_darwin.go index 951f642..abf1ebc 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -485,6 +485,10 @@ func (c *context) Err() error { return c.err.Load() } +func (c *context) OutputLatency() (time.Duration, bool) { + return 0, false +} + func render(inUserData unsafe.Pointer, inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef) { theContext.cond.L.Lock() defer theContext.cond.L.Unlock() diff --git a/driver_js.go b/driver_js.go index e1e8f20..7c8c98b 100644 --- a/driver_js.go +++ b/driver_js.go @@ -19,6 +19,7 @@ import ( "fmt" "runtime" "syscall/js" + "time" "unsafe" "github.com/ebitengine/oto/v3/internal/mux" @@ -251,6 +252,10 @@ func (c *context) Err() error { return c.err.Load() } +func (c *context) OutputLatency() (time.Duration, bool) { + return 0, false +} + func float32SliceToTypedArray(s []float32) js.Value { bs := unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), len(s)*4) a := js.Global().Get("Uint8Array").New(len(bs)) diff --git a/driver_unix.go b/driver_unix.go index 19879f4..ae14549 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -18,6 +18,7 @@ package oto import ( "fmt" + "time" "github.com/ebitengine/oto/v3/internal/mux" ) @@ -108,3 +109,7 @@ func (c *context) Err() error { } return nil } + +func (c *context) OutputLatency() (time.Duration, bool) { + return 0, false +} diff --git a/driver_windows.go b/driver_windows.go index d091e3d..fcea3d4 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -125,6 +125,10 @@ func (c *context) Err() error { return nil } +func (c *context) OutputLatency() (time.Duration, bool) { + return 0, false +} + type nullContext struct { suspended atomic.Bool } diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 27a25cb..0e72df9 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -526,9 +526,8 @@ Stream::Stream() = default; constexpr std::chrono::milliseconds kLatencyEvery{100}; // Latency returns how many frames read from Go are still to be heard: those -// queued in fifo_, and those the stream holds, which on Android includes a -// Bluetooth headset's own delay where the headset reports it. It returns -1 -// while the stream has not said yet. +// queued in fifo_, and those the stream holds. It returns -1 while the stream +// has not said yet. int64_t Stream::Latency() { if (!buffers_ready_.load()) { return -1; @@ -543,7 +542,8 @@ int64_t Stream::Latency() { void Stream::LoopRead() { auto measured = std::chrono::steady_clock::now(); for (;;) { - if (auto now = std::chrono::steady_clock::now(); now - measured >= kLatencyEvery) { + if (auto now = std::chrono::steady_clock::now(); + now - measured >= kLatencyEvery) { measured = now; // The stream is reached under mutex_, which Pause and Resume hold only // briefly; a measurement is skipped rather than waited for. diff --git a/oto_test.go b/oto_test.go index fac52f4..5b542c7 100644 --- a/oto_test.go +++ b/oto_test.go @@ -48,6 +48,16 @@ func TestEmptyPlayer(t *testing.T) { } } +func TestOutputLatency(t *testing.T) { + d, ok := theContext.OutputLatency() + if ok && d < 0 { + t.Errorf("OutputLatency() = %v, true; want a duration of zero or more", d) + } + if !ok && d != 0 { + t.Errorf("OutputLatency() = %v, false; want zero with false", d) + } +} + // Issue #258 func TestSetBufferSize(t *testing.T) { for range 10 { diff --git a/outputlatency_android.go b/outputlatency_android.go deleted file mode 100644 index 94a8ce7..0000000 --- a/outputlatency_android.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2026 The Oto Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oto - -import "time" - -// OutputLatency returns how long the sound the context has read from its -// players takes to be heard, as the device last reported it, and whether it -// has. It counts what the context queues and what the device holds, which on -// Android includes a Bluetooth headset's own delay where the headset reports -// it. It leaves out what each player buffers: see Player.BufferedSize. -// -// OutputLatency is concurrent-safe. -func (c *Context) OutputLatency() (time.Duration, bool) { - return c.context.outputLatency() -} diff --git a/outputlatency_other.go b/outputlatency_other.go deleted file mode 100644 index c21b773..0000000 --- a/outputlatency_other.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2026 The Oto Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !android - -package oto - -import "time" - -// OutputLatency returns how long the sound the context has read from its -// players takes to be heard, as the device last reported it, and whether it -// has. It counts what the context queues and what the device holds, which on -// Android includes a Bluetooth headset's own delay where the headset reports -// it. It leaves out what each player buffers: see Player.BufferedSize. -// -// Only Android reports it so far; elsewhere it returns false. -// -// OutputLatency is concurrent-safe. -func (c *Context) OutputLatency() (time.Duration, bool) { - return 0, false -} From 91f34343821d8f5495b6fbc52887c805142a6d36 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Thu, 8 Oct 2026 08:31:31 +0200 Subject: [PATCH 03/12] oto: say how each driver could report OutputLatency Each driver that reports no latency yet has a TODO naming what it would use: PulseAudio's latency query and snd_pcm_delay on Linux, IAudioClock and waveOutGetPosition on Windows, the audio queue's time and the device's latency on macOS and iOS, and the AudioContext's latencies on the web. Co-Authored-By: Claude Opus 5.5 --- driver_console.go | 1 + driver_darwin.go | 3 +++ driver_js.go | 2 ++ driver_unix.go | 3 +++ driver_windows.go | 3 +++ 5 files changed, 12 insertions(+) diff --git a/driver_console.go b/driver_console.go index 6e6fce3..f320b57 100644 --- a/driver_console.go +++ b/driver_console.go @@ -76,5 +76,6 @@ func (c *context) Err() error { } func (c *context) OutputLatency() (time.Duration, bool) { + // TODO: Report the latency where the console's audio API gives it. return 0, false } diff --git a/driver_darwin.go b/driver_darwin.go index abf1ebc..1803073 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -486,6 +486,9 @@ func (c *context) Err() error { } func (c *context) OutputLatency() (time.Duration, bool) { + // TODO: Report the latency: the frames enqueued less the queue's position + // from AudioQueueGetCurrentTime, plus the device's latency, which on iOS + // AVAudioSession's outputLatency gives. return 0, false } diff --git a/driver_js.go b/driver_js.go index 7c8c98b..f8b857b 100644 --- a/driver_js.go +++ b/driver_js.go @@ -253,6 +253,8 @@ func (c *context) Err() error { } func (c *context) OutputLatency() (time.Duration, bool) { + // TODO: Report the latency: the AudioContext's outputLatency and + // baseLatency, plus what is scheduled and not yet played. return 0, false } diff --git a/driver_unix.go b/driver_unix.go index ae14549..87900c1 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -111,5 +111,8 @@ func (c *context) Err() error { } func (c *context) OutputLatency() (time.Duration, bool) { + // TODO: Report the latency: from PulseAudio's latency query for its stream, + // and from snd_pcm_delay on ALSA, plus what the driver has read and not + // yet written. return 0, false } diff --git a/driver_windows.go b/driver_windows.go index fcea3d4..8c472e9 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -126,6 +126,9 @@ func (c *context) Err() error { } func (c *context) OutputLatency() (time.Duration, bool) { + // TODO: Report the latency: on WASAPI, the frames written less the position + // IAudioClock reports, and GetStreamLatency; on WinMM, the frames written + // less the position waveOutGetPosition reports. return 0, false } From 3d1f7681f6bc65580e65a1804f90b7713e3d4618 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Fri, 9 Oct 2026 10:46:25 +0200 Subject: [PATCH 04/12] oto: report what each player has not played yet, in place of OutputLatency The delay after the mux is shared by the players, but an app needs it per player: which of this player's data is heard now, also after Pause, right after Play, and at the end of the source. - The mux counts the samples it mixes, and each player records the spans of the mix its data went into, while they may be unheard. - Each driver reports, through Mux.SetDelayFunc, how many of the frames the mux has mixed are not heard yet. Android does; the others have a TODO naming what they would use. - Player.UnplayedSize returns the bytes read from the source that are not heard yet: what BufferedSize returns, and what was sent on and not played. Where the driver reports nothing, it returns what BufferedSize does. Seek and Reset forget what was sent. - Context.OutputLatency is gone. On Android, LoopRead measures every 100 ms when the frame written to the fifo next will be heard, and Delay counts on from that pair, so the fifo and the stream are sampled together. The stream is asked outside mutex_, and a measurement is kept only if the stream is unchanged and no callback ran meanwhile. It is forgotten wherever the stream is dropped, paused or replaced, clamped at zero, and estimated from the stream's buffer on OpenSL ES, which has no timestamps. Co-Authored-By: Claude Opus 5.5 --- context.go | 10 -- driver_android.go | 16 +--- driver_console.go | 9 +- driver_darwin.go | 10 +- driver_js.go | 9 +- driver_unix.go | 11 +-- driver_windows.go | 10 +- internal/mux/mux.go | 108 ++++++++++++++++++++- internal/mux/unplayed_test.go | 153 ++++++++++++++++++++++++++++++ internal/oboe/binding_android.cpp | 129 ++++++++++++++++++------- internal/oboe/binding_android.go | 8 +- internal/oboe/binding_android.h | 2 +- oto_test.go | 16 ++-- player.go | 10 ++ 14 files changed, 396 insertions(+), 105 deletions(-) create mode 100644 internal/mux/unplayed_test.go diff --git a/context.go b/context.go index 3b11ab6..5706954 100644 --- a/context.go +++ b/context.go @@ -207,16 +207,6 @@ func (c *Context) Err() error { return c.context.Err() } -// OutputLatency returns how long the sound the context has read from its -// players takes to be heard, and whether the device reports it. It counts what -// the context queues and what the device holds, and leaves out what each -// player buffers: see Player.BufferedSize. Only Android reports it so far. -// -// OutputLatency is concurrent-safe. -func (c *Context) OutputLatency() (time.Duration, bool) { - return c.context.OutputLatency() -} - type atomicError struct { err error m sync.Mutex diff --git a/driver_android.go b/driver_android.go index 67f0bfe..6402e5c 100644 --- a/driver_android.go +++ b/driver_android.go @@ -16,15 +16,13 @@ package oto import ( "sync" - "time" "github.com/ebitengine/oto/v3/internal/mux" "github.com/ebitengine/oto/v3/internal/oboe" ) type context struct { - mux *mux.Mux - sampleRate int + mux *mux.Mux err atomicError @@ -35,9 +33,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI ready := make(chan struct{}) c := &context{ - mux: mux.New(sampleRate, channelCount, format), - sampleRate: sampleRate, + mux: mux.New(sampleRate, channelCount, format), } + c.mux.SetDelayFunc(oboe.Delay) go func() { // The ready channel must close even if Play fails, or callers waiting on it block forever. defer close(ready) @@ -64,14 +62,6 @@ func (c *context) Resume() error { return oboe.Resume() } -func (c *context) OutputLatency() (time.Duration, bool) { - n, ok := oboe.Latency() - if !ok { - return 0, false - } - return time.Duration(n) * time.Second / time.Duration(c.sampleRate), true -} - func (c *context) Err() error { return c.err.Load() } diff --git a/driver_console.go b/driver_console.go index f320b57..449ff15 100644 --- a/driver_console.go +++ b/driver_console.go @@ -29,8 +29,6 @@ package oto // } import "C" -import "time" - import ( "unsafe" @@ -55,6 +53,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c := &context{ mux: mux.New(sampleRate, channelCount, format), } + // TODO: Report the delay with c.mux.SetDelayFunc, where the console's audio + // API gives it. theContext = c C.oto_OpenAudioProxy(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)) @@ -74,8 +74,3 @@ func (c *context) Resume() error { func (c *context) Err() error { return nil } - -func (c *context) OutputLatency() (time.Duration, bool) { - // TODO: Report the latency where the console's audio API gives it. - return 0, false -} diff --git a/driver_darwin.go b/driver_darwin.go index 1803073..11f8d6e 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -160,6 +160,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI channelCount: channelCount, oneBufferSizeInBytes: oneBufferSizeInBytes, } + // TODO: Report the delay with c.mux.SetDelayFunc: the frames enqueued less + // the queue's position from AudioQueueGetCurrentTime, plus the device's + // latency, which on iOS AVAudioSession's outputLatency gives. theContext = c if err := initializeAPI(); err != nil { @@ -485,13 +488,6 @@ func (c *context) Err() error { return c.err.Load() } -func (c *context) OutputLatency() (time.Duration, bool) { - // TODO: Report the latency: the frames enqueued less the queue's position - // from AudioQueueGetCurrentTime, plus the device's latency, which on iOS - // AVAudioSession's outputLatency gives. - return 0, false -} - func render(inUserData unsafe.Pointer, inAQ _AudioQueueRef, inBuffer _AudioQueueBufferRef) { theContext.cond.L.Lock() defer theContext.cond.L.Unlock() diff --git a/driver_js.go b/driver_js.go index f8b857b..e7ef279 100644 --- a/driver_js.go +++ b/driver_js.go @@ -19,7 +19,6 @@ import ( "fmt" "runtime" "syscall/js" - "time" "unsafe" "github.com/ebitengine/oto/v3/internal/mux" @@ -51,6 +50,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI audioContext: class.New(options), mux: mux.New(sampleRate, channelCount, format), } + // TODO: Report the delay with d.mux.SetDelayFunc: the AudioContext's + // outputLatency and baseLatency, plus what is scheduled and not yet played. if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. @@ -252,12 +253,6 @@ func (c *context) Err() error { return c.err.Load() } -func (c *context) OutputLatency() (time.Duration, bool) { - // TODO: Report the latency: the AudioContext's outputLatency and - // baseLatency, plus what is scheduled and not yet played. - return 0, false -} - func float32SliceToTypedArray(s []float32) js.Value { bs := unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), len(s)*4) a := js.Global().Get("Uint8Array").New(len(bs)) diff --git a/driver_unix.go b/driver_unix.go index 87900c1..82f6f11 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -18,7 +18,6 @@ package oto import ( "fmt" - "time" "github.com/ebitengine/oto/v3/internal/mux" ) @@ -48,6 +47,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI mux: mux.New(sampleRate, channelCount, format), ready: make(chan struct{}), } + // TODO: Report the delay with ctx.mux.SetDelayFunc: from PulseAudio's latency + // query for its stream, and from 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. @@ -109,10 +111,3 @@ func (c *context) Err() error { } return nil } - -func (c *context) OutputLatency() (time.Duration, bool) { - // TODO: Report the latency: from PulseAudio's latency query for its stream, - // and from snd_pcm_delay on ALSA, plus what the driver has read and not - // yet written. - return 0, false -} diff --git a/driver_windows.go b/driver_windows.go index 8c472e9..6c99785 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -46,6 +46,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI mux: mux.New(sampleRate, channelCount, format), ready: make(chan struct{}), } + // TODO: Report the delay with ctx.mux.SetDelayFunc: on WASAPI, the frames + // written less the position IAudioClock reports; on WinMM, the frames written + // less the position waveOutGetPosition reports. // Initializing drivers might take some time. Do this asynchronously. go func() { @@ -125,13 +128,6 @@ func (c *context) Err() error { return nil } -func (c *context) OutputLatency() (time.Duration, bool) { - // TODO: Report the latency: on WASAPI, the frames written less the position - // IAudioClock reports, and GetStreamLatency; on WinMM, the frames written - // less the position waveOutGetPosition reports. - return 0, false -} - type nullContext struct { suspended atomic.Bool } diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 7652d83..8250a8b 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -23,6 +23,7 @@ import ( "math" "runtime" "sync" + "sync/atomic" "time" ) @@ -61,8 +62,21 @@ type Mux struct { // stopped says Stop was called, and the loop filling the players' buffers // returns. It is guarded by cond.L. stopped bool + + // mixed counts the samples ReadFloat32s has mixed. + mixed atomic.Int64 + + // delay is the driver's report of how many of the frames ReadFloat32s has + // mixed are not heard yet, and whether it knows, or nil where the driver + // reports nothing. + delay func() (int64, bool) } +// maxSentSpans is the most spans of the mix a player remembers its data went +// into while they may be unheard. Spans the player fills back to back merge, +// so a player that plays on keeps one. +const maxSentSpans = 256 + // New creates a new Mux. func New(sampleRate int, channelCount int, format Format) *Mux { m := &Mux{ @@ -155,6 +169,27 @@ func (m *Mux) removePlayer(player *playerImpl) { delete(m.players, player) } +// SetDelayFunc sets how the driver reports its delay: f returns how many of the +// frames ReadFloat32s has mixed are not heard yet, and whether it knows. It is +// set before the players play. +func (m *Mux) SetDelayFunc(f func() (int64, bool)) { + m.delay = f +} + +// heard returns how many of the samples mixed have been heard, and whether the +// driver reports it. +func (m *Mux) heard() (int64, bool) { + if m.delay == nil { + return 0, false + } + mixed := m.mixed.Load() + d, ok := m.delay() + if !ok { + return 0, false + } + return mixed - max(d, 0)*int64(m.channelCount), true +} + // Stop stops the Mux from reading the players' sources. func (m *Mux) Stop() { m.cond.L.Lock() @@ -180,9 +215,11 @@ func (m *Mux) ReadFloat32s(buf []float32) { for i := range buf { buf[i] = 0 } + start := m.mixed.Load() for _, p := range players { - p.readBufferAndAdd(buf) + p.readBufferAndAdd(buf, start) } + m.mixed.Add(int64(len(buf))) m.signal() } @@ -237,9 +274,20 @@ type playerImpl struct { // The result of a read that started at an older generation is stale and must be discarded. srcGen int + // sent holds the spans of the mix this player's data went into, oldest + // first, while they may be unheard. + sent []sentSpan + m sync.Mutex } +// A sentSpan is a span of the mix, from sample start to end, that a player's +// data went into, a sample of its data each. +type sentSpan struct { + start int64 + end int64 +} + func (m *Mux) NewPlayer(src io.Reader) *Player { p := &playerImpl{ mux: m, @@ -406,6 +454,8 @@ func (p *playerImpl) Seek(offset int64, whence int) (int64, error) { p.readPos = 0 p.eof = false p.srcGen++ + // The data sent before is from the old position. + p.sent = p.sent[:0] // Wait until an ongoing read from the source finishes. // Otherwise the source would be sought while it is being read. @@ -433,6 +483,7 @@ func (p *playerImpl) Reset() { p.buf = p.buf[:0] p.readPos = 0 p.eof = false + p.sent = p.sent[:0] // The buffered data is discarded, so a pending source error is reported now. p.reportSourceErrorIfDrainedImpl() @@ -489,6 +540,53 @@ func (p *playerImpl) BufferedSize() int { return p.buffered() } +func (p *Player) UnplayedSize() int { + return p.p.UnplayedSize() +} + +func (p *playerImpl) UnplayedSize() int { + p.m.Lock() + defer p.m.Unlock() + + n := p.buffered() + heard, ok := p.mux.heard() + if !ok { + p.sent = p.sent[:0] + return n + } + p.forgetHeard(heard) + for _, s := range p.sent { + n += int(s.end-max(s.start, heard)) * p.mux.format.ByteLength() + } + return n +} + +// forgetHeard drops the spans sent that end by sample heard of the mix. +// +// When forgetHeard is called, the mutex m must be locked. +func (p *playerImpl) forgetHeard(heard int64) { + i := 0 + for i < len(p.sent) && p.sent[i].end <= heard { + i++ + } + p.sent = append(p.sent[:0], p.sent[i:]...) +} + +// recordSent records that the player's data went into samples start to end of +// the mix. +// +// When recordSent is called, the mutex m must be locked. +func (p *playerImpl) recordSent(start, end int64) { + if last := len(p.sent) - 1; last >= 0 && p.sent[last].end == start { + p.sent[last].end = end + return + } + if len(p.sent) == maxSentSpans { + p.sent = append(p.sent[:0], p.sent[1:]...) + } + p.sent = append(p.sent, sentSpan{start: start, end: end}) +} + func (p *Player) Close() error { p.cleanup.Stop() return p.p.Close() @@ -527,7 +625,9 @@ func (p *playerImpl) drained() bool { return p.eof && p.buffered() < p.mux.format.ByteLength() } -func (p *playerImpl) readBufferAndAdd(buf []float32) int { +// readBufferAndAdd adds the player's buffered data to buf, which goes into the +// mix from sample start. +func (p *playerImpl) readBufferAndAdd(buf []float32, start int64) int { p.m.Lock() defer p.m.Unlock() @@ -587,6 +687,10 @@ func (p *playerImpl) readBufferAndAdd(buf []float32) int { p.prevVolume = p.volume + if n > 0 { + p.recordSent(start, start+int64(n)) + } + // The consumed region is compacted lazily when the buffer is refilled. p.readPos += n * bitDepthInBytes if p.readPos == len(p.buf) { diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go new file mode 100644 index 0000000..a7a4ab8 --- /dev/null +++ b/internal/mux/unplayed_test.go @@ -0,0 +1,153 @@ +// Copyright 2026 The Oto Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mux_test + +import ( + "bytes" + "testing" + "time" + + "github.com/ebitengine/oto/v3/internal/mux" +) + +// The tests play 48 kHz stereo float32: 8 bytes a frame. +const bytesPerFrame = 8 + +// newDelayedMux returns a mux whose driver reports delay frames as not heard +// yet, where known is true. +func newDelayedMux(t *testing.T, delay int64, known bool) *mux.Mux { + t.Helper() + + m := mux.New(48000, 2, mux.FormatFloat32LE) + t.Cleanup(m.Stop) + if known { + m.SetDelayFunc(func() (int64, bool) { + return delay, true + }) + } + return m +} + +// newBufferedPlayer plays frames frames of sound on m, once the player has +// read all of them from its source. +func newBufferedPlayer(t *testing.T, m *mux.Mux, frames int) *mux.Player { + t.Helper() + + p := newPlayer(t, m, bytes.NewReader(bytes.Repeat([]byte{0, 0, 0x80, 0x3f}, frames*2))) + p.SetBufferSize(frames * bytesPerFrame) + p.Play() + deadline := time.Now().Add(time.Second) + for p.BufferedSize() < frames*bytesPerFrame { + if time.Now().After(deadline) { + t.Fatalf("the player buffered %d bytes of %d", p.BufferedSize(), frames*bytesPerFrame) + } + time.Sleep(time.Millisecond) + } + return p +} + +// readFrames mixes frames frames from m, as a driver reads. +func readFrames(m *mux.Mux, frames int) { + m.ReadFloat32s(make([]float32, frames*2)) +} + +func TestUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { + m := newDelayedMux(t, 0, false) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, 480) + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} + +func TestUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { + const delay = 1000 + m := newDelayedMux(t, delay, true) + p := newBufferedPlayer(t, m, 4800) + + // Right after Play, nothing is sent yet. + if got, want := p.UnplayedSize(), 4800*bytesPerFrame; got != want { + t.Fatalf("before any read: UnplayedSize() = %d; want %d", got, want) + } + // While less than the delay is mixed, none of it is heard: the whole + // source is unplayed. + readFrames(m, 480) + readFrames(m, 480) + if got, want := p.UnplayedSize(), 4800*bytesPerFrame; got != want { + t.Fatalf("after 960 frames: UnplayedSize() = %d; want %d", got, want) + } + // Then the delay's worth of what is sent stays unheard. + readFrames(m, 480) + if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { + t.Errorf("after 1,440 frames: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) + } +} + +func TestUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { + const delay = 1000 + m := newDelayedMux(t, delay, true) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, 1440) + p.Pause() + + // What was sent before Pause is still to be heard, and is heard as the + // device plays on. + if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { + t.Fatalf("right after Pause: UnplayedSize() = %d; want %d", got, want) + } + readFrames(m, 400) + if got, want := p.UnplayedSize(), p.BufferedSize()+(delay-400)*bytesPerFrame; got != want { + t.Fatalf("400 frames after Pause: UnplayedSize() = %d; want %d", got, want) + } + readFrames(m, 600) + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("a delay after Pause: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} + +func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { + const delay = 1000 + m := newDelayedMux(t, delay, true) + p := newBufferedPlayer(t, m, 960) + readFrames(m, 960) + // The mux finds the source's end on its next read from it. + deadline := time.Now().Add(time.Second) + for p.IsPlaying() { + if time.Now().After(deadline) { + t.Fatal("the player plays on after its source is mixed") + } + time.Sleep(time.Millisecond) + } + if got, want := p.UnplayedSize(), 960*bytesPerFrame; got != want { + t.Fatalf("as the source ends: UnplayedSize() = %d; want %d", got, want) + } + readFrames(m, 1000) + if got := p.UnplayedSize(); got != 0 { + t.Errorf("a delay after the source ends: UnplayedSize() = %d; want 0", got) + } +} + +func TestUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { + const delay = 1000 + m := newDelayedMux(t, delay, true) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, 1440) + if _, err := p.Seek(0, 0); err != nil { + t.Fatal(err) + } + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("after Seek: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 0e72df9..b4ed319 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -130,7 +131,7 @@ class Stream : public oboe::AudioStreamDataCallback, const char *Resume(); const char *Close(); const char *AppendBuffer(float *buf, size_t len); - int64_t Latency(); + int64_t Delay(); oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream, void *audio_data, @@ -146,6 +147,8 @@ class Stream : public oboe::AudioStreamDataCallback, // The Locked functions must be called with mutex_ held. Status OpenLocked(); void CloseLocked(); + void ForgetDelayLocked(); + void MeasureDelay(); void PrepareBuffersLocked(); void ConfigureRefillLocked(); Status EnsureStreamLocked(); @@ -216,12 +219,17 @@ class Stream : public oboe::AudioStreamDataCallback, std::atomic min_wait_us_{1000}; std::atomic max_callback_{0}; - // buffers_ready_ says fifo_ is made, and - // stream_latency_frames_ is how many frames the stream playing holds that are - // still to be heard, as its timestamp last said, or -1 while it has not said. - // LoopRead measures it every kLatencyEvery. - std::atomic buffers_ready_{false}; - std::atomic stream_latency_frames_{-1}; + // The delay. Every kDelayEvery, LoopRead measures when the frame written to + // fifo_ next will be heard: delay_written_ is the write counter then, and + // delay_heard_at_ the time, while delay_known_ is set. delay_gen_ counts the + // streams dropped, paused and opened, so that a measurement of a stream that + // changed meanwhile is dropped. delay_mutex_ guards these, and is taken after + // mutex_ where both are. + std::mutex delay_mutex_; + bool delay_known_ = false; + int64_t delay_written_ = 0; + std::chrono::steady_clock::time_point delay_heard_at_; + int delay_gen_ = 0; // read_thread_ runs LoopRead, which reads from Go into fifo_. std::unique_ptr read_thread_; @@ -267,6 +275,7 @@ Status Stream::OpenLocked() { // running stream, and its result is of no interest: the stream is not used // again either way. void Stream::CloseLocked() { + ForgetDelayLocked(); if (!stream_) { return; } @@ -284,7 +293,6 @@ void Stream::PrepareBuffersLocked() { // One second of sound is more than any device's queue. fifo_ = std::make_unique(channel_num_ * sizeof(float), sample_rate_); - buffers_ready_.store(true); } // ConfigureRefillLocked sets how LoopRead refills fifo_ for the stream just @@ -321,8 +329,6 @@ Status Stream::EnsureStreamLocked() { return Status{}; } ConfigureRefillLocked(); - // The stream is new, and has not said how long it takes yet. - stream_latency_frames_.store(-1); // No callback can run before the stream is started, so the fifo can be // emptied here. Its contents were mixed for the device that went away and // would otherwise be played late on the new one. @@ -428,6 +434,7 @@ void Stream::onErrorAfterClose(oboe::AudioStream *oboe_stream, } // Oboe stopped and closed the stream before calling this, so the only way // to keep playing is to open a new one. + ForgetDelayLocked(); stream_.reset(); state_ = State::kStopped; // A stream that goes away while suspended stays closed until Resume, so @@ -451,6 +458,7 @@ void Stream::onErrorAfterClose(oboe::AudioStream *oboe_stream, const char *Stream::Pause() { std::lock_guard lock{mutex_}; suspended_ = true; + ForgetDelayLocked(); if (state_ == State::kStartDeferred) { // Nothing may start playing while the caller wants silence. Resume attempts // it again. @@ -501,6 +509,7 @@ const char *Stream::Close() { if (oboe::Result result = stream_->close(); result != oboe::Result::OK) { return oboe::convertToText(result); } + ForgetDelayLocked(); stream_.reset(); return nullptr; } @@ -521,39 +530,93 @@ oboe::DataCallbackResult Stream::onAudioReady(oboe::AudioStream *oboe_stream, Stream::Stream() = default; -// kLatencyEvery is how often LoopRead measures how long the stream takes to -// play what it is given. -constexpr std::chrono::milliseconds kLatencyEvery{100}; +// kDelayEvery is how often LoopRead measures the delay. +constexpr std::chrono::milliseconds kDelayEvery{100}; -// Latency returns how many frames read from Go are still to be heard: those -// queued in fifo_, and those the stream holds. It returns -1 while the stream -// has not said yet. -int64_t Stream::Latency() { - if (!buffers_ready_.load()) { - return -1; +// ForgetDelayLocked forgets the delay measured, as the stream it was measured +// on is dropped, paused or replaced. +void Stream::ForgetDelayLocked() { + std::lock_guard lock{delay_mutex_}; + delay_gen_++; + delay_known_ = false; +} + +// MeasureDelay measures when the frame written to fifo_ next will be heard. +void Stream::MeasureDelay() { + std::shared_ptr stream; + int gen; + { + // Pause and Resume hold mutex_ only briefly; a measurement is skipped + // rather than waited for. + std::unique_lock lock{mutex_, std::try_to_lock}; + if (!lock.owns_lock() || !stream_ || state_ != State::kRunning) { + return; + } + stream = stream_; + std::lock_guard delay_lock{delay_mutex_}; + gen = delay_gen_; + } + // The stream is asked outside mutex_, as asking it can wait on the device. + // Only this thread writes to fifo_, and a callback reads from it as the + // stream takes frames, so a measurement is kept only if no callback ran + // meanwhile. + for (int i = 0; i < 3; i++) { + int64_t read = fifo_->getReadCounter(); + double ms; + if (auto result = stream->calculateLatencyMillis(); result) { + // The next frame the stream takes is heard this long from now. It can + // come out negative, as around an underrun. + ms = std::max(0.0, result.value()); + } else if (result.error() == oboe::Result::ErrorUnimplemented) { + // OpenSL ES has no timestamps: the frames the stream holds are the + // estimate. + ms = stream->getBufferSizeInFrames() * 1000.0 / sample_rate_; + } else { + return; + } + auto now = std::chrono::steady_clock::now(); + if (fifo_->getReadCounter() != read) { + continue; + } + int64_t written = fifo_->getWriteCounter(); + // The frames queued in fifo_ are heard before the frame written next. + auto heard_at = + now + std::chrono::microseconds(std::llround( + ms * 1000 + (written - read) * 1e6 / sample_rate_)); + std::lock_guard lock{delay_mutex_}; + if (delay_gen_ != gen) { + return; + } + delay_known_ = true; + delay_written_ = written; + delay_heard_at_ = heard_at; + return; } - int64_t stream = stream_latency_frames_.load(); - if (stream < 0) { +} + +// Delay returns how many of the frames read from Go are not heard yet, or -1 +// while the stream has not been measured. +int64_t Stream::Delay() { + std::lock_guard lock{delay_mutex_}; + if (!delay_known_) { return -1; } - return stream + fifo_->getFullFramesAvailable(); + // The frame written next at the measurement is heard at delay_heard_at_, and + // the frames written since after it. + std::chrono::duration until = + delay_heard_at_ - std::chrono::steady_clock::now(); + int64_t frames = fifo_->getWriteCounter() - delay_written_ + + std::llround(until.count() * sample_rate_); + return std::max(frames, 0); } void Stream::LoopRead() { auto measured = std::chrono::steady_clock::now(); for (;;) { if (auto now = std::chrono::steady_clock::now(); - now - measured >= kLatencyEvery) { + now - measured >= kDelayEvery) { measured = now; - // The stream is reached under mutex_, which Pause and Resume hold only - // briefly; a measurement is skipped rather than waited for. - std::unique_lock lock{mutex_, std::try_to_lock}; - if (lock.owns_lock() && stream_ && state_ == State::kRunning) { - if (auto ms = stream_->calculateLatencyMillis(); ms) { - stream_latency_frames_.store( - static_cast(ms.value() * sample_rate_ / 1000)); - } - } + MeasureDelay(); } // The queue is kept at the larger of the target and two of the largest // callbacks so far plus a read, for a device whose callbacks outgrow its @@ -620,6 +683,6 @@ const char *oto_oboe_Suspend() { return Stream::GetInstance().Pause(); } const char *oto_oboe_Resume() { return Stream::GetInstance().Resume(); } -int64_t oto_oboe_Latency() { return Stream::GetInstance().Latency(); } +int64_t oto_oboe_Delay() { return Stream::GetInstance().Delay(); } } // extern "C" diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 4601735..9879db7 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -63,10 +63,10 @@ func Resume() error { return nil } -// Latency returns how many frames read from the read function are still to be -// heard, and whether the device has said yet. -func Latency() (int64, bool) { - n := int64(C.oto_oboe_Latency()) +// Delay returns how many of the frames read with the read function are not +// heard yet, and whether the device reports it. +func Delay() (int64, bool) { + n := int64(C.oto_oboe_Delay()) return n, n >= 0 } diff --git a/internal/oboe/binding_android.h b/internal/oboe/binding_android.h index 41678a7..f2cbf6e 100644 --- a/internal/oboe/binding_android.h +++ b/internal/oboe/binding_android.h @@ -27,7 +27,7 @@ const char *oto_oboe_Play(int sample_rate, int channel_num, int buffer_size_in_bytes); const char *oto_oboe_Suspend(); const char *oto_oboe_Resume(); -int64_t oto_oboe_Latency(); +int64_t oto_oboe_Delay(); #ifdef __cplusplus } diff --git a/oto_test.go b/oto_test.go index 5b542c7..7d6bcd3 100644 --- a/oto_test.go +++ b/oto_test.go @@ -48,13 +48,17 @@ func TestEmptyPlayer(t *testing.T) { } } -func TestOutputLatency(t *testing.T) { - d, ok := theContext.OutputLatency() - if ok && d < 0 { - t.Errorf("OutputLatency() = %v, true; want a duration of zero or more", d) +func TestUnplayedSize(t *testing.T) { + p := theContext.NewPlayer(bytes.NewReader(make([]byte, 4800*8))) + p.Play() + for p.IsPlaying() { + if u, b := p.UnplayedSize(), p.BufferedSize(); u < b { + t.Fatalf("UnplayedSize() = %d, less than BufferedSize(), %d", u, b) + } + time.Sleep(time.Millisecond) } - if !ok && d != 0 { - t.Errorf("OutputLatency() = %v, false; want zero with false", d) + if u := p.UnplayedSize(); u < 0 { + t.Fatalf("UnplayedSize() = %d after the source ends; want 0 or more", u) } } diff --git a/player.go b/player.go index f6cf37d..d730233 100644 --- a/player.go +++ b/player.go @@ -79,6 +79,16 @@ func (p *Player) BufferedSize() int { return p.player.BufferedSize() } +// UnplayedSize returns the byte size of the data read from the source that is not heard yet: the buffered data, and +// the data sent to the audio hardware that it has not played yet, also after Pause and after the end of the source. +// Where the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as +// BufferedSize. Seek and Reset forget the data already sent. +// +// So the part of the source being heard now is the bytes read from it less UnplayedSize. +func (p *Player) UnplayedSize() int { + return p.player.UnplayedSize() +} + // Err returns an error that occurred while reading the source. // Reaching the end of the source (io.EOF) is not treated as an error. // An error is reported after the data read before it is played or discarded. From 8913cd778e53680276e86f728b5cfc7f5ccca234 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sat, 10 Oct 2026 09:51:47 +0200 Subject: [PATCH 05/12] oto: test UnplayedSize in virtual time, and tidy its comments The UnplayedSize tests run in testing/synctest bubbles and wait for the mux's loop with synctest.Wait, so their results depend on no machine's scheduler. Their cleanup lets the loop see Stop after the moment it sleeps once a source has ended. sentSpan's literal has a field a line. Doc comments say what each thing does: how spans merge is said where they merge, and ForgetDelayLocked's says only what it forgets. MeasureDelay says why a few tries are enough. Co-Authored-By: Claude Opus 5.5 --- internal/mux/mux.go | 12 ++++--- internal/mux/unplayed_test.go | 53 +++++++++++++++++++++++-------- internal/oboe/binding_android.cpp | 6 ++-- 3 files changed, 50 insertions(+), 21 deletions(-) diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 8250a8b..3711873 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -73,8 +73,7 @@ type Mux struct { } // maxSentSpans is the most spans of the mix a player remembers its data went -// into while they may be unheard. Spans the player fills back to back merge, -// so a player that plays on keeps one. +// into while they may be unheard. const maxSentSpans = 256 // New creates a new Mux. @@ -282,7 +281,7 @@ type playerImpl struct { } // A sentSpan is a span of the mix, from sample start to end, that a player's -// data went into, a sample of its data each. +// data went into, one sample of the data to each sample of the mix. type sentSpan struct { start int64 end int64 @@ -577,6 +576,8 @@ func (p *playerImpl) forgetHeard(heard int64) { // // When recordSent is called, the mutex m must be locked. func (p *playerImpl) recordSent(start, end int64) { + // A span that follows on from the last merges with it, so a player that + // plays on keeps one. if last := len(p.sent) - 1; last >= 0 && p.sent[last].end == start { p.sent[last].end = end return @@ -584,7 +585,10 @@ func (p *playerImpl) recordSent(start, end int64) { if len(p.sent) == maxSentSpans { p.sent = append(p.sent[:0], p.sent[1:]...) } - p.sent = append(p.sent, sentSpan{start: start, end: end}) + p.sent = append(p.sent, sentSpan{ + start: start, + end: end, + }) } func (p *Player) Close() error { diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go index a7a4ab8..6dbb274 100644 --- a/internal/mux/unplayed_test.go +++ b/internal/mux/unplayed_test.go @@ -17,6 +17,7 @@ package mux_test import ( "bytes" "testing" + "testing/synctest" "time" "github.com/ebitengine/oto/v3/internal/mux" @@ -27,11 +28,21 @@ const bytesPerFrame = 8 // newDelayedMux returns a mux whose driver reports delay frames as not heard // yet, where known is true. +// +// The tests run in synctest bubbles, and wait for the mux's loop to fill the +// players' buffers with synctest.Wait, so their results depend on no +// machine's scheduler. func newDelayedMux(t *testing.T, delay int64, known bool) *mux.Mux { t.Helper() m := mux.New(48000, 2, mux.FormatFloat32LE) - t.Cleanup(m.Stop) + // The mux's loop must end before the synctest bubble does. It sees Stop + // the next time it waits, which can be after it sleeps a moment, as it + // does once a source has ended; in the bubble the sleep takes no time. + t.Cleanup(func() { + m.Stop() + time.Sleep(time.Second) + }) if known { m.SetDelayFunc(func() (int64, bool) { return delay, true @@ -41,19 +52,16 @@ func newDelayedMux(t *testing.T, delay int64, known bool) *mux.Mux { } // newBufferedPlayer plays frames frames of sound on m, once the player has -// read all of them from its source. +// read all of them from its source. It is called in a synctest bubble. func newBufferedPlayer(t *testing.T, m *mux.Mux, frames int) *mux.Player { t.Helper() p := newPlayer(t, m, bytes.NewReader(bytes.Repeat([]byte{0, 0, 0x80, 0x3f}, frames*2))) p.SetBufferSize(frames * bytesPerFrame) p.Play() - deadline := time.Now().Add(time.Second) - for p.BufferedSize() < frames*bytesPerFrame { - if time.Now().After(deadline) { - t.Fatalf("the player buffered %d bytes of %d", p.BufferedSize(), frames*bytesPerFrame) - } - time.Sleep(time.Millisecond) + synctest.Wait() + if got, want := p.BufferedSize(), frames*bytesPerFrame; got != want { + t.Fatalf("the player buffered %d bytes; want %d", got, want) } return p } @@ -64,6 +72,10 @@ func readFrames(m *mux.Mux, frames int) { } func TestUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { + synctest.Test(t, testUnplayedSizeIsBufferedSizeWithoutADelay) +} + +func testUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { m := newDelayedMux(t, 0, false) p := newBufferedPlayer(t, m, 4800) readFrames(m, 480) @@ -73,6 +85,10 @@ func TestUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { } func TestUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsWhatIsNotHeardYet) +} + +func testUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { const delay = 1000 m := newDelayedMux(t, delay, true) p := newBufferedPlayer(t, m, 4800) @@ -96,6 +112,10 @@ func TestUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { } func TestUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsWhatIsSentBeforePause) +} + +func testUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { const delay = 1000 m := newDelayedMux(t, delay, true) p := newBufferedPlayer(t, m, 4800) @@ -118,17 +138,18 @@ func TestUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { } func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard) +} + +func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { const delay = 1000 m := newDelayedMux(t, delay, true) p := newBufferedPlayer(t, m, 960) readFrames(m, 960) // The mux finds the source's end on its next read from it. - deadline := time.Now().Add(time.Second) - for p.IsPlaying() { - if time.Now().After(deadline) { - t.Fatal("the player plays on after its source is mixed") - } - time.Sleep(time.Millisecond) + synctest.Wait() + if p.IsPlaying() { + t.Fatal("the player plays on after its source is mixed") } if got, want := p.UnplayedSize(), 960*bytesPerFrame; got != want { t.Fatalf("as the source ends: UnplayedSize() = %d; want %d", got, want) @@ -140,6 +161,10 @@ func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { } func TestUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { + synctest.Test(t, testUnplayedSizeForgetsWhatIsSentBeforeSeek) +} + +func testUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { const delay = 1000 m := newDelayedMux(t, delay, true) p := newBufferedPlayer(t, m, 4800) diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index b4ed319..5d45664 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -533,8 +533,7 @@ Stream::Stream() = default; // kDelayEvery is how often LoopRead measures the delay. constexpr std::chrono::milliseconds kDelayEvery{100}; -// ForgetDelayLocked forgets the delay measured, as the stream it was measured -// on is dropped, paused or replaced. +// ForgetDelayLocked forgets the delay measured. void Stream::ForgetDelayLocked() { std::lock_guard lock{delay_mutex_}; delay_gen_++; @@ -559,7 +558,8 @@ void Stream::MeasureDelay() { // The stream is asked outside mutex_, as asking it can wait on the device. // Only this thread writes to fifo_, and a callback reads from it as the // stream takes frames, so a measurement is kept only if no callback ran - // meanwhile. + // meanwhile. A callback is short and rare next to a measurement, so a few + // tries are enough, and the next measurement comes kDelayEvery later. for (int i = 0; i < 3; i++) { int64_t read = fifo_->getReadCounter(); double ms; From 8655691df1397fb6e20cb8d7abb71caee5b5e96c Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 14 Oct 2026 08:15:03 +0200 Subject: [PATCH 06/12] oto: have the driver report when a frame is heard, and keep what is sent while unknown The driver now hands each measurement to the mux with Mux.SetHeard: which frame of the mix is heard at what time. The mux works out the frame heard now from the clock, so nothing is read at two moments, and it no longer calls into the driver. On Android, LoopRead reports every 100 ms, under delay_mutex_, and forgetting the measurement calls Mux.ClearHeard. A report holds for a second, and one that puts a frame more than 2 seconds away is taken as unknown. While the delay is unknown, as during Suspend, a player keeps the spans it sent and leaves them out of UnplayedSize, so they count again once the driver reports. TestUnplayedSize no longer compares UnplayedSize with BufferedSize from two calls, and got/want checks use t.Errorf. Co-Authored-By: Claude Opus 5.5 --- driver_android.go | 3 +- driver_console.go | 4 +- driver_darwin.go | 7 +- driver_js.go | 5 +- driver_unix.go | 6 +- driver_windows.go | 6 +- internal/mux/mux.go | 72 ++++++++++---- internal/mux/unplayed_test.go | 159 +++++++++++++++++++++--------- internal/oboe/binding_android.cpp | 50 +++------- internal/oboe/binding_android.go | 36 ++++--- internal/oboe/binding_android.h | 1 - oto_test.go | 7 +- 12 files changed, 226 insertions(+), 130 deletions(-) diff --git a/driver_android.go b/driver_android.go index 6402e5c..6360a35 100644 --- a/driver_android.go +++ b/driver_android.go @@ -35,7 +35,6 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c := &context{ mux: mux.New(sampleRate, channelCount, format), } - c.mux.SetDelayFunc(oboe.Delay) go func() { // The ready channel must close even if Play fails, or callers waiting on it block forever. defer close(ready) @@ -43,7 +42,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c.m.Lock() defer c.m.Unlock() - if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.err.Join, bufferSizeInBytes); err != nil { + if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.mux.SetHeard, c.mux.ClearHeard, c.err.Join, bufferSizeInBytes); err != nil { c.err.Join(err) } }() diff --git a/driver_console.go b/driver_console.go index 449ff15..1c54b81 100644 --- a/driver_console.go +++ b/driver_console.go @@ -53,8 +53,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c := &context{ mux: mux.New(sampleRate, channelCount, format), } - // TODO: Report the delay with c.mux.SetDelayFunc, where the console's audio - // API gives it. + // TODO: Report when the frames are heard with c.mux.SetHeard, where the + // console's audio API gives it. theContext = c C.oto_OpenAudioProxy(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)) diff --git a/driver_darwin.go b/driver_darwin.go index 11f8d6e..ec83219 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -160,9 +160,10 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI channelCount: channelCount, oneBufferSizeInBytes: oneBufferSizeInBytes, } - // TODO: Report the delay with c.mux.SetDelayFunc: the frames enqueued less - // the queue's position from AudioQueueGetCurrentTime, plus the device's - // latency, which on iOS AVAudioSession's outputLatency gives. + // TODO: Report when the frames are heard with c.mux.SetHeard, from the delay: + // the frames enqueued less the queue's position from + // AudioQueueGetCurrentTime, plus the device's latency, which on iOS + // AVAudioSession's outputLatency gives. theContext = c if err := initializeAPI(); err != nil { diff --git a/driver_js.go b/driver_js.go index e7ef279..cb3eca6 100644 --- a/driver_js.go +++ b/driver_js.go @@ -50,8 +50,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI audioContext: class.New(options), mux: mux.New(sampleRate, channelCount, format), } - // TODO: Report the delay with d.mux.SetDelayFunc: the AudioContext's - // outputLatency and baseLatency, plus what is scheduled and not yet played. + // TODO: Report when the frames are heard with d.mux.SetHeard: the + // AudioContext's getOutputTimestamp gives the context time of the frame + // heard now, and the frames queued in the worklet are heard after it. if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. diff --git a/driver_unix.go b/driver_unix.go index 82f6f11..25888fa 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -47,9 +47,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI mux: mux.New(sampleRate, channelCount, format), ready: make(chan struct{}), } - // TODO: Report the delay with ctx.mux.SetDelayFunc: from PulseAudio's latency - // query for its stream, and from snd_pcm_delay on ALSA, plus what the driver - // has read and not yet written. + // TODO: Report when the frames are heard with ctx.mux.SetHeard, 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. diff --git a/driver_windows.go b/driver_windows.go index 6c99785..8157c02 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -46,9 +46,9 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI mux: mux.New(sampleRate, channelCount, format), ready: make(chan struct{}), } - // TODO: Report the delay with ctx.mux.SetDelayFunc: 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 heard with ctx.mux.SetHeard, from the + // delay: on WASAPI, the frames written less the position IAudioClock reports; + // on WinMM, the frames written less the position waveOutGetPosition reports. // Initializing drivers might take some time. Do this asynchronously. go func() { diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 3711873..0778720 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -66,16 +66,26 @@ type Mux struct { // mixed counts the samples ReadFloat32s has mixed. mixed atomic.Int64 - // delay is the driver's report of how many of the frames ReadFloat32s has - // mixed are not heard yet, and whether it knows, or nil where the driver - // reports nothing. - delay func() (int64, bool) + // heardMu guards the driver's last report: frame heardFrame of the mix is + // heard at heardAt, reported at reportedAt, while heardKnown is set. + heardMu sync.Mutex + heardKnown bool + heardFrame int64 + heardAt time.Time + reportedAt time.Time } // maxSentSpans is the most spans of the mix a player remembers its data went // into while they may be unheard. const maxSentSpans = 256 +// reportLifetime is how long a report of when a frame is heard holds. +const reportLifetime = time.Second + +// maxReportedDelay is the longest a report can put a frame's being heard after +// the report. +const maxReportedDelay = 2 * time.Second + // New creates a new Mux. func New(sampleRate int, channelCount int, format Format) *Mux { m := &Mux{ @@ -168,25 +178,52 @@ func (m *Mux) removePlayer(player *playerImpl) { delete(m.players, player) } -// SetDelayFunc sets how the driver reports its delay: f returns how many of the -// frames ReadFloat32s has mixed are not heard yet, and whether it knows. It is -// set before the players play. -func (m *Mux) SetDelayFunc(f func() (int64, bool)) { - m.delay = f +// SetHeard reports that frame of the mix is heard at time at, where frame 0 is +// the first frame ReadFloat32s mixed. A driver that reports calls SetHeard at +// least once every reportLifetime while playing. A report holds for +// reportLifetime, and one with at more than maxReportedDelay away is taken as +// unknown. +func (m *Mux) SetHeard(frame int64, at time.Time) { + now := time.Now() + + m.heardMu.Lock() + defer m.heardMu.Unlock() + + if at.Sub(now) > maxReportedDelay { + m.heardKnown = false + return + } + m.heardKnown = true + m.heardFrame = frame + m.heardAt = at + m.reportedAt = now +} + +// ClearHeard forgets the driver's last report. +func (m *Mux) ClearHeard() { + m.heardMu.Lock() + defer m.heardMu.Unlock() + + m.heardKnown = false } // heard returns how many of the samples mixed have been heard, and whether the // driver reports it. func (m *Mux) heard() (int64, bool) { - if m.delay == nil { - return 0, false - } - mixed := m.mixed.Load() - d, ok := m.delay() - if !ok { + now := time.Now() + + m.heardMu.Lock() + known, frame, at, reportedAt := m.heardKnown, m.heardFrame, m.heardAt, m.reportedAt + m.heardMu.Unlock() + + if !known || now.Sub(reportedAt) > reportLifetime { return 0, false } - return mixed - max(d, 0)*int64(m.channelCount), true + // The frames around the one reported are heard at the sample rate. + frame += int64(now.Sub(at)) * int64(m.sampleRate) / int64(time.Second) + // No more than is mixed has been heard, as when the device has run dry + // since the report. + return min(frame*int64(m.channelCount), m.mixed.Load()), true } // Stop stops the Mux from reading the players' sources. @@ -550,7 +587,8 @@ func (p *playerImpl) UnplayedSize() int { n := p.buffered() heard, ok := p.mux.heard() if !ok { - p.sent = p.sent[:0] + // What is sent stays, as it may be heard once the driver reports again, + // as after Resume. return n } p.forgetHeard(heard) diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go index 6dbb274..ab02e4e 100644 --- a/internal/mux/unplayed_test.go +++ b/internal/mux/unplayed_test.go @@ -26,13 +26,12 @@ import ( // The tests play 48 kHz stereo float32: 8 bytes a frame. const bytesPerFrame = 8 -// newDelayedMux returns a mux whose driver reports delay frames as not heard -// yet, where known is true. +// newMux returns a mux for the tests. // // The tests run in synctest bubbles, and wait for the mux's loop to fill the // players' buffers with synctest.Wait, so their results depend on no -// machine's scheduler. -func newDelayedMux(t *testing.T, delay int64, known bool) *mux.Mux { +// machine's scheduler, and they move the clock the mux reads with time.Sleep. +func newMux(t *testing.T) *mux.Mux { t.Helper() m := mux.New(48000, 2, mux.FormatFloat32LE) @@ -43,11 +42,6 @@ func newDelayedMux(t *testing.T, delay int64, known bool) *mux.Mux { m.Stop() time.Sleep(time.Second) }) - if known { - m.SetDelayFunc(func() (int64, bool) { - return delay, true - }) - } return m } @@ -71,12 +65,28 @@ func readFrames(m *mux.Mux, frames int) { m.ReadFloat32s(make([]float32, frames*2)) } -func TestUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { - synctest.Test(t, testUnplayedSizeIsBufferedSizeWithoutADelay) +// frameTime is how long frames frames take to play. +func frameTime(frames int) time.Duration { + return time.Duration(frames) * time.Second / 48000 +} + +// The tests' driver reports that frame 1,440 of the mix is heard 960 frames, +// 20 ms, from now. +const ( + reportedFrame = 1440 + delay = 960 +) + +func reportHeard(m *mux.Mux) { + m.SetHeard(reportedFrame, time.Now().Add(frameTime(delay))) } -func testUnplayedSizeIsBufferedSizeWithoutADelay(t *testing.T) { - m := newDelayedMux(t, 0, false) +func TestUnplayedSizeIsBufferedSizeWithoutAReport(t *testing.T) { + synctest.Test(t, testUnplayedSizeIsBufferedSizeWithoutAReport) +} + +func testUnplayedSizeIsBufferedSizeWithoutAReport(t *testing.T) { + m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, 480) if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { @@ -89,25 +99,25 @@ func TestUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { } func testUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { - const delay = 1000 - m := newDelayedMux(t, delay, true) + m := newMux(t) p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportHeard(m) - // Right after Play, nothing is sent yet. - if got, want := p.UnplayedSize(), 4800*bytesPerFrame; got != want { - t.Fatalf("before any read: UnplayedSize() = %d; want %d", got, want) + // The delay's worth of what is sent is not heard yet. + if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { + t.Errorf("at the report: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) } - // While less than the delay is mixed, none of it is heard: the whole - // source is unplayed. - readFrames(m, 480) - readFrames(m, 480) - if got, want := p.UnplayedSize(), 4800*bytesPerFrame; got != want { - t.Fatalf("after 960 frames: UnplayedSize() = %d; want %d", got, want) + // It is heard as the clock moves on. + time.Sleep(frameTime(400)) + if got, want := p.UnplayedSize(), p.BufferedSize()+(delay-400)*bytesPerFrame; got != want { + t.Errorf("400 frames after the report: UnplayedSize() = %d; want %d", got, want) } - // Then the delay's worth of what is sent stays unheard. - readFrames(m, 480) - if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { - t.Errorf("after 1,440 frames: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) + // No more than is mixed is heard, however long the device goes without a + // read. + time.Sleep(frameTime(800)) + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("1,200 frames after the report: UnplayedSize() = %d; want BufferedSize(), %d", got, want) } } @@ -116,45 +126,100 @@ func TestUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { } func testUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { - const delay = 1000 - m := newDelayedMux(t, delay, true) + m := newMux(t) p := newBufferedPlayer(t, m, 4800) - readFrames(m, 1440) + readFrames(m, reportedFrame) + reportHeard(m) p.Pause() // What was sent before Pause is still to be heard, and is heard as the // device plays on. if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { - t.Fatalf("right after Pause: UnplayedSize() = %d; want %d", got, want) + t.Errorf("right after Pause: UnplayedSize() = %d; want %d", got, want) } - readFrames(m, 400) - if got, want := p.UnplayedSize(), p.BufferedSize()+(delay-400)*bytesPerFrame; got != want { - t.Fatalf("400 frames after Pause: UnplayedSize() = %d; want %d", got, want) - } - readFrames(m, 600) + time.Sleep(frameTime(delay)) if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { t.Errorf("a delay after Pause: UnplayedSize() = %d; want BufferedSize(), %d", got, want) } } +func TestUnplayedSizeKeepsWhatIsSentWhileUnreported(t *testing.T) { + synctest.Test(t, testUnplayedSizeKeepsWhatIsSentWhileUnreported) +} + +func testUnplayedSizeKeepsWhatIsSentWhileUnreported(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportHeard(m) + + // As when the device is suspended, and resumed. + m.ClearHeard() + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("after ClearHeard: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } + reportHeard(m) + if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { + t.Errorf("reported again: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) + } +} + +func TestUnplayedSizeForgetsAnOldReport(t *testing.T) { + synctest.Test(t, testUnplayedSizeForgetsAnOldReport) +} + +func testUnplayedSizeForgetsAnOldReport(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + // The last frame mixed is heard in 1.5 seconds. + m.SetHeard(reportedFrame, time.Now().Add(1500*time.Millisecond)) + + time.Sleep(time.Second) + if got, want := p.UnplayedSize(), p.BufferedSize()+reportedFrame*bytesPerFrame; got != want { + t.Errorf("a second after the report: UnplayedSize() = %d; want BufferedSize() and all that is sent, %d", got, want) + } + time.Sleep(time.Millisecond) + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("over a second after the report: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} + +func TestUnplayedSizeIgnoresAFarReport(t *testing.T) { + synctest.Test(t, testUnplayedSizeIgnoresAFarReport) +} + +func testUnplayedSizeIgnoresAFarReport(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportHeard(m) + + // A report puts the frame over 2 seconds away. + m.SetHeard(reportedFrame, time.Now().Add(2*time.Second+time.Millisecond)) + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("after the far report: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} + func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { synctest.Test(t, testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard) } func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { - const delay = 1000 - m := newDelayedMux(t, delay, true) - p := newBufferedPlayer(t, m, 960) - readFrames(m, 960) + m := newMux(t) + p := newBufferedPlayer(t, m, reportedFrame) + readFrames(m, reportedFrame) // The mux finds the source's end on its next read from it. synctest.Wait() if p.IsPlaying() { t.Fatal("the player plays on after its source is mixed") } - if got, want := p.UnplayedSize(), 960*bytesPerFrame; got != want { - t.Fatalf("as the source ends: UnplayedSize() = %d; want %d", got, want) + reportHeard(m) + if got, want := p.UnplayedSize(), delay*bytesPerFrame; got != want { + t.Errorf("as the source ends: UnplayedSize() = %d; want %d", got, want) } - readFrames(m, 1000) + time.Sleep(frameTime(delay)) if got := p.UnplayedSize(); got != 0 { t.Errorf("a delay after the source ends: UnplayedSize() = %d; want 0", got) } @@ -165,10 +230,10 @@ func TestUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { } func testUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { - const delay = 1000 - m := newDelayedMux(t, delay, true) + m := newMux(t) p := newBufferedPlayer(t, m, 4800) - readFrames(m, 1440) + readFrames(m, reportedFrame) + reportHeard(m) if _, err := p.Seek(0, 0); err != nil { t.Fatal(err) } diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 5d45664..2866303 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -131,7 +131,6 @@ class Stream : public oboe::AudioStreamDataCallback, const char *Resume(); const char *Close(); const char *AppendBuffer(float *buf, size_t len); - int64_t Delay(); oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream, void *audio_data, @@ -219,16 +218,13 @@ class Stream : public oboe::AudioStreamDataCallback, std::atomic min_wait_us_{1000}; std::atomic max_callback_{0}; - // The delay. Every kDelayEvery, LoopRead measures when the frame written to - // fifo_ next will be heard: delay_written_ is the write counter then, and - // delay_heard_at_ the time, while delay_known_ is set. delay_gen_ counts the - // streams dropped, paused and opened, so that a measurement of a stream that - // changed meanwhile is dropped. delay_mutex_ guards these, and is taken after - // mutex_ where both are. + // Every kDelayEvery, LoopRead measures when the frame written to fifo_ next + // will be heard, and reports it to Go. delay_gen_ counts the streams + // dropped, paused and opened, so that a measurement of a stream that changed + // meanwhile is dropped. delay_mutex_ guards it, and is held while reporting + // to Go, so that reports reach Go in order. It is taken after mutex_ where + // both are. std::mutex delay_mutex_; - bool delay_known_ = false; - int64_t delay_written_ = 0; - std::chrono::steady_clock::time_point delay_heard_at_; int delay_gen_ = 0; // read_thread_ runs LoopRead, which reads from Go into fifo_. @@ -533,14 +529,15 @@ Stream::Stream() = default; // kDelayEvery is how often LoopRead measures the delay. constexpr std::chrono::milliseconds kDelayEvery{100}; -// ForgetDelayLocked forgets the delay measured. +// ForgetDelayLocked forgets the delay measured, in Go too. void Stream::ForgetDelayLocked() { std::lock_guard lock{delay_mutex_}; delay_gen_++; - delay_known_ = false; + oto_oboe_forgetHeard(); } -// MeasureDelay measures when the frame written to fifo_ next will be heard. +// MeasureDelay measures when the frame written to fifo_ next will be heard, and +// reports it to Go. void Stream::MeasureDelay() { std::shared_ptr stream; int gen; @@ -587,29 +584,16 @@ void Stream::MeasureDelay() { if (delay_gen_ != gen) { return; } - delay_known_ = true; - delay_written_ = written; - delay_heard_at_ = heard_at; + // fifo_ is written only with what is read from Go, so its write counter + // counts the frames read from Go. + oto_oboe_setHeard(written, + std::chrono::duration_cast( + heard_at - std::chrono::steady_clock::now()) + .count()); return; } } -// Delay returns how many of the frames read from Go are not heard yet, or -1 -// while the stream has not been measured. -int64_t Stream::Delay() { - std::lock_guard lock{delay_mutex_}; - if (!delay_known_) { - return -1; - } - // The frame written next at the measurement is heard at delay_heard_at_, and - // the frames written since after it. - std::chrono::duration until = - delay_heard_at_ - std::chrono::steady_clock::now(); - int64_t frames = fifo_->getWriteCounter() - delay_written_ + - std::llround(until.count() * sample_rate_); - return std::max(frames, 0); -} - void Stream::LoopRead() { auto measured = std::chrono::steady_clock::now(); for (;;) { @@ -683,6 +667,4 @@ const char *oto_oboe_Suspend() { return Stream::GetInstance().Pause(); } const char *oto_oboe_Resume() { return Stream::GetInstance().Resume(); } -int64_t oto_oboe_Delay() { return Stream::GetInstance().Delay(); } - } // extern "C" diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 9879db7..1a4a31a 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -22,24 +22,31 @@ import "C" import ( "fmt" + "time" "unsafe" ) var ( - theReadFunc func(buf []float32) - theErrorFunc func(err error) + theReadFunc func(buf []float32) + theHeardFunc func(frame int64, at time.Time) + theForgetFunc func() + theErrorFunc func(err error) ) // Play starts playing. Playing starts as soon as an audio device is available, -// which can be after Play returns. errorFunc is called when playing stops for a -// reason that cannot be recovered from, which can happen at any time after Play -// returns. -func Play(sampleRate int, channelCount int, readFunc func(buf []float32), errorFunc func(err error), bufferSizeInBytes int) error { +// which can be after Play returns. heardFunc is called about every 100 ms while +// playing with when a frame is heard, where frame 0 is the first frame read with +// readFunc. forgetFunc is called when the last of those no longer holds. +// errorFunc is called when playing stops for a reason that cannot be recovered +// from, which can happen at any time after Play returns. +func Play(sampleRate int, channelCount int, readFunc func(buf []float32), heardFunc func(frame int64, at time.Time), forgetFunc func(), errorFunc func(err error), bufferSizeInBytes int) error { // Play can invoke the callbacks. Set the callbacks before Play. // // Reads are paced: after the device takes a large burst, reads made as // fast as there is room would outrun the players' buffers. theReadFunc = newPacer(readFunc, sampleRate, channelCount).Read + theHeardFunc = heardFunc + theForgetFunc = forgetFunc theErrorFunc = errorFunc if msg := C.oto_oboe_Play(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)); msg != nil { return fmt.Errorf("oboe: Play failed: %s", C.GoString(msg)) @@ -63,18 +70,21 @@ func Resume() error { return nil } -// Delay returns how many of the frames read with the read function are not -// heard yet, and whether the device reports it. -func Delay() (int64, bool) { - n := int64(C.oto_oboe_Delay()) - return n, n >= 0 -} - //export oto_oboe_read func oto_oboe_read(buf *C.float, len C.size_t) { theReadFunc(unsafe.Slice((*float32)(unsafe.Pointer(buf)), len)) } +//export oto_oboe_setHeard +func oto_oboe_setHeard(frame C.int64_t, inNanoseconds C.int64_t) { + theHeardFunc(int64(frame), time.Now().Add(time.Duration(inNanoseconds))) +} + +//export oto_oboe_forgetHeard +func oto_oboe_forgetHeard() { + theForgetFunc() +} + //export oto_oboe_error func oto_oboe_error(msg *C.char) { theErrorFunc(fmt.Errorf("oboe: %s", C.GoString(msg))) diff --git a/internal/oboe/binding_android.h b/internal/oboe/binding_android.h index f2cbf6e..334ce5d 100644 --- a/internal/oboe/binding_android.h +++ b/internal/oboe/binding_android.h @@ -27,7 +27,6 @@ const char *oto_oboe_Play(int sample_rate, int channel_num, int buffer_size_in_bytes); const char *oto_oboe_Suspend(); const char *oto_oboe_Resume(); -int64_t oto_oboe_Delay(); #ifdef __cplusplus } diff --git a/oto_test.go b/oto_test.go index 7d6bcd3..a905ffe 100644 --- a/oto_test.go +++ b/oto_test.go @@ -52,13 +52,14 @@ func TestUnplayedSize(t *testing.T) { p := theContext.NewPlayer(bytes.NewReader(make([]byte, 4800*8))) p.Play() for p.IsPlaying() { - if u, b := p.UnplayedSize(), p.BufferedSize(); u < b { - t.Fatalf("UnplayedSize() = %d, less than BufferedSize(), %d", u, b) + if u := p.UnplayedSize(); u < 0 { + t.Errorf("UnplayedSize() = %d while playing; want 0 or more", u) + break } time.Sleep(time.Millisecond) } if u := p.UnplayedSize(); u < 0 { - t.Fatalf("UnplayedSize() = %d after the source ends; want 0 or more", u) + t.Errorf("UnplayedSize() = %d after the source ends; want 0 or more", u) } } From 3d5e24e967987d6aa38163205aa11df6d4df400f Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 14 Oct 2026 08:39:18 +0200 Subject: [PATCH 07/12] oto: take a report of a frame heard long ago as unknown, and tidy comments Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 3 ++- internal/mux/mux.go | 6 +++--- internal/mux/unplayed_test.go | 2 +- internal/oboe/binding_android.cpp | 11 +++++++---- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/driver_js.go b/driver_js.go index cb3eca6..9800bfe 100644 --- a/driver_js.go +++ b/driver_js.go @@ -52,7 +52,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI } // TODO: Report when the frames are heard with d.mux.SetHeard: the // AudioContext's getOutputTimestamp gives the context time of the frame - // heard now, and the frames queued in the worklet are heard after it. + // heard now, and the frames queued in the worklet or the script processor + // are heard after it. if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 0778720..0fdd694 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -181,15 +181,15 @@ func (m *Mux) removePlayer(player *playerImpl) { // SetHeard reports that frame of the mix is heard at time at, where frame 0 is // the first frame ReadFloat32s mixed. A driver that reports calls SetHeard at // least once every reportLifetime while playing. A report holds for -// reportLifetime, and one with at more than maxReportedDelay away is taken as -// unknown. +// reportLifetime, and one with at more than maxReportedDelay after the report, +// or more than reportLifetime before it, is taken as unknown. func (m *Mux) SetHeard(frame int64, at time.Time) { now := time.Now() m.heardMu.Lock() defer m.heardMu.Unlock() - if at.Sub(now) > maxReportedDelay { + if at.Sub(now) > maxReportedDelay || now.Sub(at) > reportLifetime { m.heardKnown = false return } diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go index ab02e4e..3b92b91 100644 --- a/internal/mux/unplayed_test.go +++ b/internal/mux/unplayed_test.go @@ -172,7 +172,7 @@ func testUnplayedSizeForgetsAnOldReport(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - // The last frame mixed is heard in 1.5 seconds. + // Frame 1,440, the next one mixed, is heard in 1.5 seconds. m.SetHeard(reportedFrame, time.Now().Add(1500*time.Millisecond)) time.Sleep(time.Second) diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 2866303..096a3aa 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -221,9 +221,8 @@ class Stream : public oboe::AudioStreamDataCallback, // Every kDelayEvery, LoopRead measures when the frame written to fifo_ next // will be heard, and reports it to Go. delay_gen_ counts the streams // dropped, paused and opened, so that a measurement of a stream that changed - // meanwhile is dropped. delay_mutex_ guards it, and is held while reporting - // to Go, so that reports reach Go in order. It is taken after mutex_ where - // both are. + // meanwhile is dropped. delay_mutex_ guards it, and is taken after mutex_ + // where both are. std::mutex delay_mutex_; int delay_gen_ = 0; @@ -533,6 +532,9 @@ constexpr std::chrono::milliseconds kDelayEvery{100}; void Stream::ForgetDelayLocked() { std::lock_guard lock{delay_mutex_}; delay_gen_++; + // Go is told under delay_mutex_, so that no report of the stream measured + // before lands after this. The Go side takes only a lock of its own, which + // calls nothing while held. oto_oboe_forgetHeard(); } @@ -585,7 +587,8 @@ void Stream::MeasureDelay() { return; } // fifo_ is written only with what is read from Go, so its write counter - // counts the frames read from Go. + // counts the frames read from Go. Go is told under delay_mutex_, so that + // reports and forgetting reach it in order. oto_oboe_setHeard(written, std::chrono::duration_cast( heard_at - std::chrono::steady_clock::now()) From da8252d0cfcc209f89956018b9a0fd67a5a83f56 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 14 Oct 2026 09:28:07 +0200 Subject: [PATCH 08/12] oto: name resets and discards as the rest of oto does Co-Authored-By: Claude Opus 5.5 --- internal/mux/mux.go | 10 +++++----- internal/mux/unplayed_test.go | 12 ++++++------ internal/oboe/binding_android.cpp | 18 +++++++++--------- internal/oboe/binding_android.go | 20 ++++++++++---------- player.go | 2 +- 5 files changed, 31 insertions(+), 31 deletions(-) diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 0fdd694..1022d0c 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -199,7 +199,7 @@ func (m *Mux) SetHeard(frame int64, at time.Time) { m.reportedAt = now } -// ClearHeard forgets the driver's last report. +// ClearHeard clears the driver's last report. func (m *Mux) ClearHeard() { m.heardMu.Lock() defer m.heardMu.Unlock() @@ -591,17 +591,17 @@ func (p *playerImpl) UnplayedSize() int { // as after Resume. return n } - p.forgetHeard(heard) + p.dropHeard(heard) for _, s := range p.sent { n += int(s.end-max(s.start, heard)) * p.mux.format.ByteLength() } return n } -// forgetHeard drops the spans sent that end by sample heard of the mix. +// dropHeard drops the spans sent that end by sample heard of the mix. // -// When forgetHeard is called, the mutex m must be locked. -func (p *playerImpl) forgetHeard(heard int64) { +// When dropHeard is called, the mutex m must be locked. +func (p *playerImpl) dropHeard(heard int64) { i := 0 for i < len(p.sent) && p.sent[i].end <= heard { i++ diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go index 3b92b91..f01d24e 100644 --- a/internal/mux/unplayed_test.go +++ b/internal/mux/unplayed_test.go @@ -164,11 +164,11 @@ func testUnplayedSizeKeepsWhatIsSentWhileUnreported(t *testing.T) { } } -func TestUnplayedSizeForgetsAnOldReport(t *testing.T) { - synctest.Test(t, testUnplayedSizeForgetsAnOldReport) +func TestUnplayedSizeIgnoresAnOldReport(t *testing.T) { + synctest.Test(t, testUnplayedSizeIgnoresAnOldReport) } -func testUnplayedSizeForgetsAnOldReport(t *testing.T) { +func testUnplayedSizeIgnoresAnOldReport(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) @@ -225,11 +225,11 @@ func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { } } -func TestUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { - synctest.Test(t, testUnplayedSizeForgetsWhatIsSentBeforeSeek) +func TestUnplayedSizeDiscardsWhatIsSentBeforeSeek(t *testing.T) { + synctest.Test(t, testUnplayedSizeDiscardsWhatIsSentBeforeSeek) } -func testUnplayedSizeForgetsWhatIsSentBeforeSeek(t *testing.T) { +func testUnplayedSizeDiscardsWhatIsSentBeforeSeek(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 096a3aa..a23dd1e 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -146,7 +146,7 @@ class Stream : public oboe::AudioStreamDataCallback, // The Locked functions must be called with mutex_ held. Status OpenLocked(); void CloseLocked(); - void ForgetDelayLocked(); + void ResetDelayLocked(); void MeasureDelay(); void PrepareBuffersLocked(); void ConfigureRefillLocked(); @@ -270,7 +270,7 @@ Status Stream::OpenLocked() { // running stream, and its result is of no interest: the stream is not used // again either way. void Stream::CloseLocked() { - ForgetDelayLocked(); + ResetDelayLocked(); if (!stream_) { return; } @@ -429,7 +429,7 @@ void Stream::onErrorAfterClose(oboe::AudioStream *oboe_stream, } // Oboe stopped and closed the stream before calling this, so the only way // to keep playing is to open a new one. - ForgetDelayLocked(); + ResetDelayLocked(); stream_.reset(); state_ = State::kStopped; // A stream that goes away while suspended stays closed until Resume, so @@ -453,7 +453,7 @@ void Stream::onErrorAfterClose(oboe::AudioStream *oboe_stream, const char *Stream::Pause() { std::lock_guard lock{mutex_}; suspended_ = true; - ForgetDelayLocked(); + ResetDelayLocked(); if (state_ == State::kStartDeferred) { // Nothing may start playing while the caller wants silence. Resume attempts // it again. @@ -504,7 +504,7 @@ const char *Stream::Close() { if (oboe::Result result = stream_->close(); result != oboe::Result::OK) { return oboe::convertToText(result); } - ForgetDelayLocked(); + ResetDelayLocked(); stream_.reset(); return nullptr; } @@ -528,14 +528,14 @@ Stream::Stream() = default; // kDelayEvery is how often LoopRead measures the delay. constexpr std::chrono::milliseconds kDelayEvery{100}; -// ForgetDelayLocked forgets the delay measured, in Go too. -void Stream::ForgetDelayLocked() { +// ResetDelayLocked discards the delay measured, in Go too. +void Stream::ResetDelayLocked() { std::lock_guard lock{delay_mutex_}; delay_gen_++; // Go is told under delay_mutex_, so that no report of the stream measured // before lands after this. The Go side takes only a lock of its own, which // calls nothing while held. - oto_oboe_forgetHeard(); + oto_oboe_clearHeard(); } // MeasureDelay measures when the frame written to fifo_ next will be heard, and @@ -588,7 +588,7 @@ void Stream::MeasureDelay() { } // fifo_ is written only with what is read from Go, so its write counter // counts the frames read from Go. Go is told under delay_mutex_, so that - // reports and forgetting reach it in order. + // reports and resets reach it in order. oto_oboe_setHeard(written, std::chrono::duration_cast( heard_at - std::chrono::steady_clock::now()) diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 1a4a31a..29ec84b 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -27,26 +27,26 @@ import ( ) var ( - theReadFunc func(buf []float32) - theHeardFunc func(frame int64, at time.Time) - theForgetFunc func() - theErrorFunc func(err error) + theReadFunc func(buf []float32) + theHeardFunc func(frame int64, at time.Time) + theClearFunc func() + theErrorFunc func(err error) ) // Play starts playing. Playing starts as soon as an audio device is available, // which can be after Play returns. heardFunc is called about every 100 ms while // playing with when a frame is heard, where frame 0 is the first frame read with -// readFunc. forgetFunc is called when the last of those no longer holds. +// readFunc. clearFunc is called when the last of those no longer holds. // errorFunc is called when playing stops for a reason that cannot be recovered // from, which can happen at any time after Play returns. -func Play(sampleRate int, channelCount int, readFunc func(buf []float32), heardFunc func(frame int64, at time.Time), forgetFunc func(), errorFunc func(err error), bufferSizeInBytes int) error { +func Play(sampleRate int, channelCount int, readFunc func(buf []float32), heardFunc func(frame int64, at time.Time), clearFunc func(), errorFunc func(err error), bufferSizeInBytes int) error { // Play can invoke the callbacks. Set the callbacks before Play. // // Reads are paced: after the device takes a large burst, reads made as // fast as there is room would outrun the players' buffers. theReadFunc = newPacer(readFunc, sampleRate, channelCount).Read theHeardFunc = heardFunc - theForgetFunc = forgetFunc + theClearFunc = clearFunc theErrorFunc = errorFunc if msg := C.oto_oboe_Play(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)); msg != nil { return fmt.Errorf("oboe: Play failed: %s", C.GoString(msg)) @@ -80,9 +80,9 @@ func oto_oboe_setHeard(frame C.int64_t, inNanoseconds C.int64_t) { theHeardFunc(int64(frame), time.Now().Add(time.Duration(inNanoseconds))) } -//export oto_oboe_forgetHeard -func oto_oboe_forgetHeard() { - theForgetFunc() +//export oto_oboe_clearHeard +func oto_oboe_clearHeard() { + theClearFunc() } //export oto_oboe_error diff --git a/player.go b/player.go index d730233..2f9a516 100644 --- a/player.go +++ b/player.go @@ -82,7 +82,7 @@ func (p *Player) BufferedSize() int { // UnplayedSize returns the byte size of the data read from the source that is not heard yet: the buffered data, and // the data sent to the audio hardware that it has not played yet, also after Pause and after the end of the source. // Where the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as -// BufferedSize. Seek and Reset forget the data already sent. +// BufferedSize. Seek and Reset discard the data already sent. // // So the part of the source being heard now is the bytes read from it less UnplayedSize. func (p *Player) UnplayedSize() int { From 6692dc664f77c0a3615ac98903dda3106b147216 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Thu, 15 Oct 2026 22:15:32 +0200 Subject: [PATCH 09/12] internal/oboe: tell Go of a reset only after Play Suspend before Play called a Go function that Play sets, and panicked. The test is Hajime's, from his review. Co-authored-by: Hajime Hoshi Co-Authored-By: Claude Opus 5.5 --- internal/oboe/binding_android.cpp | 7 +++++-- internal/oboe/suspend_android_test.go | 29 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 internal/oboe/suspend_android_test.go diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index a23dd1e..432fdab 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -534,8 +534,11 @@ void Stream::ResetDelayLocked() { delay_gen_++; // Go is told under delay_mutex_, so that no report of the stream measured // before lands after this. The Go side takes only a lock of its own, which - // calls nothing while held. - oto_oboe_clearHeard(); + // calls nothing while held. Before Play, nothing is reported, and Go has no + // function to call. + if (play_called_) { + oto_oboe_clearHeard(); + } } // MeasureDelay measures when the frame written to fifo_ next will be heard, and diff --git a/internal/oboe/suspend_android_test.go b/internal/oboe/suspend_android_test.go new file mode 100644 index 0000000..7291b43 --- /dev/null +++ b/internal/oboe/suspend_android_test.go @@ -0,0 +1,29 @@ +// Copyright 2026 The Oto Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package oboe_test + +import ( + "testing" + + "github.com/ebitengine/oto/v3/internal/oboe" +) + +// Ebitengine calls Suspend on lifecycle events as soon as NewContext returns, +// which can be before the context's goroutine calls Play. +func TestSuspendBeforePlay(t *testing.T) { + if err := oboe.Suspend(); err != nil { + t.Errorf("Suspend before Play: %v", err) + } +} From 64c8b2fc09bf9a3490e6568ed9d62fe66233973a Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Mon, 2 Nov 2026 14:43:15 +0100 Subject: [PATCH 10/12] oto: trim UnplayedSize's doc and drop its smoke test The doc's last sentence told callers how to use the value, not what it is. TestUnplayedSize only checked the value is not negative; the tests in internal/mux cover the behavior. Co-Authored-By: Claude Opus 5.5 --- oto_test.go | 15 --------------- player.go | 2 -- 2 files changed, 17 deletions(-) diff --git a/oto_test.go b/oto_test.go index a905ffe..fac52f4 100644 --- a/oto_test.go +++ b/oto_test.go @@ -48,21 +48,6 @@ func TestEmptyPlayer(t *testing.T) { } } -func TestUnplayedSize(t *testing.T) { - p := theContext.NewPlayer(bytes.NewReader(make([]byte, 4800*8))) - p.Play() - for p.IsPlaying() { - if u := p.UnplayedSize(); u < 0 { - t.Errorf("UnplayedSize() = %d while playing; want 0 or more", u) - break - } - time.Sleep(time.Millisecond) - } - if u := p.UnplayedSize(); u < 0 { - t.Errorf("UnplayedSize() = %d after the source ends; want 0 or more", u) - } -} - // Issue #258 func TestSetBufferSize(t *testing.T) { for range 10 { diff --git a/player.go b/player.go index 2f9a516..6163a41 100644 --- a/player.go +++ b/player.go @@ -83,8 +83,6 @@ func (p *Player) BufferedSize() int { // the data sent to the audio hardware that it has not played yet, also after Pause and after the end of the source. // Where the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as // BufferedSize. Seek and Reset discard the data already sent. -// -// So the part of the source being heard now is the bytes read from it less UnplayedSize. func (p *Player) UnplayedSize() int { return p.player.UnplayedSize() } From 7c0329b8a6ff8ad6b1e71d362f0ba74e08225168 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Tue, 3 Nov 2026 20:58:25 +0100 Subject: [PATCH 11/12] oto: take the review's wording for three doc comments UnplayedSize's doc says "while" in place of "where", as the report can also be cleared for a time, and says data sent before Seek or Reset still plays but is not counted. Play's doc drops the 100 ms, which is not guaranteed. maxReportedDelay's doc reads more plainly. Co-Authored-By: Claude Opus 5.5 --- internal/mux/mux.go | 4 ++-- internal/oboe/binding_android.go | 4 ++-- player.go | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 1022d0c..49e34fb 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -82,8 +82,8 @@ const maxSentSpans = 256 // reportLifetime is how long a report of when a frame is heard holds. const reportLifetime = time.Second -// maxReportedDelay is the longest a report can put a frame's being heard after -// the report. +// maxReportedDelay is the furthest after a report that the frame it reports +// can be heard. const maxReportedDelay = 2 * time.Second // New creates a new Mux. diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 29ec84b..9e49599 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -34,8 +34,8 @@ var ( ) // Play starts playing. Playing starts as soon as an audio device is available, -// which can be after Play returns. heardFunc is called about every 100 ms while -// playing with when a frame is heard, where frame 0 is the first frame read with +// which can be after Play returns. heardFunc is called while playing with a +// frame and when it is heard, where frame 0 is the first frame read with // readFunc. clearFunc is called when the last of those no longer holds. // errorFunc is called when playing stops for a reason that cannot be recovered // from, which can happen at any time after Play returns. diff --git a/player.go b/player.go index 6163a41..ce8e651 100644 --- a/player.go +++ b/player.go @@ -81,8 +81,8 @@ func (p *Player) BufferedSize() int { // UnplayedSize returns the byte size of the data read from the source that is not heard yet: the buffered data, and // the data sent to the audio hardware that it has not played yet, also after Pause and after the end of the source. -// Where the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as -// BufferedSize. Seek and Reset discard the data already sent. +// While the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as +// BufferedSize. After Seek or Reset, the data sent before it is not counted. func (p *Player) UnplayedSize() int { return p.player.UnplayedSize() } From bcf89a385284d6b31e3e2c927e4bae2d6cde9a26 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sun, 8 Nov 2026 12:16:30 +0100 Subject: [PATCH 12/12] oto: say "played" throughout for the audio hardware playing Rename the internal "heard" names and comments to "played", to match UnplayedSize: Mux.SetPlayed, ClearPlayed and played, the played... fields and dropPlayed, playedFunc, oto_oboe_setPlayed and oto_oboe_clearPlayed, played_at, reportPlayed and the test names, and the TODOs in the drivers. Three comments used "played" for the earlier moment, when the data leaves the player's buffer. Player.Err's doc now says "sent to the audio hardware", and the two comments on srcErr in internal/mux say "mixed". Take the review's wording for UnplayedSize's doc. Co-Authored-By: Claude Opus 5.5 --- driver_android.go | 2 +- driver_console.go | 2 +- driver_darwin.go | 2 +- driver_js.go | 6 +-- driver_unix.go | 2 +- driver_windows.go | 2 +- internal/mux/mux.go | 84 +++++++++++++++---------------- internal/mux/unplayed_test.go | 50 +++++++++--------- internal/oboe/binding_android.cpp | 16 +++--- internal/oboe/binding_android.go | 26 +++++----- player.go | 10 ++-- 11 files changed, 101 insertions(+), 101 deletions(-) diff --git a/driver_android.go b/driver_android.go index 6360a35..ec5b1a5 100644 --- a/driver_android.go +++ b/driver_android.go @@ -42,7 +42,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c.m.Lock() defer c.m.Unlock() - if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.mux.SetHeard, c.mux.ClearHeard, c.err.Join, bufferSizeInBytes); err != nil { + if err := oboe.Play(sampleRate, channelCount, c.mux.ReadFloat32s, c.mux.SetPlayed, c.mux.ClearPlayed, c.err.Join, bufferSizeInBytes); err != nil { c.err.Join(err) } }() diff --git a/driver_console.go b/driver_console.go index 1c54b81..5eb3320 100644 --- a/driver_console.go +++ b/driver_console.go @@ -53,7 +53,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c := &context{ mux: mux.New(sampleRate, channelCount, format), } - // TODO: Report when the frames are heard with c.mux.SetHeard, where the + // TODO: Report when the frames are played with c.mux.SetPlayed, where the // console's audio API gives it. theContext = c C.oto_OpenAudioProxy(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)) diff --git a/driver_darwin.go b/driver_darwin.go index ec83219..3988140 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -160,7 +160,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI channelCount: channelCount, oneBufferSizeInBytes: oneBufferSizeInBytes, } - // TODO: Report when the frames are heard with c.mux.SetHeard, from the delay: + // TODO: Report when the frames are played with c.mux.SetPlayed, from the delay: // the frames enqueued less the queue's position from // AudioQueueGetCurrentTime, plus the device's latency, which on iOS // AVAudioSession's outputLatency gives. diff --git a/driver_js.go b/driver_js.go index 9800bfe..b0beff6 100644 --- a/driver_js.go +++ b/driver_js.go @@ -50,10 +50,10 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI audioContext: class.New(options), mux: mux.New(sampleRate, channelCount, format), } - // TODO: Report when the frames are heard with d.mux.SetHeard: the + // TODO: Report when the frames are played with d.mux.SetPlayed: the // AudioContext's getOutputTimestamp gives the context time of the frame - // heard now, and the frames queued in the worklet or the script processor - // are heard after it. + // played now, and the frames queued in the worklet or the script processor + // are played after it. if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. diff --git a/driver_unix.go b/driver_unix.go index 25888fa..91eb501 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -47,7 +47,7 @@ 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 heard with ctx.mux.SetHeard, from the + // 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. diff --git a/driver_windows.go b/driver_windows.go index 8157c02..a866c3f 100644 --- a/driver_windows.go +++ b/driver_windows.go @@ -46,7 +46,7 @@ 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 heard with ctx.mux.SetHeard, from the + // 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. diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 49e34fb..0782c67 100644 --- a/internal/mux/mux.go +++ b/internal/mux/mux.go @@ -66,24 +66,24 @@ type Mux struct { // mixed counts the samples ReadFloat32s has mixed. mixed atomic.Int64 - // heardMu guards the driver's last report: frame heardFrame of the mix is - // heard at heardAt, reported at reportedAt, while heardKnown is set. - heardMu sync.Mutex - heardKnown bool - heardFrame int64 - heardAt time.Time - reportedAt time.Time + // playedMu guards the driver's last report: frame playedFrame of the mix is + // played at playedAt, reported at reportedAt, while playedKnown is set. + playedMu sync.Mutex + playedKnown bool + playedFrame int64 + playedAt time.Time + reportedAt time.Time } // maxSentSpans is the most spans of the mix a player remembers its data went -// into while they may be unheard. +// into while they may be unplayed. const maxSentSpans = 256 -// reportLifetime is how long a report of when a frame is heard holds. +// reportLifetime is how long a report of when a frame is played holds. const reportLifetime = time.Second // maxReportedDelay is the furthest after a report that the frame it reports -// can be heard. +// can be played. const maxReportedDelay = 2 * time.Second // New creates a new Mux. @@ -178,50 +178,50 @@ func (m *Mux) removePlayer(player *playerImpl) { delete(m.players, player) } -// SetHeard reports that frame of the mix is heard at time at, where frame 0 is -// the first frame ReadFloat32s mixed. A driver that reports calls SetHeard at +// SetPlayed reports that frame of the mix is played at time at, where frame 0 is +// the first frame ReadFloat32s mixed. A driver that reports calls SetPlayed at // least once every reportLifetime while playing. A report holds for // reportLifetime, and one with at more than maxReportedDelay after the report, // or more than reportLifetime before it, is taken as unknown. -func (m *Mux) SetHeard(frame int64, at time.Time) { +func (m *Mux) SetPlayed(frame int64, at time.Time) { now := time.Now() - m.heardMu.Lock() - defer m.heardMu.Unlock() + m.playedMu.Lock() + defer m.playedMu.Unlock() if at.Sub(now) > maxReportedDelay || now.Sub(at) > reportLifetime { - m.heardKnown = false + m.playedKnown = false return } - m.heardKnown = true - m.heardFrame = frame - m.heardAt = at + m.playedKnown = true + m.playedFrame = frame + m.playedAt = at m.reportedAt = now } -// ClearHeard clears the driver's last report. -func (m *Mux) ClearHeard() { - m.heardMu.Lock() - defer m.heardMu.Unlock() +// ClearPlayed clears the driver's last report. +func (m *Mux) ClearPlayed() { + m.playedMu.Lock() + defer m.playedMu.Unlock() - m.heardKnown = false + m.playedKnown = false } -// heard returns how many of the samples mixed have been heard, and whether the +// played returns how many of the samples mixed have been played, and whether the // driver reports it. -func (m *Mux) heard() (int64, bool) { +func (m *Mux) played() (int64, bool) { now := time.Now() - m.heardMu.Lock() - known, frame, at, reportedAt := m.heardKnown, m.heardFrame, m.heardAt, m.reportedAt - m.heardMu.Unlock() + m.playedMu.Lock() + known, frame, at, reportedAt := m.playedKnown, m.playedFrame, m.playedAt, m.reportedAt + m.playedMu.Unlock() if !known || now.Sub(reportedAt) > reportLifetime { return 0, false } - // The frames around the one reported are heard at the sample rate. + // The frames around the one reported are played at the sample rate. frame += int64(now.Sub(at)) * int64(m.sampleRate) / int64(time.Second) - // No more than is mixed has been heard, as when the device has run dry + // No more than is mixed has been played, as when the device has run dry // since the report. return min(frame*int64(m.channelCount), m.mixed.Load()), true } @@ -298,7 +298,7 @@ type playerImpl struct { err error // srcErr is an error from the source that is not reported by err yet. - // It is moved to err after the data read before it is played or discarded. + // It is moved to err after the data read before it is mixed or discarded. srcErr error // reading reports whether a read from the source is in flight. @@ -311,7 +311,7 @@ type playerImpl struct { srcGen int // sent holds the spans of the mix this player's data went into, oldest - // first, while they may be unheard. + // first, while they may be unplayed. sent []sentSpan m sync.Mutex @@ -585,25 +585,25 @@ func (p *playerImpl) UnplayedSize() int { defer p.m.Unlock() n := p.buffered() - heard, ok := p.mux.heard() + played, ok := p.mux.played() if !ok { - // What is sent stays, as it may be heard once the driver reports again, + // What is sent stays, as it may be played once the driver reports again, // as after Resume. return n } - p.dropHeard(heard) + p.dropPlayed(played) for _, s := range p.sent { - n += int(s.end-max(s.start, heard)) * p.mux.format.ByteLength() + n += int(s.end-max(s.start, played)) * p.mux.format.ByteLength() } return n } -// dropHeard drops the spans sent that end by sample heard of the mix. +// dropPlayed drops the spans sent that end by sample played of the mix. // -// When dropHeard is called, the mutex m must be locked. -func (p *playerImpl) dropHeard(heard int64) { +// When dropPlayed is called, the mutex m must be locked. +func (p *playerImpl) dropPlayed(played int64) { i := 0 - for i < len(p.sent) && p.sent[i].end <= heard { + for i < len(p.sent) && p.sent[i].end <= played { i++ } p.sent = append(p.sent[:0], p.sent[i:]...) @@ -829,7 +829,7 @@ func (p *playerImpl) finishSourceRead(buf *[]byte, gen, n int, err error) int { p.mux.removePlayer(p) } case err != nil: - // The data read before the error, including the data returned together with it, is played first. + // The data read before the error, including the data returned together with it, is mixed first. p.srcErr = err p.reportSourceErrorIfDrainedImpl() } diff --git a/internal/mux/unplayed_test.go b/internal/mux/unplayed_test.go index f01d24e..aecea2c 100644 --- a/internal/mux/unplayed_test.go +++ b/internal/mux/unplayed_test.go @@ -70,15 +70,15 @@ func frameTime(frames int) time.Duration { return time.Duration(frames) * time.Second / 48000 } -// The tests' driver reports that frame 1,440 of the mix is heard 960 frames, +// The tests' driver reports that frame 1,440 of the mix is played 960 frames, // 20 ms, from now. const ( reportedFrame = 1440 delay = 960 ) -func reportHeard(m *mux.Mux) { - m.SetHeard(reportedFrame, time.Now().Add(frameTime(delay))) +func reportPlayed(m *mux.Mux) { + m.SetPlayed(reportedFrame, time.Now().Add(frameTime(delay))) } func TestUnplayedSizeIsBufferedSizeWithoutAReport(t *testing.T) { @@ -94,26 +94,26 @@ func testUnplayedSizeIsBufferedSizeWithoutAReport(t *testing.T) { } } -func TestUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { - synctest.Test(t, testUnplayedSizeCountsWhatIsNotHeardYet) +func TestUnplayedSizeCountsWhatIsNotPlayedYet(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsWhatIsNotPlayedYet) } -func testUnplayedSizeCountsWhatIsNotHeardYet(t *testing.T) { +func testUnplayedSizeCountsWhatIsNotPlayedYet(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - reportHeard(m) + reportPlayed(m) - // The delay's worth of what is sent is not heard yet. + // The delay's worth of what is sent is not played yet. if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { t.Errorf("at the report: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) } - // It is heard as the clock moves on. + // It is played as the clock moves on. time.Sleep(frameTime(400)) if got, want := p.UnplayedSize(), p.BufferedSize()+(delay-400)*bytesPerFrame; got != want { t.Errorf("400 frames after the report: UnplayedSize() = %d; want %d", got, want) } - // No more than is mixed is heard, however long the device goes without a + // No more than is mixed is played, however long the device goes without a // read. time.Sleep(frameTime(800)) if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { @@ -129,10 +129,10 @@ func testUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - reportHeard(m) + reportPlayed(m) p.Pause() - // What was sent before Pause is still to be heard, and is heard as the + // What was sent before Pause is still to be played, and is played as the // device plays on. if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { t.Errorf("right after Pause: UnplayedSize() = %d; want %d", got, want) @@ -151,14 +151,14 @@ func testUnplayedSizeKeepsWhatIsSentWhileUnreported(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - reportHeard(m) + reportPlayed(m) // As when the device is suspended, and resumed. - m.ClearHeard() + m.ClearPlayed() if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { - t.Errorf("after ClearHeard: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + t.Errorf("after ClearPlayed: UnplayedSize() = %d; want BufferedSize(), %d", got, want) } - reportHeard(m) + reportPlayed(m) if got, want := p.UnplayedSize(), p.BufferedSize()+delay*bytesPerFrame; got != want { t.Errorf("reported again: UnplayedSize() = %d; want BufferedSize() and the delay, %d", got, want) } @@ -172,8 +172,8 @@ func testUnplayedSizeIgnoresAnOldReport(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - // Frame 1,440, the next one mixed, is heard in 1.5 seconds. - m.SetHeard(reportedFrame, time.Now().Add(1500*time.Millisecond)) + // Frame 1,440, the next one mixed, is played in 1.5 seconds. + m.SetPlayed(reportedFrame, time.Now().Add(1500*time.Millisecond)) time.Sleep(time.Second) if got, want := p.UnplayedSize(), p.BufferedSize()+reportedFrame*bytesPerFrame; got != want { @@ -193,20 +193,20 @@ func testUnplayedSizeIgnoresAFarReport(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - reportHeard(m) + reportPlayed(m) // A report puts the frame over 2 seconds away. - m.SetHeard(reportedFrame, time.Now().Add(2*time.Second+time.Millisecond)) + m.SetPlayed(reportedFrame, time.Now().Add(2*time.Second+time.Millisecond)) if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { t.Errorf("after the far report: UnplayedSize() = %d; want BufferedSize(), %d", got, want) } } -func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { - synctest.Test(t, testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard) +func TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed) } -func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { +func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, reportedFrame) readFrames(m, reportedFrame) @@ -215,7 +215,7 @@ func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsHeard(t *testing.T) { if p.IsPlaying() { t.Fatal("the player plays on after its source is mixed") } - reportHeard(m) + reportPlayed(m) if got, want := p.UnplayedSize(), delay*bytesPerFrame; got != want { t.Errorf("as the source ends: UnplayedSize() = %d; want %d", got, want) } @@ -233,7 +233,7 @@ func testUnplayedSizeDiscardsWhatIsSentBeforeSeek(t *testing.T) { m := newMux(t) p := newBufferedPlayer(t, m, 4800) readFrames(m, reportedFrame) - reportHeard(m) + reportPlayed(m) if _, err := p.Seek(0, 0); err != nil { t.Fatal(err) } diff --git a/internal/oboe/binding_android.cpp b/internal/oboe/binding_android.cpp index 432fdab..94465c1 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -219,7 +219,7 @@ class Stream : public oboe::AudioStreamDataCallback, std::atomic max_callback_{0}; // Every kDelayEvery, LoopRead measures when the frame written to fifo_ next - // will be heard, and reports it to Go. delay_gen_ counts the streams + // will be played, and reports it to Go. delay_gen_ counts the streams // dropped, paused and opened, so that a measurement of a stream that changed // meanwhile is dropped. delay_mutex_ guards it, and is taken after mutex_ // where both are. @@ -537,11 +537,11 @@ void Stream::ResetDelayLocked() { // calls nothing while held. Before Play, nothing is reported, and Go has no // function to call. if (play_called_) { - oto_oboe_clearHeard(); + oto_oboe_clearPlayed(); } } -// MeasureDelay measures when the frame written to fifo_ next will be heard, and +// MeasureDelay measures when the frame written to fifo_ next will be played, and // reports it to Go. void Stream::MeasureDelay() { std::shared_ptr stream; @@ -566,7 +566,7 @@ void Stream::MeasureDelay() { int64_t read = fifo_->getReadCounter(); double ms; if (auto result = stream->calculateLatencyMillis(); result) { - // The next frame the stream takes is heard this long from now. It can + // The next frame the stream takes is played this long from now. It can // come out negative, as around an underrun. ms = std::max(0.0, result.value()); } else if (result.error() == oboe::Result::ErrorUnimplemented) { @@ -581,8 +581,8 @@ void Stream::MeasureDelay() { continue; } int64_t written = fifo_->getWriteCounter(); - // The frames queued in fifo_ are heard before the frame written next. - auto heard_at = + // The frames queued in fifo_ are played before the frame written next. + auto played_at = now + std::chrono::microseconds(std::llround( ms * 1000 + (written - read) * 1e6 / sample_rate_)); std::lock_guard lock{delay_mutex_}; @@ -592,9 +592,9 @@ void Stream::MeasureDelay() { // fifo_ is written only with what is read from Go, so its write counter // counts the frames read from Go. Go is told under delay_mutex_, so that // reports and resets reach it in order. - oto_oboe_setHeard(written, + oto_oboe_setPlayed(written, std::chrono::duration_cast( - heard_at - std::chrono::steady_clock::now()) + played_at - std::chrono::steady_clock::now()) .count()); return; } diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 9e49599..c7ea3b5 100644 --- a/internal/oboe/binding_android.go +++ b/internal/oboe/binding_android.go @@ -27,25 +27,25 @@ import ( ) var ( - theReadFunc func(buf []float32) - theHeardFunc func(frame int64, at time.Time) - theClearFunc func() - theErrorFunc func(err error) + theReadFunc func(buf []float32) + thePlayedFunc func(frame int64, at time.Time) + theClearFunc func() + theErrorFunc func(err error) ) // Play starts playing. Playing starts as soon as an audio device is available, -// which can be after Play returns. heardFunc is called while playing with a -// frame and when it is heard, where frame 0 is the first frame read with +// which can be after Play returns. playedFunc is called while playing with a +// frame and when it is played, where frame 0 is the first frame read with // readFunc. clearFunc is called when the last of those no longer holds. // errorFunc is called when playing stops for a reason that cannot be recovered // from, which can happen at any time after Play returns. -func Play(sampleRate int, channelCount int, readFunc func(buf []float32), heardFunc func(frame int64, at time.Time), clearFunc func(), errorFunc func(err error), bufferSizeInBytes int) error { +func Play(sampleRate int, channelCount int, readFunc func(buf []float32), playedFunc func(frame int64, at time.Time), clearFunc func(), errorFunc func(err error), bufferSizeInBytes int) error { // Play can invoke the callbacks. Set the callbacks before Play. // // Reads are paced: after the device takes a large burst, reads made as // fast as there is room would outrun the players' buffers. theReadFunc = newPacer(readFunc, sampleRate, channelCount).Read - theHeardFunc = heardFunc + thePlayedFunc = playedFunc theClearFunc = clearFunc theErrorFunc = errorFunc if msg := C.oto_oboe_Play(C.int(sampleRate), C.int(channelCount), C.int(bufferSizeInBytes)); msg != nil { @@ -75,13 +75,13 @@ func oto_oboe_read(buf *C.float, len C.size_t) { theReadFunc(unsafe.Slice((*float32)(unsafe.Pointer(buf)), len)) } -//export oto_oboe_setHeard -func oto_oboe_setHeard(frame C.int64_t, inNanoseconds C.int64_t) { - theHeardFunc(int64(frame), time.Now().Add(time.Duration(inNanoseconds))) +//export oto_oboe_setPlayed +func oto_oboe_setPlayed(frame C.int64_t, inNanoseconds C.int64_t) { + thePlayedFunc(int64(frame), time.Now().Add(time.Duration(inNanoseconds))) } -//export oto_oboe_clearHeard -func oto_oboe_clearHeard() { +//export oto_oboe_clearPlayed +func oto_oboe_clearPlayed() { theClearFunc() } diff --git a/player.go b/player.go index ce8e651..079aa7d 100644 --- a/player.go +++ b/player.go @@ -79,17 +79,17 @@ func (p *Player) BufferedSize() int { return p.player.BufferedSize() } -// UnplayedSize returns the byte size of the data read from the source that is not heard yet: the buffered data, and -// the data sent to the audio hardware that it has not played yet, also after Pause and after the end of the source. -// While the platform does not report how long the audio hardware takes to play, UnplayedSize returns the same as -// BufferedSize. After Seek or Reset, the data sent before it is not counted. +// UnplayedSize returns the byte size of the data read from the source that the audio hardware has not played yet: +// the buffered data, and the data sent to the audio hardware but not played yet, also after Pause and after the end +// of the source. While the platform does not report how long the audio hardware takes to play, UnplayedSize returns +// the same as BufferedSize. After Seek or Reset, the data sent before it is not counted. func (p *Player) UnplayedSize() int { return p.player.UnplayedSize() } // Err returns an error that occurred while reading the source. // Reaching the end of the source (io.EOF) is not treated as an error. -// An error is reported after the data read before it is played or discarded. +// An error is reported after the data read before it is sent to the audio hardware or discarded. // // Once Err returns a non-nil error, this player is closed and no longer usable, // and Err keeps returning the same error.