Files
aego/platform/web/audio_worker_output_js_test.go
sanspie 50be5c04bc
ci-platforms / darwin amd64 smoke (push) Skipped
GitHub / linux amd64 native GitHub-hosted native CI: success
ci-platforms / windows amd64 smoke (push) Skipped
GitHub / windows amd64 native GitHub-hosted native CI: success
GitHub / darwin arm64 native GitHub-hosted native CI: success
GitHub / darwin amd64 native GitHub-hosted native CI: success
ci / checks (push) Failing after 1h21m34s
ci / native-authoring (push) Skipped
ci-platforms / darwin arm64 smoke (push) Skipped
github-native / gitea-pending (push) Skipped
github-native / darwin amd64 native (push) Skipped
github-native / linux amd64 native (push) Skipped
github-native / windows amd64 native (push) Skipped
github-native / darwin arm64 native (push) Skipped
github-native / gitea-result (push) Skipped
ci / build (amd64, linux, ubuntu-24.04) (push) Successful in 12m4s
ci / release (push) Skipped
Stage 12.5: Art Workspace and asset authoring
Add dockable Art tools, animation and previews, guarded asset workflows,
and the Web Asset Studio built on the shared Art Core. Expand English and
Russian documentation, interactive Try scenes, examples and editor icons.

Add audio waveform navigation, source analysis, guarded previews and a
browser Worker mixer. Preserve source changes and recovery with bounded
checks, and strengthen native, browser and interoperability CI.

Prepare version 0.12.5 and manually built native artifact candidates.
Fix the production site image demo build dependency.
Reuse immutable scene indices when capturing keyframes.
Wait for real Persist save/load completion in component tests.
Stabilize browser Game View captures outside pointer hover.
Aseprite interchange and persistent Audio EDL recovery remain limited;
the artifact workflow does not publish releases or change stable.
2026-11-15 10:37:50 +03:00

292 lines
12 KiB
Go

//go:build js && wasm
package web
import (
"syscall/js"
"testing"
"aego/platform"
)
func TestWebAudioWorkerOutputReservation(t *testing.T) {
g := js.Global()
for _, shared := range []bool{false, true} {
a := &Audio{g: g, shared: shared, target: 3, spec: platform.AudioSpec{SampleRate: 48000, Channels: 2, Frames: 512}}
if _, _, _, _, _, ok := a.WorkerOutput(); ok || !a.ReserveWorkerOutput() || a.ReserveWorkerOutput() {
t.Fatal("untouched output was not reserved exactly once")
}
if _, _, _, _, _, ok := a.WorkerOutput(); ok {
t.Fatal("returned an output before its worklet was ready")
}
if n := a.Write([]float32{1, 1}); n != 0 || a.sentAudio {
t.Fatal("local PCM entered the reserved output")
}
a.ready, a.node = true, g.Get("Object").New()
var dataBuffer, indexBuffer js.Value
if shared {
sab := g.Get("SharedArrayBuffer")
if sab.Type() != js.TypeFunction {
t.Fatal("test requires SharedArrayBuffer")
}
dataBuffer, indexBuffer = sab.New(ringFrames*2*4), sab.New(16)
a.data = g.Get("Uint8Array").New(dataBuffer)
a.index = g.Get("Int32Array").New(indexBuffer)
}
node, data, index, block, target, ok := a.WorkerOutput()
wantTarget := 3072 // Both transports reserve six blocks for this spec.
if !ok || !node.Equal(a.node) || block != 512 || target != wantTarget {
t.Fatalf("unexpected worker endpoint: shared=%v block=%d target=%d ready=%v", shared, block, target, ok)
}
if shared && (!data.Equal(dataBuffer) || !index.Equal(indexBuffer)) {
t.Fatal("shared endpoint did not return the original buffers")
}
if !shared && (data.Type() != js.TypeUndefined || index.Type() != js.TypeUndefined) {
t.Fatal("message endpoint returned shared buffers")
}
if !a.CancelWorkerOutput() || a.CancelWorkerOutput() || a.workerReserved {
t.Fatal("unattached output could not be released")
}
if !a.ReserveWorkerOutput() || !a.CommitWorkerOutput() || a.CommitWorkerOutput() || a.CancelWorkerOutput() {
t.Fatal("attachment was not permanent")
}
if n := a.Write([]float32{1, 1}); n != 0 {
t.Fatal("local PCM entered the attached worker output")
}
}
}
func TestWebAudioWorkerOutputRejectsExistingProducer(t *testing.T) {
for _, a := range []*Audio{
{closed: true},
{failed: "worklet load failed"},
{sentAudio: true},
{priming: true},
{refill: func() int { return 0 }},
} {
if a.ReserveWorkerOutput() {
t.Fatal("claimed an output with a previous or active local producer")
}
}
if (*Audio)(nil).ReserveWorkerOutput() {
t.Fatal("claimed a nil output")
}
}
func TestWebAudioWorkerOutputRejectsLocalRefill(t *testing.T) {
a := &Audio{spec: platform.AudioSpec{Channels: 2, Frames: 512}}
if !a.ReserveWorkerOutput() {
t.Fatal("could not reserve untouched output")
}
a.SetRefill(func() int { t.Error("reserved output invoked local refill"); return 1 })
if a.refill != nil || a.failed == "" {
t.Fatal("reserved output accepted a local refill callback")
}
a.BeginAudioPrime(512)
if a.priming {
t.Fatal("reserved output began a local PCM prime")
}
if !a.CancelWorkerOutput() {
t.Fatal("unattached failed claim could not be cancelled")
}
}
func TestWebAudioWorkerReservationConfiguresWorkletRefills(t *testing.T) {
g := js.Global()
port := g.Get("Function").New(`return {messages:[],postMessage(m){this.messages.push(m)}}`).Invoke()
a := &Audio{port: port, spec: platform.AudioSpec{SampleRate: 48000, Channels: 2, Frames: 512}}
if a.refillThreshold() != 0 || !a.ReserveWorkerOutput() {
t.Fatal("output did not start without a refill producer")
}
if a.refillThreshold() != 1152 || port.Get("messages").Length() != 1 ||
port.Get("messages").Index(0).Get("refillAt").Int() != 1152 {
t.Fatal("worker reservation did not configure the existing refill threshold")
}
if !a.CancelWorkerOutput() || a.refillThreshold() != 0 || port.Get("messages").Length() != 2 ||
port.Get("messages").Index(1).Get("refillAt").Int() != 0 {
t.Fatal("cancelling the reservation left worker refill requests enabled")
}
loading := &Audio{spec: a.spec}
if !loading.ReserveWorkerOutput() || loading.refillThreshold() != 1152 {
t.Fatal("worklet loading after reservation would not receive its refill threshold")
}
}
func TestWebAudioWorkerSharedReserveAndRefillBoundaries(t *testing.T) {
g := js.Global()
oldBlocks := g.Get("aegoAudioBlocks")
g.Set("aegoAudioBlocks", 0)
t.Cleanup(func() { g.Set("aegoAudioBlocks", oldBlocks) })
for _, tt := range []struct {
name string
shared bool
rate, frames, baseTarget, workerTarget int
workerRefill, localRefill int
}{
{"shared default", true, 48000, 512, 3, 6, 2560, 1152},
{"shared 44.1 kHz", true, 44100, 512, 3, 6, 2560, 1059},
{"shared small block", true, 48000, 256, 3, 6, 1280, 768},
{"shared larger block", true, 48000, 1024, 3, 6, 5120, 1152},
{"shared ring bound", true, 48000, 2048, 3, 4, 6144, 1152},
{"shared larger existing target", true, 48000, 512, 8, 8, 2560, 1152},
{"message unchanged", false, 48000, 512, 3, 6, 1152, 1152},
} {
t.Run(tt.name, func(t *testing.T) {
port := g.Get("Function").New(`return {messages:[],postMessage(m){this.messages.push(m)}}`).Invoke()
a := &Audio{g: g, port: port, node: g.Get("Object").New(), ready: true,
shared: tt.shared, target: tt.baseTarget,
spec: platform.AudioSpec{SampleRate: tt.rate, Channels: 2, Frames: tt.frames}}
if tt.shared {
sab := g.Get("SharedArrayBuffer")
a.data = g.Get("Uint8Array").New(sab.New(ringFrames * 2 * 4))
a.index = g.Get("Int32Array").New(sab.New(16))
if a.TargetBlocks() != tt.baseTarget {
t.Fatal("the local shared target changed before reservation")
}
}
if !a.ReserveWorkerOutput() {
t.Fatal("could not reserve the worker output")
}
if got := a.refillThreshold(); got != tt.workerRefill {
t.Errorf("worker refill threshold = %d, want %d", got, tt.workerRefill)
}
_, _, _, block, target, ok := a.WorkerOutput()
if !ok || block != tt.frames || target != tt.workerTarget*tt.frames {
t.Errorf("worker endpoint: block=%d target=%d ready=%v, want target %d", block, target, ok, tt.workerTarget*tt.frames)
}
if port.Get("messages").Index(0).Get("refillAt").Int() != tt.workerRefill {
t.Error("worker refill threshold was not sent to the worklet")
}
if !a.CancelWorkerOutput() || a.refillThreshold() != 0 ||
port.Get("messages").Index(1).Get("refillAt").Int() != 0 {
t.Fatal("cancellation left the worker refill threshold enabled")
}
if tt.shared && a.TargetBlocks() != tt.baseTarget {
t.Fatal("cancelling the worker reservation changed the local shared target")
}
a.SetRefill(func() int { return 0 })
if a.refillThreshold() != tt.localRefill || port.Get("messages").Index(2).Get("refillAt").Int() != tt.localRefill {
t.Fatal("local refill did not recover its original threshold")
}
a.SetRefill(nil)
})
}
loading := &Audio{g: g, shared: true, target: 3,
spec: platform.AudioSpec{SampleRate: 48000, Channels: 2, Frames: 512}}
if !loading.ReserveWorkerOutput() || loading.refillThreshold() != 2560 {
t.Fatal("a shared worklet loaded after reservation would miss the worker threshold")
}
g.Set("aegoAudioBlocks", 4)
message := &Audio{g: g, target: 6, ready: true, node: g.Get("Object").New(),
spec: platform.AudioSpec{SampleRate: 48000, Channels: 2, Frames: 512}}
if !message.ReserveWorkerOutput() {
t.Fatal("could not reserve message output with a diagnostic override")
}
_, _, _, _, target, ok := message.WorkerOutput()
if !ok || target != 2048 || message.refillThreshold() != 1152 {
t.Fatal("message diagnostic override or refill threshold changed")
}
}
func TestWebAudioWorkerReservationFailsClosedOnPortError(t *testing.T) {
g := js.Global()
badPort := g.Get("Function").New(`return {postMessage(){throw Error('closed port')}}`).Invoke()
a := &Audio{port: badPort, spec: platform.AudioSpec{SampleRate: 48000, Channels: 2, Frames: 512}}
if a.ReserveWorkerOutput() || a.workerReserved || a.failed == "" {
t.Fatal("a failed threshold update retained an apparently valid claim")
}
b := &Audio{spec: a.spec}
if !b.ReserveWorkerOutput() {
t.Fatal("could not reserve an output before its worklet loaded")
}
b.port = badPort
if b.CancelWorkerOutput() || !b.workerReserved || b.failed == "" {
t.Fatal("a failed threshold reset incorrectly returned local ownership")
}
}
func TestWebAudioWorkerGatePreservesUserMuteAndHoldsUnmute(t *testing.T) {
g := js.Global()
ctx := g.Get("Function").New(`return {currentTime:5,suspend(){},resume(){}}`).Invoke()
param := g.Get("Function").New(`return {value:1,cancelScheduledValues(){},
setValueAtTime(v){this.value=v},setTargetAtTime(v){this.value=v}}`).Invoke()
gain := g.Get("Object").New()
gain.Set("gain", param)
a := &Audio{g: g, ctx: ctx, gain: gain, state: "running", ready: true}
if a.SetWorkerStateListener(func() {}) || a.SetWorkerGate(true) || !a.ReserveWorkerOutput() {
t.Fatal("worker controls ignored reservation ownership")
}
var states []bool
if !a.SetWorkerStateListener(func() {
states = append(states, a.WorkerSilent())
if !a.SetWorkerGate(true) {
t.Error("could not gate output on a lifecycle transition")
}
}) {
t.Fatal("could not observe reserved output")
}
a.SetMuted(true)
if !a.Muted() || param.Get("value").Float() != 0 {
t.Fatal("mute did not silence the gain")
}
a.SetMuted(false)
if a.Muted() || param.Get("value").Float() != 0 || len(states) != 2 || !states[0] || states[1] {
t.Fatal("unmute escaped the worker gate or lost the user's preference")
}
if !a.SetWorkerGate(false) || param.Get("value").Float() != 1 {
t.Fatal("acknowledged resume did not restore the user's level")
}
a.visibility(true)
if !a.WorkerSilent() || param.Get("value").Float() != 0 {
t.Fatal("pending visibility suspension was not immediately gated")
}
a.visibility(false)
if a.WorkerSilent() || param.Get("value").Float() != 0 {
t.Fatal("visibility resume escaped the gate before the worker was ready")
}
if !a.CancelWorkerOutput() || param.Get("value").Float() != 1 || a.workerState != nil {
t.Fatal("safe startup cancellation did not restore the local output")
}
}
func TestWebAudioWorkerGateFailureRequestsSuspension(t *testing.T) {
g := js.Global()
ctx := g.Get("Function").New(`return {currentTime:0,stopped:false,suspend(){this.stopped=true}}`).Invoke()
gain := g.Get("Function").New(`return {gain:{cancelScheduledValues(){},setValueAtTime(){throw Error('gate failed')}}}`).Invoke()
a := &Audio{g: g, ctx: ctx, gain: gain, workerReserved: true}
if a.SetWorkerGate(true) || a.failed == "" || !ctx.Get("stopped").Bool() {
t.Fatal("gate failure did not stop the output and report an error")
}
}
func TestWebAudioWorkerBaselinePreservesCountersAndFinalQuietReport(t *testing.T) {
g := js.Global()
a := &Audio{g: g, workerReserved: true, ready: true, state: "running",
prior: platform.AudioCounters{Underruns: 2, Consumed: 500, Sum: 4, Samples: 16, Suppressed: 32}}
var signals int
a.SetWorkerStateListener(func() { signals++ })
a.report(js.ValueOf(map[string]any{"time": 1, "consumed": 128, "underruns": 1, "sum": 1, "count": 4,
"quiet": true, "quietToken": 7, "suppressed": 64}))
if !a.WorkerQuiet(7) || a.WorkerQuiet(6) || signals != 1 {
t.Fatal("final worklet report did not publish quiet state")
}
want := platform.AudioCounters{Underruns: 3, Consumed: 628, Sum: 5, Samples: 20, Suppressed: 96}
if got := a.WorkerCounters(); got != want {
t.Fatalf("old output counters = %+v, want %+v", got, want)
}
b := &Audio{g: g, workerReserved: true, ready: true, state: "running"}
if !b.SetWorkerBaseline(want) {
t.Fatal("replacement rejected valid baseline")
}
b.report(js.ValueOf(map[string]any{"time": 2, "consumed": 256, "underruns": 1, "sum": 3, "count": 12}))
stats := b.Stats()
if stats.Underruns != 4 || stats.Consumed != 884 || stats.Suppressed != 96 || stats.RMS != .5 {
t.Fatalf("replacement lost cumulative measurements: %+v", stats)
}
if b.SetWorkerBaseline(want) {
t.Fatal("baseline could be replaced after the new worklet reported audio")
}
}