Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 118 additions & 8 deletions driver_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import (
"errors"
"fmt"
"runtime"
"sync/atomic"
"syscall/js"
"time"
"unsafe"

"github.com/ebitengine/oto/v3/internal/mux"
Expand All @@ -30,6 +32,22 @@ type context struct {
scriptProcessorCallback js.Func
err atomicError

// 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

// 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. It is set when the worklet module loads.
workletPort atomic.Pointer[js.Value]

mux *mux.Mux
}

Expand All @@ -50,10 +68,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.hasOutputTimestamp = d.audioContext.Get("getOutputTimestamp").Truthy()

if bufferSizeInBytes == 0 {
// 4096 was not great at least on Safari 15.
Expand All @@ -67,15 +82,30 @@ 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;
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;
// reported_ is whether a report stands since the last clear.
this.reported_ = false;
// gen_ is the report generation, set at creation and on every resume.
this.gen_ = options.processorOptions.gen;

// Receive data from the main thread.
this.port.onmessage = (event) => {
// 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;
}
const buf = event.data;
const newBuf = new Float32Array(this.buf_.length + buf.length);
newBuf.set(this.buf_);
Expand All @@ -97,9 +127,22 @@ 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.reported_) {
this.reported_ = false;
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.reported_ = true;
this.port.postMessage({frame: this.frames_, time: currentTime, gen: this.gen_});
}

// 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;
Expand All @@ -112,11 +155,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() {
Expand All @@ -129,13 +173,30 @@ 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")
// When the worklet processor requests more data, send the request to the worklet.
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")
if data.Type() == js.TypeObject {
if data.Get("clear").Truthy() {
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
}

// 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)
Expand Down Expand Up @@ -166,9 +227,20 @@ 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.
// 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())
}
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]
Expand Down Expand Up @@ -251,11 +323,18 @@ 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
}

func (c *context) Resume() error {
c.suspended.Store(false)
if port := c.workletPort.Load(); port != nil {
port.Call("postMessage", map[string]any{"gen": c.reportGen.Load()})
}
c.audioContext.Call("resume")
return nil
}
Expand All @@ -264,6 +343,37 @@ 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

// 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) {
if !c.hasOutputTimestamp || c.suspended.Load() {
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
}
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))))
}

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))
Expand Down
Loading