From 54c3dd88629738a34cc7241cf82d2fe00df70128 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Sun, 8 Nov 2026 13:24:15 +0100 Subject: [PATCH 1/5] oto: report when frames are played on browsers The web driver now calls Mux.SetPlayed, so UnplayedSize counts the frames queued after the player's buffer and the audio hardware's delay. The worklet processor reports which frame of the mix it outputs at which context time, every 100 ms, and clears the report when it outputs silence for want of data. The script processor reports the frame each buffer starts with at the buffer's playbackTime. The main thread turns the context time into a time.Time with AudioContext.getOutputTimestamp. Suspend clears the report. Where getOutputTimestamp is missing, nothing is reported, and UnplayedSize returns the same as BufferedSize, as before. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 73 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/driver_js.go b/driver_js.go index d07a467..db2682c 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" @@ -30,6 +31,9 @@ type context struct { scriptProcessorCallback js.Func err atomicError + // outputTimestamp reports whether the AudioContext has getOutputTimestamp. + outputTimestamp bool + mux *mux.Mux } @@ -50,10 +54,7 @@ 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. + d.outputTimestamp = d.audioContext.Get("getOutputTimestamp").Truthy() if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. @@ -73,6 +74,10 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { this.channelCount_ = %[2]d; this.buf_ = new Float32Array(); this.waitRecv_ = false; + // frames_ counts the frames of the mix output so far. + this.frames_ = 0; + // reportedTime_ is the context time of the last report to the main thread. + this.reportedTime_ = -Infinity; // Receive data from the main thread. this.port.onmessage = (event) => { @@ -97,9 +102,20 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { for (let i = 0; i < output.length; i++) { output[i].fill(0); } + // The silence delays the frames of the mix after it, so the last report no longer holds. + if (this.reportedTime_ !== -Infinity) { + this.reportedTime_ = -Infinity; + this.port.postMessage({clear: true}); + } return true; } + // Report which frame of the mix is output at which context time. + if (currentTime - this.reportedTime_ >= %[3]g) { + this.reportedTime_ = currentTime; + this.port.postMessage({frame: this.frames_, time: currentTime}); + } + // If the buffer is short, request more data. if (this.buf_.length <= Math.max(this.bufferSize_*this.channelCount_ / 2, output[0].length*this.channelCount_) && !this.waitRecv_) { this.waitRecv_ = true; @@ -112,11 +128,12 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { } } this.buf_ = this.buf_.slice(output[0].length*this.channelCount_); + this.frames_ += output[0].length; return true; } } registerProcessor('oto-worklet-processor', OtoWorkletProcessor); -`, bufferSizeInBytes/4/channelCount, channelCount) +`, bufferSizeInBytes/4/channelCount, channelCount, workletReportInterval.Seconds()) scriptURL := newScriptURL(script) var onAddModuleSuccess, onAddModuleFailure js.Func release := func() { @@ -131,11 +148,22 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); "outputChannelCount": []any{channelCount}, }) port := node.Get("port") - // When the worklet processor requests more data, send the request to the worklet. + // The worklet processor sends reports of the frame it outputs, and requests for more data. port.Set("onmessage", js.FuncOf(func(this js.Value, arguments []js.Value) any { + data := arguments[0].Get("data") + if data.Type() == js.TypeObject { + if data.Get("clear").Truthy() { + d.mux.ClearPlayed() + return nil + } + d.reportPlayed(int64(data.Get("frame").Float()), data.Get("time").Float()) + return nil + } + + // When the worklet processor requests more data, send the data to the worklet. // A transfer must cover at least one render quantum, even when the // requested context buffer is smaller than the worklet's output. - if size := arguments[0].Get("data").Int() * channelCount; len(buf32) < size { + if size := data.Int() * channelCount; len(buf32) < size { buf32 = make([]float32, size) } d.mux.ReadFloat32s(buf32) @@ -166,9 +194,17 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); chBuf32[i] = make([]float32, len(buf32)/channelCount) } + // frames counts the frames of the mix read so far. + var frames int64 + sp := d.audioContext.Call("createScriptProcessor", bufferSizeInBytes/4/channelCount, 0, channelCount) f := js.FuncOf(func(this js.Value, arguments []js.Value) any { + // The buffer filled now is output at the context time playbackTime. + if t := arguments[0].Get("playbackTime"); t.Type() == js.TypeNumber { + d.reportPlayed(frames, t.Float()) + } d.mux.ReadFloat32s(buf32) + frames += int64(len(buf32) / channelCount) for i := 0; i < channelCount; i++ { for j := range chBuf32[i] { chBuf32[i][j] = buf32[j*channelCount+i] @@ -252,6 +288,7 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); func (c *context) Suspend() error { c.audioContext.Call("suspend") + c.mux.ClearPlayed() return nil } @@ -264,6 +301,28 @@ func (c *context) Err() error { return c.err.Load() } +// workletReportInterval is how often, in context time, the worklet reports which +// frame of the mix it outputs. +const workletReportInterval = 100 * time.Millisecond + +// reportPlayed reports to the mux that frame of the mix is output at the context +// time contextTime, in seconds. +func (c *context) reportPlayed(frame int64, contextTime float64) { + if !c.outputTimestamp { + return + } + // getOutputTimestamp gives the context time of the frame the audio hardware + // plays now, and the performance time it is played at. + ts := c.audioContext.Call("getOutputTimestamp") + performanceTime := ts.Get("performanceTime") + // The performance time is 0 until the audio hardware starts playing. + if performanceTime.Type() != js.TypeNumber || performanceTime.Float() == 0 { + return + } + ms := performanceTime.Float() + (contextTime-ts.Get("contextTime").Float())*1000 - js.Global().Get("performance").Call("now").Float() + c.mux.SetPlayed(frame, time.Now().Add(time.Duration(ms*float64(time.Millisecond)))) +} + 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)) From fcf9e7959cd46313d89b73d12aea0ac4aa92de07 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Mon, 9 Nov 2026 22:09:21 +0100 Subject: [PATCH 2/5] oto: drop browser reports that arrive while suspended AudioContext.suspend is asynchronous, so a report already queued could land after Suspend cleared the report. Reports are now dropped from Suspend until Resume. Resume also tells the worklet to report on its next output, rather than up to 100 ms later. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/driver_js.go b/driver_js.go index db2682c..73a65d2 100644 --- a/driver_js.go +++ b/driver_js.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "runtime" + "sync/atomic" "syscall/js" "time" "unsafe" @@ -31,8 +32,16 @@ type context struct { scriptProcessorCallback js.Func err atomicError - // outputTimestamp reports whether the AudioContext has getOutputTimestamp. - outputTimestamp bool + // hasOutputTimestamp reports whether the AudioContext has getOutputTimestamp. + hasOutputTimestamp bool + + // suspended is set from Suspend until Resume. Reports of played frames are + // dropped while it is set, as they can still arrive after Suspend. + suspended atomic.Bool + + // workletPort is the message port of the AudioWorkletNode, when the + // AudioWorklet is used. + workletPort js.Value mux *mux.Mux } @@ -54,7 +63,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI audioContext: class.New(options), mux: mux.New(sampleRate, channelCount, format), } - d.outputTimestamp = d.audioContext.Get("getOutputTimestamp").Truthy() + d.hasOutputTimestamp = d.audioContext.Get("getOutputTimestamp").Truthy() if bufferSizeInBytes == 0 { // 4096 was not great at least on Safari 15. @@ -81,6 +90,11 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { // Receive data from the main thread. this.port.onmessage = (event) => { + // After a resume, report on the next output. + if (event.data.reset) { + this.reportedTime_ = -Infinity; + return; + } const buf = event.data; const newBuf = new Float32Array(this.buf_.length + buf.length); newBuf.set(this.buf_); @@ -148,6 +162,7 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); "outputChannelCount": []any{channelCount}, }) port := node.Get("port") + d.workletPort = port // The worklet processor sends reports of the frame it outputs, and requests for more data. port.Set("onmessage", js.FuncOf(func(this js.Value, arguments []js.Value) any { data := arguments[0].Get("data") @@ -200,6 +215,9 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); sp := d.audioContext.Call("createScriptProcessor", bufferSizeInBytes/4/channelCount, 0, channelCount) f := js.FuncOf(func(this js.Value, arguments []js.Value) any { // The buffer filled now is output at the context time playbackTime. + // This reports once per buffer. A buffer that lasts longer than the + // mux keeps a report (reportLifetime), such as 16384 frames at + // 16 kHz or less, leaves gaps without a report. if t := arguments[0].Get("playbackTime"); t.Type() == js.TypeNumber { d.reportPlayed(frames, t.Float()) } @@ -287,12 +305,17 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); } func (c *context) Suspend() error { + c.suspended.Store(true) c.audioContext.Call("suspend") c.mux.ClearPlayed() return nil } func (c *context) Resume() error { + c.suspended.Store(false) + if c.workletPort.Truthy() { + c.workletPort.Call("postMessage", map[string]any{"reset": true}) + } c.audioContext.Call("resume") return nil } @@ -308,7 +331,7 @@ const workletReportInterval = 100 * time.Millisecond // reportPlayed reports to the mux that frame of the mix is output at the context // time contextTime, in seconds. func (c *context) reportPlayed(frame int64, contextTime float64) { - if !c.outputTimestamp { + if !c.hasOutputTimestamp || c.suspended.Load() { return } // getOutputTimestamp gives the context time of the frame the audio hardware From 0eaa3d4b4a391afc181ca58aab1113c768885d26 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Mon, 9 Nov 2026 22:22:23 +0100 Subject: [PATCH 3/5] oto: drop worklet reports from before a Suspend after Resume A report posted before a Suspend and handled after a quick Resume passed the suspended check. The worklet now tags each report with a generation that changes on every Suspend, as the PulseAudio driver does. The underrun clear has its own flag, so a reset no longer skips it. A report that maps to a time in the past is dropped, as its output timestamp is stale. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/driver_js.go b/driver_js.go index 73a65d2..b129685 100644 --- a/driver_js.go +++ b/driver_js.go @@ -39,6 +39,11 @@ type context struct { // dropped while it is set, as they can still arrive after Suspend. suspended atomic.Bool + // reportGen changes on every Suspend. The worklet tags its reports with the + // generation it last received, so that a report from before a Suspend is + // dropped even when it arrives after Resume. + reportGen atomic.Int64 + // workletPort is the message port of the AudioWorkletNode, when the // AudioWorklet is used. workletPort js.Value @@ -87,11 +92,17 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { this.frames_ = 0; // reportedTime_ is the context time of the last report to the main thread. this.reportedTime_ = -Infinity; + // reported_ is whether a report stands since the last clear. + this.reported_ = false; + // gen_ is the report generation, received from the main thread on resume. + this.gen_ = 0; // Receive data from the main thread. this.port.onmessage = (event) => { - // After a resume, report on the next output. - if (event.data.reset) { + // After a resume, tag reports with the new generation, and report on + // the next output. + if (typeof event.data.gen === 'number') { + this.gen_ = event.data.gen; this.reportedTime_ = -Infinity; return; } @@ -117,7 +128,8 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { output[i].fill(0); } // The silence delays the frames of the mix after it, so the last report no longer holds. - if (this.reportedTime_ !== -Infinity) { + if (this.reported_) { + this.reported_ = false; this.reportedTime_ = -Infinity; this.port.postMessage({clear: true}); } @@ -127,7 +139,8 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { // Report which frame of the mix is output at which context time. if (currentTime - this.reportedTime_ >= %[3]g) { this.reportedTime_ = currentTime; - this.port.postMessage({frame: this.frames_, time: currentTime}); + this.reported_ = true; + this.port.postMessage({frame: this.frames_, time: currentTime, gen: this.gen_}); } // If the buffer is short, request more data. @@ -171,6 +184,9 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); d.mux.ClearPlayed() return nil } + if int64(data.Get("gen").Float()) != d.reportGen.Load() { + return nil + } d.reportPlayed(int64(data.Get("frame").Float()), data.Get("time").Float()) return nil } @@ -306,6 +322,7 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); func (c *context) Suspend() error { c.suspended.Store(true) + c.reportGen.Add(1) c.audioContext.Call("suspend") c.mux.ClearPlayed() return nil @@ -314,7 +331,7 @@ func (c *context) Suspend() error { func (c *context) Resume() error { c.suspended.Store(false) if c.workletPort.Truthy() { - c.workletPort.Call("postMessage", map[string]any{"reset": true}) + c.workletPort.Call("postMessage", map[string]any{"gen": c.reportGen.Load()}) } c.audioContext.Call("resume") return nil @@ -343,6 +360,12 @@ func (c *context) reportPlayed(frame int64, contextTime float64) { return } ms := performanceTime.Float() + (contextTime-ts.Get("contextTime").Float())*1000 - js.Global().Get("performance").Call("now").Float() + // A frame rendered now plays in the future. A time in the past means the + // output timestamp is stale, as it can be right after a resume, or the + // report waited too long on the main thread. + if ms < 0 { + return + } c.mux.SetPlayed(frame, time.Now().Add(time.Duration(ms*float64(time.Millisecond)))) } From df77fbd0bb390dbebceeb8ea295247e3e1e73249 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 11 Nov 2026 10:03:31 +0100 Subject: [PATCH 4/5] oto: drop browser reports by the output timestamp's age A report handled late on the main thread still maps correctly, so a time in the past is no reason to drop it. A stale output timestamp is old, so a report is now dropped when getOutputTimestamp is more than 200 ms old. This also covers a script processor event from before a Suspend that fires after Resume. The worklet now gets the report generation when it is created, as a Suspend and Resume can both run before the module loads. workletPort is now an atomic.Pointer. Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/driver_js.go b/driver_js.go index b129685..1623c97 100644 --- a/driver_js.go +++ b/driver_js.go @@ -45,8 +45,8 @@ type context struct { reportGen atomic.Int64 // workletPort is the message port of the AudioWorkletNode, when the - // AudioWorklet is used. - workletPort js.Value + // AudioWorklet is used. It is set when the worklet module loads. + workletPort atomic.Pointer[js.Value] mux *mux.Mux } @@ -82,7 +82,7 @@ func newContext(sampleRate int, channelCount int, format mux.Format, bufferSizeI if w := d.audioContext.Get("audioWorklet"); w.Truthy() { script := fmt.Sprintf(` class OtoWorkletProcessor extends AudioWorkletProcessor { - constructor() { + constructor(options) { super(); this.bufferSize_ = %[1]d; this.channelCount_ = %[2]d; @@ -95,7 +95,7 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { // reported_ is whether a report stands since the last clear. this.reported_ = false; // gen_ is the report generation, received from the main thread on resume. - this.gen_ = 0; + this.gen_ = options.processorOptions.gen; // Receive data from the main thread. this.port.onmessage = (event) => { @@ -173,9 +173,11 @@ registerProcessor('oto-worklet-processor', OtoWorkletProcessor); node := js.Global().Get("AudioWorkletNode").New(d.audioContext, "oto-worklet-processor", map[string]any{ "outputChannelCount": []any{channelCount}, + // The generation can have changed already, by a Suspend before the module loaded. + "processorOptions": map[string]any{"gen": d.reportGen.Load()}, }) port := node.Get("port") - d.workletPort = port + d.workletPort.Store(&port) // The worklet processor sends reports of the frame it outputs, and requests for more data. port.Set("onmessage", js.FuncOf(func(this js.Value, arguments []js.Value) any { data := arguments[0].Get("data") @@ -330,8 +332,8 @@ func (c *context) Suspend() error { func (c *context) Resume() error { c.suspended.Store(false) - if c.workletPort.Truthy() { - c.workletPort.Call("postMessage", map[string]any{"gen": c.reportGen.Load()}) + if port := c.workletPort.Load(); port != nil { + port.Call("postMessage", map[string]any{"gen": c.reportGen.Load()}) } c.audioContext.Call("resume") return nil @@ -345,6 +347,11 @@ func (c *context) Err() error { // frame of the mix it outputs. const workletReportInterval = 100 * time.Millisecond +// maxOutputTimestampAge is the oldest an output timestamp can be for a report. +// While playing, getOutputTimestamp is a few milliseconds old at most. Right +// after a resume, it can still hold its values from before the suspend. +const maxOutputTimestampAge = 200 * time.Millisecond + // reportPlayed reports to the mux that frame of the mix is output at the context // time contextTime, in seconds. func (c *context) reportPlayed(frame int64, contextTime float64) { @@ -359,13 +366,11 @@ func (c *context) reportPlayed(frame int64, contextTime float64) { if performanceTime.Type() != js.TypeNumber || performanceTime.Float() == 0 { return } - ms := performanceTime.Float() + (contextTime-ts.Get("contextTime").Float())*1000 - js.Global().Get("performance").Call("now").Float() - // A frame rendered now plays in the future. A time in the past means the - // output timestamp is stale, as it can be right after a resume, or the - // report waited too long on the main thread. - if ms < 0 { + now := js.Global().Get("performance").Call("now").Float() + if now-performanceTime.Float() > float64(maxOutputTimestampAge.Milliseconds()) { return } + ms := performanceTime.Float() + (contextTime-ts.Get("contextTime").Float())*1000 - now c.mux.SetPlayed(frame, time.Now().Add(time.Duration(ms*float64(time.Millisecond)))) } From 0b120ce23645ebb538fa0988132d79e76c368aa1 Mon Sep 17 00:00:00 2001 From: Marcus Johansson Date: Wed, 11 Nov 2026 10:06:36 +0100 Subject: [PATCH 5/5] oto: say where the worklet gets its report generation Updates #311 Co-Authored-By: Claude Opus 5.5 --- driver_js.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/driver_js.go b/driver_js.go index 1623c97..300740e 100644 --- a/driver_js.go +++ b/driver_js.go @@ -94,7 +94,7 @@ class OtoWorkletProcessor extends AudioWorkletProcessor { this.reportedTime_ = -Infinity; // reported_ is whether a report stands since the last clear. this.reported_ = false; - // gen_ is the report generation, received from the main thread on resume. + // gen_ is the report generation, set at creation and on every resume. this.gen_ = options.processorOptions.gen; // Receive data from the main thread.