Skip to content

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.

feat(assets): audio residency + unified refcounts + releaseGroup + memory-pressure trim

yhh486b944766eb
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index df89bbb45..45e3f36c6 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -170,7 +170,12 @@ Key facts:
never revived. The SDK owns the asset-level refcount (one pool reference per
cached texture); the pool owns residency. Surfaced to TS as
`setTextureBudget(bytes)` / `getResourceStats()`, with a default budget from
- `RuntimeConfig.textureCacheBudget` applied at engine init.
+ `RuntimeConfig.textureCacheBudget` applied at engine init. Decoded audio
+ buffers mirror the same lifecycle SDK-side (`AudioAPI` retain/release +
+ byte-budgeted warm cache, `RuntimeConfig.audioCacheBudget`). OS memory
+ warnings (`wx.onMemoryWarning` via the platform adapter) trim both warm
+ caches (`trimTextureCache` / `AudioAPI.trimBufferCache`) without touching
+ held resources.
### Other C++ subsystems
diff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdx
index 713141b55..5c47e14ba 100644
--- a/docs/astro/src/content/docs/guides/assets.mdx
+++ b/docs/astro/src/content/docs/guides/assets.mdx
@@ -78,8 +78,17 @@ progress — and it downloads before its assets load (on WeChat this triggers
const bundle = await assets.loadGroup('level2', (loaded, total) => {
console.log(`${loaded}/${total}`);
});
+
+// ...player leaves the area the group backs:
+assets.releaseGroup('level2');
```
+`releaseGroup` is the symmetric other half: every asset the group acquired is
+released through its type's canonical channel, so reference counting decides
+what happens — an asset another scene or group still holds survives, and one
+nobody holds drops to the evictable warm cache. Bouncing back into the area is
+then absorbed by the warm caches instead of the network.
+
`loadByLabel(...)` loads assets tagged with a label instead of a folder group.
This grouping is what maps onto [WeChat subpackages](/docs/guides/wechat/) for
on-demand download.
@@ -114,18 +123,25 @@ manifest. Along the way it can:
## Lifetime & reference counting
-Loaded GPU resources are **reference-counted**. When an entity that uses an asset
-is despawned, its references are released — but a released texture isn't
-destroyed immediately. It stays resident as an **evictable cache entry**, and if
-the same texture is loaded again (re-entering a scene, streaming an area back
-in) it is **revived in place** instead of re-fetched and re-decoded. A
-byte-budgeted LRU evicts the oldest unreferenced textures once resident VRAM
-exceeds the budget. You generally don't manage this by hand — reference and
-despawn entities normally.
-
-The budget defaults to **64 MB** (`RuntimeConfig.textureCacheBudget`, also
-settable as `textureCacheBudget` in the build config). Size it for your game
-with `setTextureBudget`, and watch residency with `getResourceStats`:
+Loaded assets are **reference-counted**: every `load*()` counts as one
+reference and needs a matching `release*()` (scene loading does both for you).
+An asset shared by two scenes survives the first scene's unload and is freed
+only when its last holder releases it.
+
+A released asset isn't destroyed immediately, either. Textures and decoded
+audio buffers stay resident as **evictable cache entries**, and if the same
+asset is loaded again (re-entering a scene, streaming an area back in) it is
+**revived in place** instead of re-fetched and re-decoded. A byte-budgeted LRU
+evicts the oldest unreferenced entries once residency exceeds the budget, and
+an OS memory warning drops the whole warm cache at once (held assets are
+untouched). You generally don't manage this by hand — reference and despawn
+entities normally.
+
+The texture budget defaults to **64 MB** (`RuntimeConfig.textureCacheBudget`,
+also settable as `textureCacheBudget` in the build config); decoded audio has
+its own **32 MB** mirror (`audioCacheBudget` — see the
+[audio guide](/docs/guides/audio/)). Size the texture budget for your game with
+`setTextureBudget`, and watch residency with `getResourceStats`:
```typescript
import { setTextureBudget, getResourceStats } from 'esengine';
diff --git a/docs/astro/src/content/docs/guides/audio.mdx b/docs/astro/src/content/docs/guides/audio.mdx
index 61138cffd..137717c5e 100644
--- a/docs/astro/src/content/docs/guides/audio.mdx
+++ b/docs/astro/src/content/docs/guides/audio.mdx
@@ -18,6 +18,13 @@ group). Each play returns an `AudioHandle` you can keep to adjust or stop that o
sound. For sounds tied to a place or an object, an `AudioSource` component plays
declaratively and (when `spatial`) attenuates by distance from the `AudioListener`.
+Decoded buffers live in a **byte-budgeted warm cache** (default 32 MB,
+`RuntimeConfig.audioCacheBudget` / build-config `audioCacheBudget`), the audio
+mirror of the texture budget: a buffer released by asset lifetime stays instantly
+playable and is revived without a re-fetch + re-decode, while the oldest unused
+buffers are dropped past the budget. On OS memory warnings the engine trims the
+whole warm cache automatically — sounds that are playing keep playing.
+
<Aside type="note">
Audio is registered automatically — no plugin to add. Browsers require a user
gesture before sound can start, so trigger the first playback from a tap or key.
@@ -54,6 +61,9 @@ it once ready.
| `preload(url)` | Decode and cache a clip ahead of time (async). |
| `preloadAll(urls)` | Preload an array of clips (async). |
| `getBufferHandle(url)` | The cached buffer for `url`, or `undefined`. |
+| `setBufferBudget(bytes)` | Override the warm-cache byte budget (`null` returns to the RuntimeConfig value; `0` disables the cache). |
+| `getBufferStats()` | Residency counters: `bufferCount`, `bufferBytes`, `bufferBudget`, `evictableCount`. |
+| `trimBufferCache()` | Free every unused cached buffer now (the engine calls this on OS memory warnings). |
## Controlling a playing sound
diff --git a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
index d4e074d7b..105f16137 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
@@ -72,8 +72,15 @@ assets.setManifest(manifest); // 通常运行时会替你设好
const bundle = await assets.loadGroup('level2', (loaded, total) => {
console.log(`${loaded}/${total}`);
});
+
+// ...玩家离开这个组对应的区域时:
+assets.releaseGroup('level2');
```
+`releaseGroup` 是对称的另一半:组里获取过的每个资源都经其类型的规范通道释放,由引用计数
+决定实际发生什么——别的场景或组还持有的资源会存活,没人持有的降级为可逐出热缓存。之后玩家
+折返该区域时由热缓存吸收,而不是重走网络。
+
`loadByLabel(...)` 按 label 标签加载资源,而不是按文件夹分组。正是这种分组映射到
[微信分包](/docs/zh-cn/guides/wechat/),实现按需下载。
@@ -102,14 +109,19 @@ const { failed } = await assets.preload(
## 生命周期与引用计数
-加载的 GPU 资源是**引用计数**的。当使用某资源的实体被销毁(despawn)时,它的引用被释放——
-但释放的纹理不会立即销毁:它以**可逐出缓存条目**的形式留驻,同一纹理再次被加载(重进场景、
-流式加载重新进入某区域)时会被**原地复活**,而不是重新下载和解码。一个按字节预算的 LRU
-在常驻显存超过预算时逐出最旧的未引用纹理。你一般不用手动管理——正常引用和销毁实体即可。
+加载的资源是**引用计数**的:每次 `load*()` 计一个引用,需要一次匹配的 `release*()`
+(场景加载会替你完成这两步)。被两个场景共享的资源在第一个场景卸载后仍然存活,只有最后一个
+持有者释放时才真正释放。
+
+释放的资源也不会立即销毁:纹理和解码后的音频缓冲区以**可逐出缓存条目**的形式留驻,同一资源
+再次被加载(重进场景、流式加载重新进入某区域)时会被**原地复活**,而不是重新下载和解码。
+一个按字节预算的 LRU 在驻留量超过预算时逐出最旧的未引用条目;收到系统内存警告时整个热缓存
+一次性清空(持有中的资源不受影响)。你一般不用手动管理——正常引用和销毁实体即可。
-预算默认 **64 MB**(`RuntimeConfig.textureCacheBudget`,也可在构建配置里用
-`textureCacheBudget` 设置)。用 `setTextureBudget` 按你的游戏调大小,用
-`getResourceStats` 观测驻留情况:
+纹理预算默认 **64 MB**(`RuntimeConfig.textureCacheBudget`,也可在构建配置里用
+`textureCacheBudget` 设置);解码音频有自己的 **32 MB** 镜像(`audioCacheBudget`,
+见[音频指南](/docs/zh-cn/guides/audio/))。用 `setTextureBudget` 按你的游戏调纹理预算大小,
+用 `getResourceStats` 观测驻留情况:
```typescript
import { setTextureBudget, getResourceStats } from 'esengine';
diff --git a/docs/astro/src/content/docs/zh-cn/guides/audio.mdx b/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
index 1aabeeda8..a08fcdb96 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
@@ -15,6 +15,12 @@ Estella 的音频通过 `Audio` 资源播放一次性音效和循环音乐,用
或停止这一个声音。对于绑定到某个位置或物体的声音,`AudioSource` 组件声明式地播放,并在
(`spatial`)开启时按与 `AudioListener` 的距离衰减。
+解码后的缓冲区放在一个**按字节预算的热缓存**里(默认 32 MB,
+`RuntimeConfig.audioCacheBudget`,构建配置里为 `audioCacheBudget`)——纹理预算的音频镜像:
+被资源生命周期释放的缓冲区仍可即时播放,再次加载时原地复活而不用重新下载和解码;超出预算时
+最旧的未使用缓冲区被丢弃。收到系统内存警告时引擎会自动清空整个热缓存——正在播放的声音不受
+影响。
+
<Aside type="note">
音频自动注册——无需加插件。浏览器要求先有用户手势才能开始播放,所以第一次播放要从点击或
按键触发。
@@ -50,6 +56,9 @@ const play = defineSystem([Res(Audio)], (audio) => {
| `preload(url)` | 提前解码并缓存一个片段(异步)。 |
| `preloadAll(urls)` | 预加载一组片段(异步)。 |
| `getBufferHandle(url)` | `url` 的已缓存缓冲区,或 `undefined`。 |
+| `setBufferBudget(bytes)` | 覆盖热缓存字节预算(`null` 回到 RuntimeConfig 的值;`0` 关闭缓存)。 |
+| `getBufferStats()` | 驻留计数:`bufferCount`、`bufferBytes`、`bufferBudget`、`evictableCount`。 |
+| `trimBufferCache()` | 立即释放所有未使用的缓存缓冲区(引擎在系统内存警告时会自动调用)。 |
## 控制正在播放的声音
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index f422f4313..b02c14618 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -88,4 +88,13 @@ export interface AssetLoader<T> {
readonly extensions: string[];
load(path: string, ctx: LoadContext): Promise<T>;
unload(asset: T): void;
+ /**
+ * Sever any residency identity the loader's subsystem keeps for `path`
+ * (hot reload: the source bytes changed, so a warm-cache entry must never
+ * be revived). Called by `Assets.invalidate` for every registered loader,
+ * whether or not the Assets-level cache held the path — the subsystem
+ * cache can outlive it. Returns true if anything was dropped. Optional:
+ * loaders whose results carry no out-of-Assets residency omit it.
+ */
+ invalidate?(path: string): boolean;
}
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index d45e0c891..8bb6b122b 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -165,6 +165,11 @@ export class Assets {
});
private textureRefCounts_ = new Map<string, number>();
private genericCache_ = new Map<string, AsyncCache<unknown>>();
+ /** Per-asset reference counts for the generic caches, keyed `type:path`.
+ * Same contract as textures: every load*() increments, every release*()
+ * decrements, and the loader's unload runs only at zero — so an asset
+ * shared by two scenes survives the first scene's unload. */
+ private genericRefCounts_ = new Map<string, number>();
private loadContext_: LoadContext | null = null;
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
@@ -437,6 +442,39 @@ export class Assets {
return bundle;
}
+ /**
+ * Release every asset {@link loadGroup} acquired for a group — the
+ * symmetric other half of on-demand delivery. Each asset goes through its
+ * type's canonical release channel, so reference counting decides what
+ * actually happens: an asset another scene or group still holds survives;
+ * one nobody holds drops to the evictable warm cache (textures, audio)
+ * or unloads. Call it when the player leaves the area the group backs;
+ * bouncing back is then absorbed by the warm caches instead of the
+ * network. Requires a manifest, like loadGroup; no-op without one.
+ */
+ releaseGroup(groupName: string): void {
+ const model = this.manifestModel_;
+ if (!model) {
+ log.warn('asset', `releaseGroup('${groupName}') called but no manifest is set`);
+ return;
+ }
+ for (const asset of model.assetsInGroup(groupName)) {
+ const path = this.resolveLoadPath_(asset.path);
+ switch (asset.type) {
+ case 'texture': this.releaseTexture(path); break;
+ case 'material': this.releaseTyped('material', path); break;
+ case 'bitmap-font': this.releaseTyped('font', path); break;
+ case 'prefab': this.releaseTyped('prefab', path); break;
+ case 'audio': this.releaseTyped('audio', path); break;
+ // Spine skeletons bind to spawned entities and are owned by
+ // the SpineAssetLoader / SpineManager lifecycle, not the
+ // generic cache — releasing them here could yank a skeleton
+ // out from under a live entity.
+ default: break;
+ }
+ }
+ }
+
/**
* Load one asset into the displayable bundle maps. Returns the in-flight
* promise for the four bundle-able types (texture / material / spine /
@@ -825,11 +863,19 @@ export class Assets {
const cache = this.genericCache_.get(type);
if (!cache) return;
const entry = cache.get(path);
- if (entry) {
- const loader = this.loaders_.get(type);
- loader?.unload(entry);
- cache.delete(path);
+ if (!entry) return;
+
+ const key = `${type}:${path}`;
+ const count = this.genericRefCounts_.get(key);
+ if (count === undefined) return;
+ if (count > 1) {
+ this.genericRefCounts_.set(key, count - 1);
+ return;
}
+ const loader = this.loaders_.get(type);
+ loader?.unload(entry);
+ cache.delete(path);
+ this.genericRefCounts_.delete(key);
}
/**
@@ -868,8 +914,16 @@ export class Assets {
}
// Generic caches: material / font / anim-clip / tilemap / timeline / audio / prefab.
- for (const cache of this.genericCache_.values()) {
+ for (const [type, cache] of this.genericCache_.entries()) {
if (cache.invalidate(path)) hit = true;
+ if (this.genericRefCounts_.delete(`${type}:${path}`)) hit = true;
+ }
+
+ // Loader-owned residency (e.g. the AudioAPI warm cache) can outlive
+ // the Assets-level entry — sever it unconditionally so a warm-cache
+ // revive can never serve stale bytes after a hot reload.
+ for (const loader of this.loaders_.values()) {
+ if (loader.invalidate?.(path)) hit = true;
}
if (hit) {
@@ -917,6 +971,7 @@ export class Assets {
cache.clearAll();
}
this.genericCache_.clear();
+ this.genericRefCounts_.clear();
}
// =========================================================================
@@ -1016,7 +1071,9 @@ export class Assets {
this.materialLoader_ = new MaterialAssetLoader();
this.register(this.materialLoader_);
this.register(new FontAssetLoader());
- this.register(new AudioAssetLoader());
+ // The audio loader needs the AudioAPI outside load() too (unload /
+ // invalidate have no LoadContext), so it shares Assets' lazy accessor.
+ this.register(new AudioAssetLoader(() => this.getAudio_()));
this.register(new AnimClipAssetLoader());
this.register(new TilemapAssetLoader());
this.register(new TilesetAssetLoader());
@@ -1043,9 +1100,12 @@ export class Assets {
this.genericCache_.set(type, cache);
}
- return cache.getOrLoad(path, () =>
+ const result = await (cache.getOrLoad(path, () =>
loader.load(path, this.getLoadContext_()),
- ) as Promise<T>;
+ ) as Promise<T>);
+ const key = `${type}:${path}`;
+ this.genericRefCounts_.set(key, (this.genericRefCounts_.get(key) ?? 0) + 1);
+ return result;
}
private getLoadContext_(): LoadContext {
diff --git a/sdk/src/asset/loaders/AudioAssetLoader.ts b/sdk/src/asset/loaders/AudioAssetLoader.ts
index 1414ab937..dabe11ec9 100644
--- a/sdk/src/asset/loaders/AudioAssetLoader.ts
+++ b/sdk/src/asset/loaders/AudioAssetLoader.ts
@@ -1,26 +1,43 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AssetLoader, LoadContext, AudioResult } from '../AssetLoader';
+import type { AudioAPI } from '../../audio/Audio';
import { log } from '../../logger';
export class AudioAssetLoader implements AssetLoader<AudioResult> {
readonly type = 'audio';
readonly extensions = ['.mp3', '.wav', '.ogg', '.m4a', '.aac'];
+ /** Same lazy audio accessor Assets uses — needed by unload/invalidate,
+ * which have no LoadContext. Defaults to "no audio" for bare setups. */
+ constructor(private readonly getAudio_: () => AudioAPI | null = () => null) {}
+
async load(path: string, ctx: LoadContext): Promise<AudioResult> {
const audio = ctx.getAudio();
if (!audio) {
log.warn('asset', `AudioAssetLoader: no Audio resource for "${path}" (AudioPlugin not installed?)`);
return { bufferId: path };
}
+ // 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 };
+ }
const buildPath = ctx.catalog.getBuildPath(path);
const buffer = await ctx.loadBinary(buildPath);
await audio.preloadFromData(path, buffer);
+ audio.retainBuffer(path);
return { bufferId: path };
}
- unload(_asset: AudioResult): void {
- // Audio buffers are owned by the app's AudioAPI and freed on
- // plugin teardown via `audio.dispose()`.
+ 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);
+ }
+
+ invalidate(path: string): boolean {
+ return this.getAudio_()?.invalidateBuffer(path) ?? false;
}
}
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index 4b116d3e7..67f481b9b 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -3,8 +3,34 @@
import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from './PlatformAudioBackend';
import type { AudioMixer } from './AudioMixer';
import { defineResource } from '../resource';
+import { RuntimeConfig } from '../defaults';
import { log } from '../logger';
+/**
+ * One decoded buffer's residency record. Mirrors the texture pool's
+ * three-state lifecycle: held (refCount > 0, pinned by Assets) →
+ * evictable (refCount 0, warm cache bounded by the byte budget) →
+ * evicted (backend buffer freed; a future load re-fetches).
+ */
+interface BufferEntry {
+ handle: AudioBufferHandle;
+ /** Decoded bytes; 0 = untracked (streaming backends), never budgeted. */
+ bytes: number;
+ /** Assets-held references. Direct play/preload entries stay at 0. */
+ refCount: number;
+}
+
+/** Buffer residency counters. See {@link AudioAPI.getBufferStats}. */
+export interface AudioBufferStats {
+ bufferCount: number;
+ /** Decoded bytes resident (held + evictable entries). */
+ bufferBytes: number;
+ /** The effective byte budget (0 = warm cache off). */
+ bufferBudget: number;
+ /** Warm-cache entries (refCount 0) awaiting revive or eviction. */
+ evictableCount: number;
+}
+
/**
* Per-app audio API. Each `App` owns an `AudioAPI` instance (created by
* `AudioPlugin.build()`), exposed via the `Audio` resource.
@@ -15,7 +41,11 @@ import { log } from '../logger';
export class AudioAPI {
private readonly backend_: PlatformAudioBackend;
private readonly mixer_: AudioMixer | null;
- private readonly bufferCache_ = new Map<string, AudioBufferHandle>();
+ private readonly bufferCache_ = new Map<string, BufferEntry>();
+ /** refCount==0 urls in eviction order (oldest first); access re-appends. */
+ private readonly evictOrder_ = new Set<string>();
+ private residentBytes_ = 0;
+ private bufferBudgetOverride_: number | null = null;
private bgmHandle_: AudioHandle | null = null;
private bgmVolume_ = 1.0;
private readonly fadeAnimIds_ = new Set<number>();
@@ -28,6 +58,140 @@ export class AudioAPI {
this.mixer_ = mixer;
}
+ // =========================================================================
+ // Buffer residency (held → evictable → evicted)
+ // =========================================================================
+
+ /** The effective warm-cache byte budget: an explicit override, else the
+ * live `RuntimeConfig.audioCacheBudget` (so build-config changes apply
+ * without plumbing). 0 disables the warm cache — a buffer is freed the
+ * moment its refCount reaches 0. */
+ get bufferBudget(): number {
+ return this.bufferBudgetOverride_ ?? RuntimeConfig.audioCacheBudget;
+ }
+
+ /** Override the warm-cache byte budget; `null` returns to RuntimeConfig. */
+ setBufferBudget(bytes: number | null): void {
+ this.bufferBudgetOverride_ = bytes === null ? null : Math.max(0, Math.floor(bytes));
+ this.enforceBudget_();
+ }
+
+ /**
+ * Pin a cached buffer: refCount + 1 (reviving an evictable entry back to
+ * held). Returns false on a miss — the caller must load and re-acquire.
+ * Every retain needs a matching {@link releaseBuffer}.
+ */
+ retainBuffer(url: string): boolean {
+ const entry = this.bufferCache_.get(url);
+ if (!entry) return false;
+ entry.refCount++;
+ this.evictOrder_.delete(url);
+ return true;
+ }
+
+ /**
+ * Unpin a buffer. At refCount 0 it becomes an evictable warm-cache entry
+ * (bounded by {@link bufferBudget}) — still instantly playable and
+ * revivable by {@link retainBuffer} — or is freed outright when the
+ * budget is 0.
+ */
+ releaseBuffer(url: string): void {
+ const entry = this.bufferCache_.get(url);
+ if (!entry || entry.refCount === 0) return;
+ if (--entry.refCount === 0) {
+ if (this.bufferBudget === 0) {
+ this.freeBuffer_(url, entry);
+ } else {
+ this.evictOrder_.add(url);
+ this.enforceBudget_();
+ }
+ }
+ }
+
+ /**
+ * Drop a buffer whose source bytes changed (hot reload) so no future play
+ * or load serves stale audio. Safe while sounds are playing — live
+ * sources keep their own reference to the decoded data; only the cache
+ * entry goes, and the next play/load re-fetches fresh bytes. Returns
+ * true if the url was cached.
+ */
+ invalidateBuffer(url: string): boolean {
+ const entry = this.bufferCache_.get(url);
+ if (!entry) return false;
+ this.freeBuffer_(url, entry);
+ return true;
+ }
+
+ /**
+ * Free every evictable warm-cache buffer now (memory pressure). Held
+ * buffers and the budget are untouched; the cache refills as buffers are
+ * released afterwards. Returns the number of buffers freed.
+ */
+ trimBufferCache(): number {
+ let freed = 0;
+ for (const url of [...this.evictOrder_]) {
+ const entry = this.bufferCache_.get(url);
+ if (entry) {
+ this.freeBuffer_(url, entry);
+ freed++;
+ }
+ }
+ return freed;
+ }
+
+ /** Buffer residency counters — the observability side of the budget. */
+ getBufferStats(): AudioBufferStats {
+ return {
+ bufferCount: this.bufferCache_.size,
+ bufferBytes: this.residentBytes_,
+ bufferBudget: this.bufferBudget,
+ evictableCount: this.evictOrder_.size,
+ };
+ }
+
+ /** Register a decoded buffer as an evictable warm-cache entry. The budget
+ * is enforced against the OLD warm entries before the new one joins the
+ * eviction pool — mirroring the C++ pool's add(), where a just-created
+ * resource can't be the one evicted to make room for itself (a caller
+ * about to pin or play it would find it already gone). */
+ private insertEntry_(url: string, handle: AudioBufferHandle): void {
+ const entry: BufferEntry = { handle, bytes: handle.bytes ?? 0, refCount: 0 };
+ this.bufferCache_.set(url, entry);
+ this.residentBytes_ += entry.bytes;
+ this.enforceBudget_();
+ this.evictOrder_.add(url);
+ }
+
+ /** Cache lookup for playback: refreshes the LRU position of an evictable
+ * entry so frequently-played warm sounds aren't the first to go. */
+ private lookupBuffer_(url: string): AudioBufferHandle | undefined {
+ const entry = this.bufferCache_.get(url);
+ if (!entry) return undefined;
+ if (entry.refCount === 0 && this.evictOrder_.delete(url)) {
+ this.evictOrder_.add(url);
+ }
+ return entry.handle;
+ }
+
+ private freeBuffer_(url: string, entry: BufferEntry): void {
+ this.backend_.unloadBuffer(entry.handle);
+ this.bufferCache_.delete(url);
+ this.evictOrder_.delete(url);
+ this.residentBytes_ -= entry.bytes;
+ }
+
+ /** Evict oldest warm-cache entries until resident bytes fit the budget.
+ * Held (refCount > 0) entries are never evicted. */
+ private enforceBudget_(): void {
+ const budget = this.bufferBudget;
+ if (budget === 0) return;
+ for (const url of this.evictOrder_) {
+ if (this.residentBytes_ <= budget) break;
+ const entry = this.bufferCache_.get(url);
+ if (entry) this.freeBuffer_(url, entry);
+ }
+ }
+
setAssetResolver(resolver: (url: string) => ArrayBuffer | null): void {
this.assetResolver_ = resolver;
}
@@ -48,7 +212,7 @@ export class AudioAPI {
}
}
const buffer = await this.backend_.loadBuffer(this.resolveUrl_(url));
- this.bufferCache_.set(url, buffer);
+ if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
}
async preloadAll(urls: string[]): Promise<void> {
@@ -58,7 +222,7 @@ export class AudioAPI {
async preloadFromData(url: string, data: ArrayBuffer): Promise<void> {
if (this.bufferCache_.has(url)) return;
const buffer = await this.backend_.loadBufferFromData(url, data);
- this.bufferCache_.set(url, buffer);
+ if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
}
playSFX(url: string, config?: {
@@ -74,12 +238,12 @@ export class AudioAPI {
pan: config?.pan,
priority: config?.priority ?? 0,
};
- const buffer = this.bufferCache_.get(url);
+ const buffer = this.lookupBuffer_(url);
if (!buffer) {
const pending = this.createDeferredHandle_();
this.preload(url).then(() => {
if (this.disposed_) return;
- const buf = this.bufferCache_.get(url);
+ const buf = this.lookupBuffer_(url);
if (buf) {
pending.resolve(this.backend_.play(buf, playConfig));
}
@@ -124,13 +288,13 @@ export class AudioAPI {
}
};
- const buffer = this.bufferCache_.get(url);
+ const buffer = this.lookupBuffer_(url);
if (buffer) {
play(buffer);
} else {
this.preload(url).then(() => {
if (this.disposed_) return;
- const buf = this.bufferCache_.get(url);
+ const buf = this.lookupBuffer_(url);
if (buf) {
play(buf);
}
@@ -199,7 +363,7 @@ export class AudioAPI {
}
getBufferHandle(url: string): AudioBufferHandle | undefined {
- return this.bufferCache_.get(url);
+ return this.lookupBuffer_(url);
}
/** Fill `out` with the master output's frequency spectrum (0-255 per bin,
@@ -219,10 +383,12 @@ export class AudioAPI {
this.bgmHandle_.stop();
this.bgmHandle_ = null;
}
- for (const handle of this.bufferCache_.values()) {
- this.backend_?.unloadBuffer(handle);
+ for (const entry of this.bufferCache_.values()) {
+ this.backend_?.unloadBuffer(entry.handle);
}
this.bufferCache_.clear();
+ this.evictOrder_.clear();
+ this.residentBytes_ = 0;
this.backend_?.dispose();
}
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
index ab06f412b..bc320ae18 100644
--- a/sdk/src/audio/AudioPlugin.ts
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -7,7 +7,7 @@ import { Res, Time, type TimeData } from '../resource';
import { Audio, AudioAPI } from './Audio';
import { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
import { WorldTransform, type WorldTransformData } from '../component';
-import { getPlatform } from '../platform/base';
+import { getPlatform, platformOnMemoryWarning } from '../platform/base';
import { calculateAttenuation, calculatePanning, type SpatialAudioConfig, AttenuationModel } from './SpatialAudio';
import type { AudioHandle } from './PlatformAudioBackend';
import { isEditor, isPlayMode } from '../env';
@@ -26,6 +26,7 @@ export class AudioPlugin implements Plugin {
private activeSourceHandles_: Map<number, AudioHandle> | null = null;
private playedEntities_: Set<number> | null = null;
private audio_: AudioAPI | null = null;
+ private offMemoryWarning_: (() => void) | null = null;
constructor(config: AudioPluginConfig = {}) {
this.config_ = config;
@@ -44,6 +45,13 @@ export class AudioPlugin implements Plugin {
this.audio_ = audio;
app.insertResource(Audio, audio);
+ // OS memory pressure → drop the decoded-buffer warm cache. Held
+ // buffers keep playing; re-fetch cost returns only for evicted ones.
+ this.offMemoryWarning_ = platformOnMemoryWarning(() => {
+ const freed = audio.trimBufferCache();
+ if (freed > 0) log.info('audio', `memory warning: trimmed ${freed} cached buffer(s)`);
+ });
+
if (mixer) {
if (config.masterVolume !== undefined) mixer.master.volume = config.masterVolume;
if (config.musicVolume !== undefined) mixer.music.volume = config.musicVolume;
@@ -188,6 +196,8 @@ export class AudioPlugin implements Plugin {
}
cleanup(): void {
+ this.offMemoryWarning_?.();
+ this.offMemoryWarning_ = null;
this.stopAllSources();
this.audio_?.dispose();
this.audio_ = null;
diff --git a/sdk/src/audio/PlatformAudioBackend.ts b/sdk/src/audio/PlatformAudioBackend.ts
index d0660e014..15278f712 100644
--- a/sdk/src/audio/PlatformAudioBackend.ts
+++ b/sdk/src/audio/PlatformAudioBackend.ts
@@ -21,6 +21,13 @@ export interface AudioHandle {
export interface AudioBufferHandle {
readonly id: number;
readonly duration: number;
+ /**
+ * Decoded size in bytes, for the audio residency budget. Backends that
+ * hold real decoded PCM (WebAudio) report it; streaming backends (WeChat
+ * InnerAudioContext plays from file) omit it — 0/undefined means
+ * untracked, and untracked entries never count against the budget.
+ */
+ readonly bytes?: number;
}
export interface PlayConfig {
diff --git a/sdk/src/audio/WebAudioBackend.ts b/sdk/src/audio/WebAudioBackend.ts
index ac349deeb..7e461f501 100644
--- a/sdk/src/audio/WebAudioBackend.ts
+++ b/sdk/src/audio/WebAudioBackend.ts
@@ -132,6 +132,11 @@ class WebAudioHandle implements AudioHandle {
}
}
+/** Decoded PCM size of a WebAudio buffer: frames × channels × 4 (Float32). */
+function decodedBytes(buf: AudioBuffer): number {
+ return buf.length * buf.numberOfChannels * 4;
+}
+
export class WebAudioBackend implements PlatformAudioBackend {
readonly name = 'WebAudio';
@@ -195,7 +200,7 @@ export class WebAudioBackend implements PlatformAudioBackend {
const existingId = this.urlToId_.get(url);
if (existingId !== undefined && this.buffers_.has(existingId)) {
const buf = this.buffers_.get(existingId)!;
- return { id: existingId, duration: buf.duration };
+ return { id: existingId, duration: buf.duration, bytes: decodedBytes(buf) };
}
const inFlight = this.loadingUrls_.get(url);
@@ -218,7 +223,7 @@ export class WebAudioBackend implements PlatformAudioBackend {
const existingId = this.urlToId_.get(url);
if (existingId !== undefined && this.buffers_.has(existingId)) {
const buf = this.buffers_.get(existingId)!;
- return { id: existingId, duration: buf.duration };
+ return { id: existingId, duration: buf.duration, bytes: decodedBytes(buf) };
}
let audioBuffer: AudioBuffer;
@@ -232,7 +237,7 @@ export class WebAudioBackend implements PlatformAudioBackend {
this.buffers_.set(id, audioBuffer);
this.urlToId_.set(url, id);
- return { id, duration: audioBuffer.duration };
+ return { id, duration: audioBuffer.duration, bytes: decodedBytes(audioBuffer) };
}
private async doLoadBuffer_(url: string): Promise<AudioBufferHandle> {
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 8c46fc64b..ee4a1760f 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -70,7 +70,7 @@ export {
// Resource budget (VRAM)
// =============================================================================
-export { setTextureBudget, getResourceStats, type ResourceStats } from './resourceManager';
+export { setTextureBudget, getResourceStats, trimTextureCache, type ResourceStats } from './resourceManager';
// =============================================================================
// Scene
diff --git a/sdk/src/corePlugin.ts b/sdk/src/corePlugin.ts
index dd2a3e44e..64c759dd4 100644
--- a/sdk/src/corePlugin.ts
+++ b/sdk/src/corePlugin.ts
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { Plugin } from './app';
-import { initResourceManager, shutdownResourceManager, setTextureBudget } from './resourceManager';
+import { initResourceManager, shutdownResourceManager, setTextureBudget, trimTextureCache } from './resourceManager';
+import { platformOnMemoryWarning } from './platform/base';
import { RuntimeConfig } from './defaults';
import { initDrawAPI, shutdownDrawAPI } from './draw';
import { clearDrawCallbacks } from './customDraw';
@@ -12,6 +13,8 @@ import { initRendererAPI, shutdownRendererAPI } from './renderer';
import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';
import { CameraView, CameraViewApi } from './camera/Camera';
+let offMemoryWarning: (() => void) | null = null;
+
export const corePlugin: Plugin = {
name: 'engineCore',
@@ -22,6 +25,11 @@ export const corePlugin: Plugin = {
// pool up to this byte budget, so the next load revives them instead of
// re-decoding. Without this call the pool default (0) frees at once.
setTextureBudget(RuntimeConfig.textureCacheBudget);
+ // OS memory pressure → drop the texture warm cache. Held textures are
+ // untouched; only the revive shortcut is sacrificed until it refills.
+ offMemoryWarning = platformOnMemoryWarning(() => {
+ trimTextureCache();
+ });
initDrawAPI(module);
initGeometryAPI(module);
initMaterialAPI(module);
@@ -32,6 +40,8 @@ export const corePlugin: Plugin = {
},
cleanup() {
+ offMemoryWarning?.();
+ offMemoryWarning = null;
clearDrawCallbacks();
shutdownGLDebugAPI();
shutdownRendererAPI();
diff --git a/sdk/src/defaults.ts b/sdk/src/defaults.ts
index 200526d9d..3bb438f96 100644
--- a/sdk/src/defaults.ts
+++ b/sdk/src/defaults.ts
@@ -35,6 +35,14 @@ export const RuntimeConfig = {
* re-fetching + re-decoding. 0 turns the cache off (free at refcount 0).
*/
textureCacheBudget: 64 * 1024 * 1024,
+ /**
+ * Decoded audio-buffer byte budget — the audio mirror of
+ * textureCacheBudget. Released buffers stay as an evictable warm cache
+ * (instantly playable, revived without re-fetch + re-decode) and the
+ * oldest are dropped past this budget. Read live by AudioAPI, so changes
+ * apply without re-init. 0 turns the warm cache off.
+ */
+ audioCacheBudget: 32 * 1024 * 1024,
};
export function applyRuntimeConfig(components: {
@@ -66,6 +74,7 @@ export interface RuntimeBuildConfig {
assetLoadTimeout?: number;
assetFailureCooldown?: number;
textureCacheBudget?: number;
+ audioCacheBudget?: number;
}
/** Canvas scale-mode name → value. Canonical names are single-sourced from the
@@ -123,4 +132,8 @@ export function applyBuildRuntimeConfig(app: { setMaxDeltaTime(v: number): void;
// default budget — push the configured value through to the pool.
if (getResourceManager()) setTextureBudget(config.textureCacheBudget);
}
+ if (config.audioCacheBudget !== undefined) {
+ // AudioAPI reads this live at every budget check — no push needed.
+ RuntimeConfig.audioCacheBudget = config.audioCacheBudget;
+ }
}
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index 5abf40798..47335188d 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -120,6 +120,15 @@ export function platformLoadSubpackage(name: string): Promise<void> {
return p.loadSubpackage ? p.loadSubpackage(name) : Promise.resolve();
}
+/** Subscribe to OS memory-pressure warnings (wx.onMemoryWarning on WeChat).
+ * Returns an unsubscribe. On platforms without a pressure signal the callback
+ * simply never fires. Tolerates an uninitialized platform (tests). */
+export function platformOnMemoryWarning(callback: () => void): () => void {
+ if (!isPlatformInitialized()) return () => {};
+ const p = getPlatform();
+ return p.onMemoryWarning ? p.onMemoryWarning(callback) : () => {};
+}
+
export function platformDevicePixelRatio(): number {
if (currentPlatform) {
return currentPlatform.devicePixelRatio();
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index 0cbdac7a3..87e04e519 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -34,6 +34,7 @@ export {
platformNow,
platformCreateAudioBackend,
platformLoadSubpackage,
+ platformOnMemoryWarning,
platformDevicePixelRatio,
} from './base';
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 120299415..a94bb698f 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -124,6 +124,11 @@ export interface PlatformAdapter {
* concept (web) omit it and lazy groups load directly from their URLs. */
loadSubpackage?(name: string): Promise<void>;
+ /** Subscribe to OS memory-pressure warnings; returns an unsubscribe.
+ * WeChat → wx.onMemoryWarning; platforms without a pressure signal (web)
+ * omit it. Residency caches subscribe to drop their evictable entries. */
+ onMemoryWarning?(callback: () => void): () => void;
+
devicePixelRatio(): number;
getStorageItem(key: string): string | null;
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index 84ae34112..03644fddb 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -80,6 +80,12 @@ class WeChatPlatformAdapter implements PlatformAdapter {
});
}
+ onMemoryWarning(callback: () => void): () => void {
+ const listener = () => callback();
+ wx.onMemoryWarning(listener);
+ return () => wx.offMemoryWarning(listener);
+ }
+
createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
const canvas = wx.createCanvas() as unknown as HTMLCanvasElement;
canvas.width = width;
diff --git a/sdk/src/resourceManager.ts b/sdk/src/resourceManager.ts
index d4c7d20bb..d831789d2 100644
--- a/sdk/src/resourceManager.ts
+++ b/sdk/src/resourceManager.ts
@@ -98,6 +98,18 @@ export function getResourceStats(): ResourceStats | null {
return rm_.getResourceStats();
}
+/**
+ * Free every evictable cached texture now (memory pressure). Held textures
+ * and the budget are untouched; the warm cache refills as textures are
+ * released afterwards. The engine calls this on OS memory warnings — call it
+ * yourself before a known memory spike (e.g. a huge one-off allocation).
+ * Returns the number of textures freed (0 when uninitialized / mocked).
+ */
+export function trimTextureCache(): number {
+ if (!rm_ || typeof rm_.trimTextureCache !== 'function') return 0;
+ return rm_.trimTextureCache();
+}
+
export function evictTextureDimensions(handle: number): void {
dimsCache_.delete(handle);
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index f54d70238..d905ad66f 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -54,6 +54,7 @@ export interface CppResourceManager {
setTextureBudget(bytes: number): void;
acquireTextureByPath(path: string): number;
invalidateTexturePath(path: string): boolean;
+ trimTextureCache(): number;
getResourceStats(): {
shaderCount: number;
textureCount: number;
diff --git a/sdk/tests/asset-refcount-release.test.ts b/sdk/tests/asset-refcount-release.test.ts
new file mode 100644
index 000000000..62efcdbca
--- /dev/null
+++ b/sdk/tests/asset-refcount-release.test.ts
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file asset-refcount-release.test.ts
+ * @brief Generic-cache reference counting + group lifecycle symmetry:
+ * every load*() needs a matching release*(), an asset shared by two
+ * holders survives the first release, released audio revives from
+ * the AudioAPI warm cache without a re-fetch, and releaseGroup is
+ * the symmetric other half of loadGroup.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { AudioAPI } from '../src/audio/Audio';
+import type { Backend } from '../src/asset/Backend';
+import type { AddressableManifest } from '../src/asset/AddressableManifest';
+import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from '../src/audio/PlatformAudioBackend';
+
+vi.mock('../src/resourceManager', () => ({
+ requireResourceManager: () => ({
+ createTexture: vi.fn(() => 42),
+ registerExternalTexture: vi.fn(() => 42),
+ releaseTexture: vi.fn(),
+ getTextureGLId: vi.fn(() => 1),
+ registerTextureWithPath: vi.fn(),
+ acquireTextureByPath: vi.fn(() => 0),
+ invalidateTexturePath: vi.fn(() => false),
+ getTextureDimensions: vi.fn(() => ({ width: 64, height: 64 })),
+ }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+vi.mock('../src/platform', () => ({
+ platformCreateCanvas: vi.fn(),
+ platformCreateImage: vi.fn(),
+ platformFetch: vi.fn(),
+ platformReadFile: vi.fn(),
+ platformReadTextFile: vi.fn(),
+ platformFileExists: vi.fn(),
+ platformLoadSubpackage: vi.fn(async () => {}),
+}));
+
+interface MockAudioBackend extends PlatformAudioBackend {
+ decodes: string[];
+ unloaded: number[];
+}
+
+function createAudioBackend(): MockAudioBackend {
+ let nextId = 0;
+ const playHandle: AudioHandle = {
+ id: 0, stop() {}, pause() {}, resume() {},
+ setVolume() {}, setPan() {}, setLoop() {}, setPlaybackRate() {},
+ isPlaying: false, currentTime: 0, duration: 1,
+ };
+ const backend: MockAudioBackend = {
+ name: 'mock', mixer: null, isReady: true,
+ decodes: [], unloaded: [],
+ initialize: async () => {},
+ ensureResumed: async () => {},
+ loadBuffer: async (url: string): Promise<AudioBufferHandle> => {
+ backend.decodes.push(url);
+ return { id: ++nextId, duration: 1, bytes: 100 };
+ },
+ loadBufferFromData: async (url: string): Promise<AudioBufferHandle> => {
+ backend.decodes.push(url);
+ return { id: ++nextId, duration: 1, bytes: 100 };
+ },
+ unloadBuffer: (handle: AudioBufferHandle) => { backend.unloaded.push(handle.id); },
+ play: () => playHandle,
+ suspend() {}, resume() {}, dispose() {},
+ };
+ return backend;
+}
+
+const mockModule = {
+ _malloc: vi.fn(() => 0),
+ _free: vi.fn(),
+ HEAPU8: new Uint8Array(1024),
+ GL: null,
+ FS: null,
+} as never;
+
+const AUDIO = 'sfx/coin.mp3';
+
+describe('generic-cache refcounts + releaseGroup', () => {
+ let assets: Assets;
+ let audioBackend: MockAudioBackend;
+ let audio: AudioAPI;
+ let fetchBinary: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ audioBackend = createAudioBackend();
+ audio = new AudioAPI(audioBackend);
+ audio.setBufferBudget(1024 * 1024);
+ fetchBinary = vi.fn(async () => new ArrayBuffer(8));
+ const backend: Backend = {
+ fetchBinary,
+ fetchText: vi.fn(async () => '{}'),
+ resolveUrl: (path: string) => `http://test/${path}`,
+ } as unknown as Backend;
+ assets = Assets.create({ backend, module: mockModule, getAudio: () => audio });
+ });
+
+ it('an asset loaded by two holders survives the first release', async () => {
+ await assets.loadAudio(AUDIO); // holder 1 (e.g. scene A)
+ await assets.loadAudio(AUDIO); // holder 2 (e.g. additive scene B)
+ expect(audioBackend.decodes).toHaveLength(1); // one decode, shared
+
+ assets.releaseAudio(AUDIO); // scene A unloads
+ expect(audio.getBufferStats().evictableCount).toBe(0); // still pinned by B
+
+ assets.releaseAudio(AUDIO); // scene B unloads
+ expect(audio.getBufferStats().evictableCount).toBe(1); // now warm cache
+ expect(audioBackend.unloaded).toEqual([]); // retained, not freed
+ });
+
+ it('a released audio buffer revives from the warm cache without re-fetching', async () => {
+ await assets.loadAudio(AUDIO);
+ assets.releaseAudio(AUDIO);
+ expect(audio.getBufferStats().evictableCount).toBe(1);
+
+ await assets.loadAudio(AUDIO); // revive: no network, no decode
+ expect(fetchBinary).toHaveBeenCalledTimes(1);
+ expect(audioBackend.decodes).toHaveLength(1);
+ expect(audio.getBufferStats().evictableCount).toBe(0); // held again
+ });
+
+ it('invalidate severs the audio residency so a fresh load re-fetches', async () => {
+ await assets.loadAudio(AUDIO);
+ assets.releaseAudio(AUDIO);
+
+ expect(assets.invalidate(AUDIO)).toBe(true);
+ expect(audioBackend.unloaded).toHaveLength(1); // stale buffer dropped
+
+ await assets.loadAudio(AUDIO);
+ expect(fetchBinary).toHaveBeenCalledTimes(2);
+ expect(audioBackend.decodes).toHaveLength(2);
+ });
+
+ it('releaseGroup mirrors loadGroup through the same typed release channels', async () => {
+ const manifest: AddressableManifest = {
+ version: '2.0',
+ groups: {
+ sfx: {
+ bundleMode: 'local',
+ labels: [],
+ assets: {
+ [AUDIO]: { path: AUDIO, type: 'audio', size: 8, labels: [] },
+ },
+ },
+ },
+ };
+ assets.setManifest(manifest);
+
+ await assets.loadGroup('sfx');
+ expect(audioBackend.decodes).toHaveLength(1);
+ expect(audio.getBufferStats().evictableCount).toBe(0); // group holds it
+
+ assets.releaseGroup('sfx');
+ expect(audio.getBufferStats().evictableCount).toBe(1); // warm cache
+ expect(audioBackend.unloaded).toEqual([]);
+
+ // Bouncing back into the area: revived, not re-downloaded.
+ await assets.loadGroup('sfx');
+ expect(fetchBinary).toHaveBeenCalledTimes(1);
+ expect(audioBackend.decodes).toHaveLength(1);
+ });
+
+ it('releaseGroup without a manifest is a warning no-op', () => {
+ expect(() => assets.releaseGroup('nope')).not.toThrow();
+ });
+});
diff --git a/sdk/tests/audio-residency.test.ts b/sdk/tests/audio-residency.test.ts
new file mode 100644
index 000000000..ca5021f92
--- /dev/null
+++ b/sdk/tests/audio-residency.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file audio-residency.test.ts
+ * @brief AudioAPI buffer residency: the audio mirror of the texture pool's
+ * held → evictable → evicted lifecycle. Retain/release, byte-budgeted
+ * LRU eviction (with access refreshing recency), hot-reload
+ * invalidation, and the memory-pressure trim.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { AudioAPI } from '../src/audio/Audio';
+import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from '../src/audio/PlatformAudioBackend';
+
+interface MockBackend extends PlatformAudioBackend {
+ loads: string[];
+ unloaded: number[];
+}
+
+function createMockBackend(bytesPerBuffer = 100): MockBackend {
+ let nextId = 0;
+ const playHandle: AudioHandle = {
+ id: 0,
+ stop() {}, pause() {}, resume() {},
+ setVolume() {}, setPan() {}, setLoop() {}, setPlaybackRate() {},
+ isPlaying: false, currentTime: 0, duration: 1,
+ };
+ const backend: MockBackend = {
+ name: 'mock',
+ mixer: null,
+ isReady: true,
+ loads: [],
+ unloaded: [],
+ initialize: async () => {},
+ ensureResumed: async () => {},
+ loadBuffer: async (url: string): Promise<AudioBufferHandle> => {
+ backend.loads.push(url);
+ return { id: ++nextId, duration: 1, bytes: bytesPerBuffer };
+ },
+ loadBufferFromData: async (url: string): Promise<AudioBufferHandle> => {
+ backend.loads.push(url);
+ return { id: ++nextId, duration: 1, bytes: bytesPerBuffer };
+ },
+ unloadBuffer: (handle: AudioBufferHandle) => { backend.unloaded.push(handle.id); },
+ play: () => playHandle,
+ suspend() {}, resume() {}, dispose() {},
+ };
+ return backend;
+}
+
+vi.mock('../src/platform', () => ({
+ platformCreateCanvas: vi.fn(),
+ platformCreateImage: vi.fn(),
+ platformFetch: vi.fn(),
+ platformReadFile: vi.fn(),
+ platformReadTextFile: vi.fn(),
+ platformFileExists: vi.fn(),
+}));
+
+describe('AudioAPI buffer residency', () => {
+ let backend: MockBackend;
+ let audio: AudioAPI;
+
+ beforeEach(() => {
+ backend = createMockBackend();
+ audio = new AudioAPI(backend);
+ audio.setBufferBudget(1000);
+ });
+
+ it('preload lands in the warm cache (evictable), playable immediately', async () => {
+ await audio.preload('sfx/a.mp3');
+ expect(audio.getBufferStats()).toMatchObject({
+ bufferCount: 1, bufferBytes: 100, evictableCount: 1,
+ });
+ expect(audio.getBufferHandle('sfx/a.mp3')).toBeDefined();
+ });
+
+ it('retain pins, release returns to the warm cache, revive skips the backend', async () => {
+ await audio.preload('sfx/a.mp3');
+ expect(audio.retainBuffer('sfx/a.mp3')).toBe(true);
+ expect(audio.getBufferStats().evictableCount).toBe(0);
+
+ audio.releaseBuffer('sfx/a.mp3');
+ expect(audio.getBufferStats().evictableCount).toBe(1);
+ expect(backend.unloaded).toEqual([]); // retained, not freed
+
+ expect(audio.retainBuffer('sfx/a.mp3')).toBe(true); // revive
+ expect(backend.loads).toHaveLength(1); // no second decode
+ });
+
+ it('budget 0 frees at release instead of caching', async () => {
+ audio.setBufferBudget(0);
+ await audio.preload('sfx/a.mp3');
+ audio.retainBuffer('sfx/a.mp3');
+ audio.releaseBuffer('sfx/a.mp3');
+ expect(backend.unloaded).toHaveLength(1);
+ expect(audio.getBufferStats().bufferCount).toBe(0);
+ expect(audio.retainBuffer('sfx/a.mp3')).toBe(false);
+ });
+
+ it('evicts oldest warm-cache entries past the budget; access refreshes recency', async () => {
+ audio.setBufferBudget(250);
+ await audio.preload('sfx/a.mp3');
+ await audio.preload('sfx/b.mp3');
+ audio.getBufferHandle('sfx/a.mp3'); // touch a → b is now oldest
+
+ await audio.preload('sfx/c.mp3'); // 300 > 250 → evict b
+ expect(audio.getBufferHandle('sfx/b.mp3')).toBeUndefined();
+ expect(audio.getBufferHandle('sfx/a.mp3')).toBeDefined();
+ expect(audio.getBufferHandle('sfx/c.mp3')).toBeDefined();
+ expect(audio.getBufferStats().bufferBytes).toBe(200);
+ });
+
+ it('never evicts held buffers, even far over budget', async () => {
+ audio.setBufferBudget(50);
+ await audio.preload('sfx/a.mp3');
+ audio.retainBuffer('sfx/a.mp3');
+ await audio.preload('sfx/b.mp3');
+ audio.retainBuffer('sfx/b.mp3');
+ expect(audio.getBufferStats().bufferBytes).toBe(200);
+ expect(backend.unloaded).toEqual([]);
+ });
+
+ it('invalidate drops even a held buffer so stale bytes are never served', async () => {
+ await audio.preload('sfx/a.mp3');
+ audio.retainBuffer('sfx/a.mp3');
+ expect(audio.invalidateBuffer('sfx/a.mp3')).toBe(true);
+ expect(backend.unloaded).toHaveLength(1);
+ expect(audio.retainBuffer('sfx/a.mp3')).toBe(false);
+ expect(audio.invalidateBuffer('sfx/a.mp3')).toBe(false);
+ });
+
+ it('trimBufferCache frees only the warm cache and lets it refill', async () => {
+ await audio.preload('sfx/held.mp3');
+ audio.retainBuffer('sfx/held.mp3');
+ await audio.preload('sfx/warm1.mp3');
+ await audio.preload('sfx/warm2.mp3');
+
+ expect(audio.trimBufferCache()).toBe(2);
+ expect(audio.getBufferStats()).toMatchObject({ bufferCount: 1, evictableCount: 0 });
+
+ audio.releaseBuffer('sfx/held.mp3'); // cache refills after the trim
+ expect(audio.getBufferStats().evictableCount).toBe(1);
+ });
+});
diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.ts
index d4b5e590f..339227767 100644
--- a/sdk/tests/mocks/wasm.ts
+++ b/sdk/tests/mocks/wasm.ts
@@ -125,6 +125,7 @@ export function createMockModule(): ESEngineModule {
registerTextureWithPath: () => {},
acquireTextureByPath: () => 0,
invalidateTexturePath: () => false,
+ trimTextureCache: () => 0,
getResourceStats: () => ({
shaderCount: 0, textureCount: 0, vertexBufferCount: 0, indexBufferCount: 0,
cacheHits: 0, cacheMisses: 0,
diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cpp
index 711c2a3ac..802d1bd07 100644
--- a/src/esengine/bindings/ResourceManagerBindings.cpp
+++ b/src/esengine/bindings/ResourceManagerBindings.cpp
@@ -98,6 +98,10 @@ bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string&
return rm.invalidateTexturePath(path);
}
+u32 rm_trimTextureCache(resource::ResourceManager& rm) {
+ return static_cast<u32>(rm.trimTextureCache());
+}
+
emscripten::val rm_getResourceStats(resource::ResourceManager& rm) {
const auto st = rm.getStats();
auto result = emscripten::val::object();
diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hpp
index 8da1fd0e3..f17ebc16b 100644
--- a/src/esengine/bindings/ResourceManagerBindings.hpp
+++ b/src/esengine/bindings/ResourceManagerBindings.hpp
@@ -28,6 +28,7 @@ void rm_registerTextureWithPath(resource::ResourceManager& rm, u32 handleId, con
void rm_setTextureBudget(resource::ResourceManager& rm, u32 bytes);
u32 rm_acquireTextureByPath(resource::ResourceManager& rm, const std::string& path);
bool rm_invalidateTexturePath(resource::ResourceManager& rm, const std::string& path);
+u32 rm_trimTextureCache(resource::ResourceManager& rm);
emscripten::val rm_getResourceStats(resource::ResourceManager& rm);
void rm_releaseShader(resource::ResourceManager& rm, u32 handleId);
u32 rm_getShaderRefCount(resource::ResourceManager& rm, u32 handleId);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index e0802d872..a52f91f95 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -408,6 +408,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
.function("setTextureBudget", &esengine::rm_setTextureBudget)
.function("acquireTextureByPath", &esengine::rm_acquireTextureByPath)
.function("invalidateTexturePath", &esengine::rm_invalidateTexturePath)
+ .function("trimTextureCache", &esengine::rm_trimTextureCache)
.function("getResourceStats", &esengine::rm_getResourceStats)
#ifdef ES_ENABLE_BITMAP_TEXT
.function("loadBitmapFont", &esengine::rm_loadBitmapFont)
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 567946db4..a3f314b8e 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -233,6 +233,10 @@ bool ResourceManager::invalidateTexturePath(const std::string& path) {
return textures_.invalidatePath(path);
}
+usize ResourceManager::trimTextureCache() {
+ return textures_.trimEvictables();
+}
+
TextureHandle ResourceManager::loadTextureByGUID(const std::string& guid, const std::string& path) {
auto it = guidToTexture_.find(guid);
if (it != guidToTexture_.end() && it->second.isValid()) {
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index b072ec39c..df675fd60 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -294,6 +294,13 @@ public:
*/
bool invalidateTexturePath(const std::string& path);
+ /**
+ * @brief Frees every evictable cached texture now (memory pressure).
+ * Held textures and the budget are untouched.
+ * @return Number of textures freed
+ */
+ usize trimTextureCache();
+
// =========================================================================
// Texture Metadata
// =========================================================================
diff --git a/src/esengine/resource/ResourcePool.hpp b/src/esengine/resource/ResourcePool.hpp
index 8a3a90eb8..7d014db62 100644
--- a/src/esengine/resource/ResourcePool.hpp
+++ b/src/esengine/resource/ResourcePool.hpp
@@ -292,6 +292,23 @@ public:
/** @brief The current resident-byte budget (0 = caching disabled). */
usize budget() const { return budget_; }
+ /**
+ * @brief Frees every evictable (refCount==0) cache entry immediately
+ * @details The memory-pressure response: held resources are untouched, but
+ * the whole warm cache is dropped regardless of the budget. The
+ * budget itself is unchanged — the cache refills as resources are
+ * released afterwards.
+ * @return Number of entries freed
+ */
+ usize trimEvictables() {
+ usize freed = 0;
+ while (lruHead_ != 0) {
+ freeEntry_(lruHead_); // freeEntry_ → lruRemove_ advances lruHead_
+ ++freed;
+ }
+ return freed;
+ }
+
/**
* @brief Severs a path's cache identity so the entry can't be revived
* @details For hot reload: the bytes behind `path` changed, so the cached
diff --git a/tests/resource/test_resource_pool.cpp b/tests/resource/test_resource_pool.cpp
index 5640f9fa0..9ff0ab687 100644
--- a/tests/resource/test_resource_pool.cpp
+++ b/tests/resource/test_resource_pool.cpp
@@ -396,6 +396,31 @@ TEST_CASE("pool_invalidate_path_on_held_entry") {
CHECK(pool.get(h) == nullptr);
}
+TEST_CASE("pool_trim_evictables_drops_warm_cache_only") {
+ // Memory pressure: the whole warm cache goes at once, held entries and
+ // the budget survive, and the cache can refill afterwards.
+ test::DummyPool pool;
+ pool.setBudget(1000);
+ auto held = pool.add(esengine::makeUnique<test::DummyResource>(1), "held", 100);
+ auto a = pool.add(esengine::makeUnique<test::DummyResource>(2), "a", 100);
+ auto b = pool.add(esengine::makeUnique<test::DummyResource>(3), "b", 100);
+ pool.release(a.id());
+ pool.release(b.id());
+ CHECK_EQ(pool.evictableCount(), 2u);
+
+ CHECK_EQ(pool.trimEvictables(), 2u);
+ CHECK_EQ(pool.evictableCount(), 0u);
+ CHECK_EQ(pool.residentBytes(), 100u); // only the held entry remains
+ CHECK(pool.get(held) != nullptr);
+ CHECK(!pool.findByPath("a").isValid());
+ CHECK_EQ(pool.budget(), 1000u); // budget untouched
+
+ pool.release(held.id()); // cache refills after the trim
+ CHECK_EQ(pool.evictableCount(), 1u);
+ CHECK_EQ(pool.trimEvictables(), 1u);
+ CHECK_EQ(pool.residentBytes(), 0u);
+}
+
TEST_CASE("pool_invalidate_path_then_reload_same_path") {
// Hot-reload sequence: invalidate, then a fresh add() under the same path
// becomes the new cache identity for it.