A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(audio): bind asset releases to retained buffer generations
yhh4beb8b6ce1f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 236bded64..7335a8f9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Fixed+- **Old audio asset leases do not release replacement clips.** Each loaded audio result releases the buffer generation and audio device it actually retained. Releasing an outgoing scene's asset after a clip update no longer unpins or evicts the current clip under the same path, including when the warm-cache budget is zero. Final release still retires the current buffer normally.+- **Audio source updates retire pending decodes.** Invalidating a clip starts a new load instead of joining its outdated request. Late results release their buffers without overwriting current audio or deleting the newer request's deduplication record. Web Audio also tracks source revisions across file reads and decode completion so old requests cannot restore stale URL-cache entries.- **Late audio decodes do not repopulate closed devices.** Audio preloads that finish after disposal release their decoded buffers instead of restoring cache entries. Concurrent callers still share one decode and one release, and new preloads on a closed API perform no backend work. Editor Stop now leaves the buffer count and resident bytes at zero even when a decode completes afterwards.diff --git a/sdk/src/asset/loaders/AudioAssetLoader.ts b/sdk/src/asset/loaders/AudioAssetLoader.tsindex fe8ccc812..6b1bc3b55 100644--- a/sdk/src/asset/loaders/AudioAssetLoader.ts+++ b/sdk/src/asset/loaders/AudioAssetLoader.ts@@ -5,6 +5,7 @@ import type { AudioAPI } from '../../audio/Audio';import { log } from '../../util/logger';export class AudioAssetLoader implements AssetLoader<AudioResult> {+ private readonly releases_ = new WeakMap<AudioResult, () => void>();readonly type = 'audio';readonly extensions = ['.mp3', '.wav', '.ogg', '.m4a', '.aac', '.flac', '.webm'];@@ -21,7 +22,7 @@ export class AudioAssetLoader implements AssetLoader<AudioResult> {// Warm-cache hit: the buffer survived its last release as an evictable// entry — pin it and skip the whole fetch + decode.if (audio.retainBuffer(path)) {- return { bufferId: path };+ return this.ownedResult_(audio, path);}// A `url` backend (a mini-game player) streams the file itself: fetching// it here reads the whole clip into memory to drop it, and its source@@ -33,14 +34,22 @@ export class AudioAssetLoader implements AssetLoader<AudioResult> {await audio.preloadFromData(path, await ctx.loadBinary(buildPath));}audio.retainBuffer(path);- return { bufferId: path };+ return this.ownedResult_(audio, path);+ }++ private ownedResult_(audio: AudioAPI, path: string): AudioResult {+ const result = { bufferId: path };+ const buffer = audio.getBufferHandle(path);+ if (buffer) this.releases_.set(result, () => {+ if (audio.getBufferHandle(path) === buffer) audio.releaseBuffer(path);+ });+ return result;}unload(asset: AudioResult): void {- // Drops the one reference Assets holds; the AudioAPI decides what that- // means — retain as an evictable warm-cache entry under the budget, or- // free outright when the budget is 0.- this.getAudio_()?.releaseBuffer(asset.bufferId);+ const release = this.releases_.get(asset);+ this.releases_.delete(asset);+ release?.();}invalidate(path: string): boolean {diff --git a/sdk/tests/audio-residency.test.ts b/sdk/tests/audio-residency.test.tsindex 069553053..68d424f8d 100644--- a/sdk/tests/audio-residency.test.ts+++ b/sdk/tests/audio-residency.test.ts@@ -9,8 +9,15 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';import { AudioAPI } from '../src/audio/Audio';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from '../src/audio/PlatformAudioBackend';+vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({}), getResourceManager: () => null,+ evictTextureDimensions: vi.fn(),+}));+interface MockBackend extends PlatformAudioBackend {loads: string[];unloaded: number[];@@ -67,6 +74,54 @@ describe('AudioAPI buffer residency', () => {audio.setBufferBudget(1000);});+ it.each([0, 1000])('releasing an old asset lease cannot release the replacement clip, budget=%i', async budget => {+ audio.setBufferBudget(budget);+ const assets = Assets.create({+ module: null,+ getAudio: () => audio,+ backend: {+ fetchBinary: async () => new ArrayBuffer(8),+ fetchText: async () => '{}',+ resolveUrl: (path: string) => path,+ } as Backend,+ });+ const old = await assets.acquireTyped('audio', 'edited.wav');+ const before = audio.getBufferHandle('edited.wav');+ expect(assets.invalidate('edited.wav')).toBe(true);+ const current = await assets.acquireTyped('audio', 'edited.wav');+ const replacement = audio.getBufferHandle('edited.wav');+ expect(replacement).toBeDefined();+ expect(replacement).not.toBe(before);+ old.release();+ expect(audio.getBufferHandle('edited.wav')).toBe(replacement);+ expect(audio.getBufferStats()).toMatchObject({ bufferCount: 1, evictableCount: 0 });+ expect(audio.trimBufferCache()).toBe(0);+ current.release();+ audio.trimBufferCache();+ expect(audio.getBufferStats()).toMatchObject({ bufferCount: 0, bufferBytes: 0 });+ });++ it('releases a lease on its original device when the audio provider changes', async () => {+ audio.setBufferBudget(0);+ const original = audio;+ const assets = Assets.create({+ module: null, getAudio: () => audio,+ backend: { fetchBinary: async () => new ArrayBuffer(8), fetchText: async () => '{}',+ resolveUrl: (path: string) => path } as Backend,+ });+ const old = await assets.acquireTyped('audio', 'edited.wav');+ audio = new AudioAPI(createMockBackend());+ audio.setBufferBudget(0);+ assets.invalidate('edited.wav');+ const current = await assets.acquireTyped('audio', 'edited.wav');+ const replacement = audio.getBufferHandle('edited.wav');+ old.release();+ expect(original.getBufferStats().bufferCount).toBe(0);+ expect(audio.getBufferHandle('edited.wav')).toBe(replacement);+ current.release();+ expect(audio.getBufferStats().bufferCount).toBe(0);+ });+it('preload lands in the warm cache (evictable), playable immediately', async () => {await audio.preload('sfx/a.mp3');expect(audio.getBufferStats()).toMatchObject({diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 65445ccae..8c2a0d07b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(audio): bind asset releases to retained buffer generations':+ { note: 'Old audio asset leases do not release replacement clips.' },'fix(audio): retire pending loads when clip sources change':{ note: 'Audio source updates retire pending decodes.' },'fix(audio): release decodes that finish after disposal':