diff --git a/driver_android.go b/driver_android.go index 17111e0..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.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 76adb04..5eb3320 100644 --- a/driver_console.go +++ b/driver_console.go @@ -53,6 +53,8 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI c := &context{ mux: mux.New(sampleRate, channelCount, format), } + // 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 951f642..3988140 100644 --- a/driver_darwin.go +++ b/driver_darwin.go @@ -160,6 +160,10 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI channelCount: channelCount, oneBufferSizeInBytes: oneBufferSizeInBytes, } + // 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. theContext = c if err := initializeAPI(); err != nil { diff --git a/driver_js.go b/driver_js.go index e1e8f20..b0beff6 100644 --- a/driver_js.go +++ b/driver_js.go @@ -50,6 +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 played with d.mux.SetPlayed: the + // AudioContext's getOutputTimestamp gives the context time of the frame + // 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 19879f4..91eb501 100644 --- a/driver_unix.go +++ b/driver_unix.go @@ -47,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 when the frames are played with ctx.mux.SetPlayed, from the + // delay: PulseAudio's latency query for its stream, and snd_pcm_delay on ALSA, + // plus what the driver has read and not yet written. // Initializing a driver might take some time, so do it asynchronously. // PulseAudio is the default; if no server is reachable, fall back to ALSA. diff --git a/driver_windows.go b/driver_windows.go index d091e3d..a866c3f 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 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. // Initializing drivers might take some time. Do this asynchronously. go func() { diff --git a/internal/mux/mux.go b/internal/mux/mux.go index 7652d83..0782c67 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,30 @@ 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 + + // 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 unplayed. +const maxSentSpans = 256 + +// 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 played. +const maxReportedDelay = 2 * time.Second + // New creates a new Mux. func New(sampleRate int, channelCount int, format Format) *Mux { m := &Mux{ @@ -155,6 +178,54 @@ func (m *Mux) removePlayer(player *playerImpl) { delete(m.players, player) } +// 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) SetPlayed(frame int64, at time.Time) { + now := time.Now() + + m.playedMu.Lock() + defer m.playedMu.Unlock() + + if at.Sub(now) > maxReportedDelay || now.Sub(at) > reportLifetime { + m.playedKnown = false + return + } + m.playedKnown = true + m.playedFrame = frame + m.playedAt = at + m.reportedAt = now +} + +// ClearPlayed clears the driver's last report. +func (m *Mux) ClearPlayed() { + m.playedMu.Lock() + defer m.playedMu.Unlock() + + m.playedKnown = false +} + +// played returns how many of the samples mixed have been played, and whether the +// driver reports it. +func (m *Mux) played() (int64, bool) { + now := time.Now() + + 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 played at the sample rate. + frame += int64(now.Sub(at)) * int64(m.sampleRate) / int64(time.Second) + // 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 +} + // Stop stops the Mux from reading the players' sources. func (m *Mux) Stop() { m.cond.L.Lock() @@ -180,9 +251,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() } @@ -225,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. @@ -237,9 +310,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 unplayed. + 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, one sample of the data to each sample of the mix. +type sentSpan struct { + start int64 + end int64 +} + func (m *Mux) NewPlayer(src io.Reader) *Player { p := &playerImpl{ mux: m, @@ -406,6 +490,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 +519,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 +576,59 @@ 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() + played, ok := p.mux.played() + if !ok { + // What is sent stays, as it may be played once the driver reports again, + // as after Resume. + return n + } + p.dropPlayed(played) + for _, s := range p.sent { + n += int(s.end-max(s.start, played)) * p.mux.format.ByteLength() + } + return n +} + +// dropPlayed drops the spans sent that end by sample played of the mix. +// +// 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 <= played { + 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) { + // 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 + } + 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 +667,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 +729,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) { @@ -683,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 new file mode 100644 index 0000000..aecea2c --- /dev/null +++ b/internal/mux/unplayed_test.go @@ -0,0 +1,243 @@ +// 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" + "testing/synctest" + "time" + + "github.com/ebitengine/oto/v3/internal/mux" +) + +// The tests play 48 kHz stereo float32: 8 bytes a frame. +const bytesPerFrame = 8 + +// 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, 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) + // 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) + }) + return m +} + +// newBufferedPlayer plays frames frames of sound on m, once the player has +// 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() + synctest.Wait() + if got, want := p.BufferedSize(), frames*bytesPerFrame; got != want { + t.Fatalf("the player buffered %d bytes; want %d", got, want) + } + 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)) +} + +// 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 played 960 frames, +// 20 ms, from now. +const ( + reportedFrame = 1440 + delay = 960 +) + +func reportPlayed(m *mux.Mux) { + m.SetPlayed(reportedFrame, time.Now().Add(frameTime(delay))) +} + +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 { + t.Errorf("UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } +} + +func TestUnplayedSizeCountsWhatIsNotPlayedYet(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsWhatIsNotPlayedYet) +} + +func testUnplayedSizeCountsWhatIsNotPlayedYet(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportPlayed(m) + + // 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 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 played, 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) + } +} + +func TestUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsWhatIsSentBeforePause) +} + +func testUnplayedSizeCountsWhatIsSentBeforePause(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportPlayed(m) + p.Pause() + + // 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) + } + 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) + reportPlayed(m) + + // As when the device is suspended, and resumed. + m.ClearPlayed() + if got, want := p.UnplayedSize(), p.BufferedSize(); got != want { + t.Errorf("after ClearPlayed: UnplayedSize() = %d; want BufferedSize(), %d", got, want) + } + 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) + } +} + +func TestUnplayedSizeIgnoresAnOldReport(t *testing.T) { + synctest.Test(t, testUnplayedSizeIgnoresAnOldReport) +} + +func testUnplayedSizeIgnoresAnOldReport(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + // 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 { + 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) + reportPlayed(m) + + // A report puts the frame over 2 seconds away. + 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 TestUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed(t *testing.T) { + synctest.Test(t, testUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed) +} + +func testUnplayedSizeCountsTheEndOfTheSourceUntilItIsPlayed(t *testing.T) { + 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") + } + reportPlayed(m) + if got, want := p.UnplayedSize(), delay*bytesPerFrame; got != want { + t.Errorf("as the source ends: UnplayedSize() = %d; want %d", got, want) + } + time.Sleep(frameTime(delay)) + if got := p.UnplayedSize(); got != 0 { + t.Errorf("a delay after the source ends: UnplayedSize() = %d; want 0", got) + } +} + +func TestUnplayedSizeDiscardsWhatIsSentBeforeSeek(t *testing.T) { + synctest.Test(t, testUnplayedSizeDiscardsWhatIsSentBeforeSeek) +} + +func testUnplayedSizeDiscardsWhatIsSentBeforeSeek(t *testing.T) { + m := newMux(t) + p := newBufferedPlayer(t, m, 4800) + readFrames(m, reportedFrame) + reportPlayed(m) + 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 9fce54d..94465c1 100644 --- a/internal/oboe/binding_android.cpp +++ b/internal/oboe/binding_android.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -145,6 +146,8 @@ class Stream : public oboe::AudioStreamDataCallback, // The Locked functions must be called with mutex_ held. Status OpenLocked(); void CloseLocked(); + void ResetDelayLocked(); + void MeasureDelay(); void PrepareBuffersLocked(); void ConfigureRefillLocked(); Status EnsureStreamLocked(); @@ -215,6 +218,14 @@ class Stream : public oboe::AudioStreamDataCallback, std::atomic min_wait_us_{1000}; std::atomic max_callback_{0}; + // Every kDelayEvery, LoopRead measures when the frame written to fifo_ next + // 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. + std::mutex delay_mutex_; + int delay_gen_ = 0; + // read_thread_ runs LoopRead, which reads from Go into fifo_. std::unique_ptr read_thread_; @@ -259,6 +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() { + ResetDelayLocked(); if (!stream_) { return; } @@ -417,6 +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. + ResetDelayLocked(); stream_.reset(); state_ = State::kStopped; // A stream that goes away while suspended stays closed until Resume, so @@ -440,6 +453,7 @@ void Stream::onErrorAfterClose(oboe::AudioStream *oboe_stream, const char *Stream::Pause() { std::lock_guard lock{mutex_}; suspended_ = true; + ResetDelayLocked(); if (state_ == State::kStartDeferred) { // Nothing may start playing while the caller wants silence. Resume attempts // it again. @@ -490,6 +504,7 @@ const char *Stream::Close() { if (oboe::Result result = stream_->close(); result != oboe::Result::OK) { return oboe::convertToText(result); } + ResetDelayLocked(); stream_.reset(); return nullptr; } @@ -510,8 +525,89 @@ oboe::DataCallbackResult Stream::onAudioReady(oboe::AudioStream *oboe_stream, Stream::Stream() = default; +// kDelayEvery is how often LoopRead measures the delay. +constexpr std::chrono::milliseconds kDelayEvery{100}; + +// 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. Before Play, nothing is reported, and Go has no + // function to call. + if (play_called_) { + oto_oboe_clearPlayed(); + } +} + +// MeasureDelay measures when the frame written to fifo_ next will be played, and +// reports it to Go. +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. 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; + if (auto result = stream->calculateLatencyMillis(); result) { + // 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) { + // 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 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_}; + if (delay_gen_ != gen) { + return; + } + // 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_setPlayed(written, + std::chrono::duration_cast( + played_at - std::chrono::steady_clock::now()) + .count()); + return; + } +} + void Stream::LoopRead() { + auto measured = std::chrono::steady_clock::now(); for (;;) { + if (auto now = std::chrono::steady_clock::now(); + now - measured >= kDelayEvery) { + measured = now; + 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 // bursts, and at most the fifo's capacity less one read. diff --git a/internal/oboe/binding_android.go b/internal/oboe/binding_android.go index 86355ed..c7ea3b5 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) + 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. 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. 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), 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 + thePlayedFunc = playedFunc + 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)) @@ -68,6 +75,16 @@ func oto_oboe_read(buf *C.float, len C.size_t) { theReadFunc(unsafe.Slice((*float32)(unsafe.Pointer(buf)), len)) } +//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_clearPlayed +func oto_oboe_clearPlayed() { + theClearFunc() +} + //export oto_oboe_error func oto_oboe_error(msg *C.char) { theErrorFunc(fmt.Errorf("oboe: %s", C.GoString(msg))) 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) + } +} diff --git a/player.go b/player.go index f6cf37d..079aa7d 100644 --- a/player.go +++ b/player.go @@ -79,9 +79,17 @@ func (p *Player) BufferedSize() int { return p.player.BufferedSize() } +// 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.